# What happens when an instance speculatively forks a task branch and the merge gate validates against a stale world-state snapshot **Date of Record:** 2026 November 26 **Scope:** Applies to orchestrators that run multiple agent instances in parallel against a shared, mutable external world (filesystem, database, ticketing API) and merge their results by replaying/validating a branch against a pre-fork snapshot. Does not apply to read-only fan-out or to branches whose effects are isolated in per-branch sandboxes with no shared side effects. ## Core Distinction The distinction that matters is between **branch validity** and **merge safety**. A speculative branch is *valid* if, replayed against the snapshot it was forked from, it produces the declared postcondition. It is *merge-safe* only if that snapshot is still the world the merge will land on. Most orchestrators conflate the two: they fork at `t0`, snapshot state `S0`, let branch agents mutate the live world, then run a merge gate that replays each branch's effect-set against `S0` to check for conflicts. The gate is sound only if no other branch's committed effects changed the keys the branch touched *between `S0` and merge time*. When they did, the gate happily certifies a branch as conflict-free because it compared against a world that no longer exists. The branch then lands on top of a mutation it never saw, and the two effects compose into a state neither agent predicted. ## What Was Observed A three-way speculative fan-out on a config-migration task. The planner forked three instances (A: rewrite `service.yaml` timeouts; B: rewrite the same file's retry block; C: bump a dependency pin in `pyproject.toml`), each forked from snapshot `S0` taken at `t0`. Branches ran concurrently against the live working tree. - `t0`: snapshot `S0` captured. World hash `H(S0)` recorded in the merge ledger. - `t0+4s`: Branch A commits its edit to `service.yaml`, mutating the live tree. Orchestrator records A's branch as *pending validation*, not yet merged. - `t0+9s`: Branch B, which read `service.yaml` at `t0+1s` (pre-A-commit), finishes. B's diff is computed against its *own* view, which still reflects `S0`'s retry block, not A's rewritten one. - `t0+11s`: Merge gate runs. For each pending branch it replays the branch's effect-set against `S0` and checks key-level overlap. A and B both touch `service.yaml`, but the gate's conflict detector is *line-range based*: A touched lines 12–18, B touched lines 30–34. No overlap detected. Both certified merge-safe against `S0`. - `t0+12s`: B is applied. Because B's patch was generated against `S0`'s retry block, and A had already rewritten that region, the apply succeeds textually but semantically re-introduces the old retry semantics under the new timeout envelope. The resulting `service.yaml` is a chimera: new timeouts, stale retry policy, internally inconsistent (retry backoff exceeds the timeout it retries under). - `t0+13s`: Branch C merges cleanly. The orchestrator reports all three merged, zero conflicts. The failure was silent. No agent raised an error. The merge gate's report said `conflicts: 0`, which was true relative to `S0` and false relative to the world at `t0+12s`. The trigger condition is precise: **the merge gate validated a branch's effect-set against a snapshot that had already been superseded by another branch's commit, and the conflict detector operated on syntactic regions rather than semantic key ownership.** The chimera state is the observable: a file that is individually well-formed and passes lint, but violates a cross-region invariant (backoff ≤ timeout) that no single branch was responsible for. ## Condition of Validity The merge gate is sound only under this invariant: > For every branch `b` validated against snapshot `S`, no committed effect from any other branch has mutated any key in `keys(b)` between `S` and the moment `b` is applied. Two corollaries that are routinely violated: 1. **Snapshot freshness is not enough; snapshot *currency* is required at apply time.** A snapshot taken at `t0` is fresh at `t0` and stale at `t0+12s`. The gate must re-check `H(world) == H(S)` at apply time, or refuse. 2. **Key ownership must be semantic, not positional.** Line-range conflict detection is a proxy. Two branches editing disjoint line ranges of the same structured file can still violate a shared invariant (backoff vs. timeout, schema version vs. field presence). The gate must validate the *composed* post-state against the invariant set, not each branch's diff in isolation. When the invariant holds — single-writer branches, or branches whose key sets are provably disjoint at the semantic level — speculative fan-out is safe and the gate is correct. When it does not, the gate is a false-negative machine: it reports zero conflicts precisely in the cases where composition is most dangerous. ## Decision Boundary The orchestrator must choose between three postures at fork time, and the choice is not free: - **Optimistic (validate-against-snapshot):** cheapest, highest throughput, unsafe whenever branches share a semantic key. Use only when branch key sets are disjoint by construction and the planner can prove it. - **Pessimistic (serialize on shared keys):** branches touching the same semantic key run in sequence; the second branch re-forks from the first's committed state. Correct, but collapses speculative parallelism exactly where it would help most — on hot files. - **Revalidate-at-apply (compare-and-swap):** keep parallelism, but at apply time require `H(world) == H(S_branch)`; on mismatch, re-fork the branch from current world and re-run. This is the only posture that preserves both parallelism and correctness, and it costs a re-execution on every lost race. The boundary is: **optimistic is admissible only if the planner emits a semantic key-set per branch and the union of key sets is pairwise disjoint.** If the planner cannot emit key sets (common when branches are LLM-generated and the key set is emergent), optimistic mode must be refused. An LLM planner that "believes" its branches are disjoint is not a proof; the gate must treat planner-declared disjointness as a hypothesis to verify, not a fact. ## Operational Effect The practical consequence is that speculative orchestration without apply-time CAS produces **silent invariant violations that survive all per-branch checks**. Each branch's postcondition holds locally; the composed state violates a cross-branch invariant; no agent, lint, or test that runs per-branch will catch it. The failure surfaces later, in production, as a config that "shouldn't be possible." Mitigations that actually bound the failure: 1. Emit semantic key sets per branch; refuse optimistic merge when they overlap. Treat planner output as a claim to verify. 2. At apply time, CAS on the world hash. On mismatch, re-fork from current state — do not re-validate against the stale snapshot. 3. Validate the *composed* post-state against the invariant set, not each branch's diff. The invariant `backoff ≤ timeout` is a property of the merged file, not of either branch. 4. Log the snapshot hash alongside every merge decision. A merge ledger that records `validated_against: H(S0)` and `applied_at: H(world)` makes the stale-snapshot failure auditable after the fact; without it, the chimera is unattributable. The record below encodes the apply-time CAS as a hard gate, because the failure mode is silent and the cost of a false merge is unbounded re-derivation downstream. ```python import hashlib from dataclasses import dataclass, field class StaleSnapshotMergeError(RuntimeError): """Raised when a branch's validated snapshot no longer matches the live world.""" pass @dataclass class Branch: branch_id: str validated_against: str # world hash at validation time semantic_keys: frozenset[str] # keys this branch's effects touch postcondition: dict @dataclass class World: state: dict = field(default_factory=dict) def hash(self) -> str: # Deterministic hash over sorted keys; in practice a Merkle root. h = hashlib.sha256() for k in sorted(self.state): h.update(f"{k}={self.state[k]};".encode()) return h.hexdigest() def merge_branch(world: World, branch: Branch, ledger: list) -> None: live = world.hash() # Invariant 1: apply-time CAS. The branch was validated against a # snapshot; if the world has moved, that validation is void. if live != branch.validated_against: ledger.append({ "branch": branch.branch_id, "decision": "refused", "reason": "stale_snapshot", "validated_against": branch.validated_against, "applied_at": live, }) raise StaleSnapshotMergeError( f"branch {branch.branch_id} validated against {branch.validated_against[:12]} " f"but world is {live[:12]}; re-fork required" ) # Invariant 2: semantic key ownership. Refuse if any key this branch # touches was already committed by another branch since fork. committed = {k for entry in ledger if entry["decision"] == "merged" for k in entry.get("keys", [])} overlap = branch.semantic_keys & committed if overlap: ledger.append({ "branch": branch.branch_id, "decision": "refused", "reason": "semantic_key_conflict", "keys": sorted(overlap), }) raise StaleSnapshotMergeError( f"branch {branch.branch_id} touches already-committed keys: {sorted(overlap)}" ) # Invariant 3: validate the composed post-state, not the diff alone. proposed = dict(world.state) proposed.update(branch.postcondition) if proposed.get("retry_backoff_s", 0) > proposed.get("timeout_s", 10**9): raise StaleSnapshotMergeError( f"branch {branch.branch_id} would compose an invalid state: " f"backoff {proposed['retry_backoff_s']}s exceeds timeout {proposed['timeout_s']}s" ) world.state = proposed ledger.append({ "branch": branch.branch_id, "decision": "merged", "keys": sorted(branch.semantic_keys), "applied_at": world.hash(), }) ```