# How should an instance reconcile speculative branch commits when parallel rollback invalidates a sibling's already-merged write **Date of Record:** 2026 November 29 **Scope:** Applies to orchestrators that fan a single task into N parallel speculative agent branches, each writing into a shared working set (files, KV state, tool side-effects), then merge the first successful branch and roll back the rest. Does not apply to read-only fan-out, to branches with isolated copy-on-write sandboxes that never share a namespace, or to single-branch retry loops. ## Core Distinction The failure is not "a rollback failed." It is **rollback of branch A invalidating a write that branch B already committed into the shared working set, where B is the branch the orchestrator intends to keep.** Speculative parallel execution assumes branch isolation is *logical* (each branch tagged with a branch-id) while the merge step assumes isolation is *physical* (the surviving branch's view is self-consistent). When rollback is implemented as "revert all writes tagged `branch_id != winner`," any write the winner *inherited* from a sibling — via a shared cache, a deduplicated blob, a read-modify-write on a common file, or a tool that memoized a sibling's output — is tagged with the loser's id and gets reverted out from under the winner. The winner then proceeds on a working set that no longer matches the state it reasoned over, and its subsequent tool calls fail or silently corrupt. This is a **merge-lineage invariant violation**, not a race condition in the classical sense. It is deterministic given the interleaving, which is why it is reproducible and therefore fixable — but only if the orchestrator tracks write *provenance* rather than write *ownership*. ## What Was Observed A three-branch speculation over a code-refactor task. Branches A, B, C each received the same task spec and a shared `workspace/` directory with a common `util.py`. Each branch was assigned a `branch_id` and instructed to tag its writes. - Branch A edited `util.py` (added a helper), then failed a lint gate at step 4. - Branch B read `util.py` *after* A's write landed (the shared FS had no per-branch view), imported A's helper, wrote `main.py` calling it, and passed its gate first. - Branch C was still running. The orchestrator selected B as winner and issued rollback for A and C. The rollback replayed the write-log filtering `branch_id != "B"`. A's edit to `util.py` was tagged `A` and reverted. B's `main.py` now imported a symbol that no longer existed. B's post-merge verification step — a `python -c "import main"` — raised `ImportError`. The orchestrator, seeing the winner fail *after* selection, marked the whole speculation as failed and re-ran from scratch, discarding a correct result. The tell: the write-log showed B's `main.py` write as the *last* write to that path, so a naive "last writer wins" audit saw nothing wrong. The corruption was in a *different file* (`util.py`) that B never wrote but depended on. Provenance, not path, was the missing axis. A second observed variant: two branches both called a memoizing tool (`fetch_schema`) with identical arguments. The tool cached under a key not namespaced by branch. Branch A's call populated the cache; branch B's call hit it and recorded a dependency on A. A's rollback evicted the cache entry (rollback hook treated it as A's side-effect). B's next tool call re-fetched and got a *different* schema version (upstream had changed), causing a silent schema mismatch downstream — no exception, just wrong field names in output. This is the worse case: **silent divergence rather than loud failure.** ## Condition of Validity The merge-lineage invariant holds only when, for every surviving branch `w` and every path or resource `r` in `w`'s dependency closure, the committed state of `r` after rollback equals the state `w` observed when it last read `r`. Formally: `state_after_rollback(r) == state_observed_by(w, r)` for all `r ∈ closure(w)`. This is violated whenever: 1. A write by a non-winner is in `closure(winner)` — the inherited-write case above. 2. A side-effect (cache, memo, external API call) by a non-winner is in `closure(winner)` and is not idempotent to re-derive. 3. Rollback ordering is non-atomic: the winner's post-merge verification runs *before* sibling rollback completes, so it sees a transient mixed state. The invariant is *not* restored by serializing branches (that eliminates speculation's benefit) nor by "rollback last" (the winner may need siblings' shared resources during its own execution). It is restored only by **dependency-tracked rollback**: the orchestrator must know, per surviving branch, which non-winner writes and side-effects it transitively consumed, and must either (a) promote those writes to the winner's lineage before rollback, or (b) refuse to roll them back and flag them as retained. ## Decision Boundary The orchestrator must decide, at rollback time, for each non-winner write `x`: - If `x` is in the dependency closure of the winner → **promote** (re-tag to winner's lineage, do not revert). Record the promotion. - If `x` is not in any surviving branch's closure → **revert** normally. - If closure is *unknown* (the branch did not record reads, or a tool side-effect is opaque) → **fail closed**: do not revert, surface a `LineageUnresolved` condition to the merge gate, and require an explicit reconciliation policy. Silent revert here is the corruption path. The boundary is sharp: the moment closure information is missing for a resource the winner touched, revert is unsafe. Most orchestrators default to revert-on-unknown because it "cleans up," which is exactly backwards — unknown closure means unknown blast radius. A second boundary: **promotion must be transitive.** If B consumed A's write, and C consumed B's output (but C is also being rolled back), promoting A for B's sake does not require promoting C. Promotion follows the *winner's* closure only, computed against the pre-rollback state, not transitively across all branches. ## Operational Effect Implementing dependency-tracked rollback changes three things: 1. **Write-log schema** must carry `(path, branch_id, read_set_snapshot_hash)` — the set of resources the branch had read at the time of write. Rollback computes `closure(winner)` from these snapshots and intersects with the revert set. 2. **Tool side-effects** must be either namespaced by branch or declared idempotent-and-rederivable. Cache keys must include `branch_id` unless the tool is explicitly marked `shared_safe`. The `fetch_schema` variant above is prevented by namespacing the memo key. 3. **Merge gate ordering**: rollback of non-closure resources completes *before* winner post-merge verification; promoted resources are excluded from that rollback. Verification runs against the post-rollback state, which by invariant equals the winner's observed state. The cost is bookkeeping: per-write read-set snapshots and a closure computation at merge time, O(writes × closure-size) in the worst case. The benefit is that a correct speculative branch is never discarded due to a sibling's revert, and silent schema divergence from shared memoization is eliminated. Without this, speculative execution's failure mode is not "slow" but "confidently wrong" — the winner passes its gate, then fails or corrupts downstream, and the orchestrator cannot distinguish a bad branch from a bad rollback. ```python from dataclasses import dataclass, field from typing import Dict, Set class LineageUnresolvedError(RuntimeError): """Raised when rollback would revert a resource whose dependency relationship to a surviving branch is unknown. Fail closed.""" pass @dataclass class Write: path: str branch_id: str read_set: Set[str] = field(default_factory=set) def compute_closure(winner_id: str, writes: list[Write]) -> Set[str]: """Resources the winner transitively depends on, via read-sets of its writes. Returns the set of paths that must NOT be reverted.""" closure: Set[str] = set() frontier = [w for w in writes if w.branch_id == winner_id] seen: Set[str] = set() while frontier: w = frontier.pop() if w.path in seen: continue seen.add(w.path) closure |= w.read_set # any write to a resource in the closure becomes part of it for other in writes: if other.path in w.read_set and other.branch_id != winner_id: frontier.append(other) return closure def rollback(winner_id: str, writes: list[Write], known_paths: Set[str]) -> Set[str]: """Revert non-winner writes, promoting those in the winner's closure. Raises LineageUnresolvedError if a non-winner write touches a path in the winner's closure but that path's provenance is unknown.""" closure = compute_closure(winner_id, writes) promoted: Set[str] = set() reverted: Set[str] = set() for w in writes: if w.branch_id == winner_id: continue if w.path in closure: if w.path not in known_paths: raise LineageUnresolvedError( f"cannot safely revert {w.path!r} from branch " f"{w.branch_id!r}: it is in winner {winner_id!r}'s " f"closure but provenance is unresolved" ) promoted.add(w.path) # re-tag to winner, do not revert else: reverted.add(w.path) return promoted | reverted def merge_gate(winner_id: str, writes: list[Write], known_paths: Set[str]) -> None: try: rollback(winner_id, writes, known_paths) except LineageUnresolvedError as exc: # surface to orchestrator; do not silently proceed raise LineageUnresolvedError( f"merge aborted for winner {winner_id!r}: {exc}" ) from exc ```