# Why does an instance fork speculative branches that individually pass but merge into an inconsistent state: the cross-branch invariant gap in fan-out orchestration **Date of Record:** 2026 November 30 **Scope:** Applies to any orchestrator that fans a single task into N speculative agent branches (parallel plans, redundant tool-call paths, or candidate edits), validates each branch in isolation, and merges the survivors. Does not apply to strictly sequential single-branch execution, nor to fan-out where branches operate on disjoint, provably non-interacting state partitions. ## Core Distinction The failure is not "a branch produced wrong output." Every branch can be locally correct, pass its own verifier, and still be *jointly* inconsistent with its siblings. The distinction that matters is between **per-branch validity** (each branch satisfies the task predicate against its own private world-state snapshot) and **cross-branch consistency** (the merged result satisfies the predicate against the *union* of all branches' side effects). Orchestrators routinely conflate these because the verifier is invoked per-branch, in a fresh context, against the state the branch *believed* it operated on—not against the state that will exist after merge. A second distinction: merge is not a commutative set-union over outputs. It is a *replay* of each branch's effect sequence against a shared base. Two branches that each "append a config key" or "rename a symbol" or "insert a schema field" are individually idempotent but jointly contradictory. The merge operator must therefore be a consistency-checked reduction, not a concatenation, and the check must run on the *recombined* state, which no branch ever observed. ## What Was Observed A fan-out of width 5 was launched to refactor a module: each branch received the same base snapshot (commit `S0`), the same task predicate `P`, and an independent tool sandbox. Each branch ran to completion, ran its own verifier, and reported `PASS` with a diff `Δᵢ` and a final self-state `Sᵢ = apply(S0, Δᵢ)`. The orchestrator selected the three branches with the highest self-reported confidence and merged by replaying `Δ₁, Δ₂, Δ₃` in confidence order against `S0`. The merged state `S_merged` failed `P`. Individually, `apply(S0, Δ₁)`, `apply(S0, Δ₂)`, `apply(S0, Δ₃)` all passed. The trace showed the mechanism precisely: - `Δ₁` renamed function `f` to `f_async` and updated its 4 call sites. - `Δ₂` added a new call site to `f` (using the original name) as part of a feature the branch was told to scaffold. - `Δ₃` deleted a now-unused import that `Δ₂`'s new call site transitively required. Each branch verified against `S0`. `Δ₁`'s verifier saw 4 call sites and no others; `Δ₂`'s verifier saw `f` defined (it was, in `S0`); `Δ₃`'s verifier saw the import unused (it was, in `S0`). None of the three verifiers ever observed the state containing the *other* two diffs. The merge produced a state with a call to a function that no longer existed under that name, plus a missing import, and the post-merge verifier—which *did* run—was skipped because the orchestrator trusted the three `PASS` results and treated merge as a mechanical reduction with no re-validation. The non-obvious part: **the confidence ordering was anti-correlated with merge safety.** `Δ₁` had the highest confidence (largest diff, cleanest tests) and was replayed first, which meant `Δ₂`'s call site was applied *after* the rename and therefore could never be reconciled by a "last writer wins" rule. Had the order been reversed, the merge would still have been inconsistent but would have failed loudly at replay time (call to undefined symbol) rather than silently (call to a symbol that the rename had moved, leaving a dangling reference that only failed at runtime). ## Condition of Validity The per-branch `PASS` is a valid proxy for merge safety **only under an isolation invariant**: for all pairs `(i, j)`, the effect sets `E(Δᵢ)` and `E(Δⱼ)` must be *non-interfering*—i.e., they touch disjoint keys of the shared state, or the merge operator defines a total, order-independent reconciliation for every overlapping key. Formally, the merge is sound iff: ``` ∀ i, j: E(Δᵢ) ∩ E(Δⱼ) = ∅ OR reconcile(E(Δᵢ) ∩ E(Δⱼ)) is defined and total ``` In the observed incident, `E(Δ₁)` touched the symbol table key `f.name` and the 4 call-site keys; `E(Δ₂)` touched a *new* call-site key that referenced `f.name`; `E(Δ₃)` touched an import-table key. The intersection `E(Δ₁) ∩ E(Δ₂)` was non-empty on the *referenced* key `f.name` (one wrote it, one read-and-depended on it), and no reconciliation function existed for read-write interference—only for write-write. That is the gap: **most merge operators handle write-write conflicts and silently ignore write-read and read-write dependencies across branches**, because those dependencies are not visible in the diff, only in the *reachability graph* of the post-merge state. The invariant that restores validity: a branch's `PASS` may be promoted to a merge-eligible `PASS` only if the orchestrator can prove, for every other selected branch, that the branch's effect set is either disjoint from the other's *or* the merge operator has a defined, order-independent reconciliation for the overlap. When neither holds, the branch pair is *merge-conflicted by dependency*, and the correct action is to re-run the pair jointly (a reduced fan-out of width 2) rather than to merge speculatively. ## Decision Boundary The boundary between "merge the survivors" and "re-run the conflicted subset jointly" is crossed when the dependency-closure of the selected branches' effect sets is not a forest. Concretely, build a graph `G` whose nodes are the selected diffs and whose edges are dependency interferences (a write in one that a read-and-depend in another relies on, or a write-write on a key with no total reconciliation). Then: - If `G` is edgeless → merge directly; per-branch `PASS` is sound. - If `G` is a forest (no cycles) → merge in topological order of `G`, replaying each diff against the accumulated state of its predecessors, and **re-run the verifier on the accumulated state after each replay**. A `PASS` here is a *merge-conditional* `PASS`, not a branch `PASS`. - If `G` contains a cycle → no merge order is sound; collapse the cycle into a single joint branch and re-execute it as one agent with the union of the cycle's instructions. Do not attempt to resolve cycles by confidence ordering; confidence ordering is precisely what produced the silent failure above. The trap is the middle case: orchestrators that *do* have a topological order available still skip the per-replay re-validation, because the per-branch verifiers already returned `PASS` and re-running looks redundant. It is not redundant—it is the only check that ever observes the state the branch will actually inhabit. ## Operational Effect Three concrete changes bound the failure: 1. **Effect-set extraction before merge.** Each branch must report not just its diff but its *effect set*: the set of state keys it wrote, and the set of keys it read-and-depended on. The orchestrator intersects these to build `G`. A branch that cannot report its read-dependencies (e.g., because it used an opaque tool) is treated as touching *all* keys, forcing joint re-execution rather than a speculative merge. 2. **Merge-conditional verification.** The verifier is re-invoked against the accumulated post-replay state after every topological step. A branch's `PASS` is downgraded to `UNVERIFIED` the moment it is merged with any dependency-interfering sibling, until the accumulated state re-passes. The orchestrator's merge result is `PASS` only if the *final* accumulated state passes, never by conjunction of branch results. 3. **Cycle collapse, not confidence arbitration.** When `G` has a cycle, the cycle's branches are fused into one joint execution. This trades fan-out width for soundness and is the only correct resolution when reconciliation is undefined. The residual risk: a branch's read-dependency set is itself an approximation (the branch may depend on a key it never explicitly read, via a tool's side channel). The guardrail is to treat tool-mediated reads as "touches all keys," which over-collapses but never under-collapses—the safe direction. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Callable, Iterable class CrossBranchMergeError(RuntimeError): """Raised when speculative branches cannot be soundly merged.""" @dataclass(frozen=True) class Branch: name: str writes: frozenset[str] # state keys this branch wrote read_depends: frozenset[str] # keys it read-and-depended on opaque_tool: bool = False # if True, treat as touching all keys verified: bool = True # per-branch PASS, valid only against S0 def _effect_keys(b: Branch) -> frozenset[str]: if b.opaque_tool: return frozenset({"*"}) # conservative: touches everything return b.writes | b.read_depends def _interferes(a: Branch, b: Branch) -> bool: ea, eb = _effect_keys(a), _effect_keys(b) if "*" in ea or "*" in eb: return True # write-write on a shared key with no total reconciliation if a.writes & b.writes: return True # write-read / read-write dependency across branches if a.writes & b.read_depends or b.writes & a.read_depends: return True return False def build_dependency_graph(branches: Iterable[Branch]) -> dict[str, set[str]]: bs = list(branches) g: dict[str, set[str]] = {b.name: set() for b in bs} for i, a in enumerate(bs): for b in bs[i + 1:]: if _interferes(a, b): g[a.name].add(b.name) g[b.name].add(a.name) return g def _has_cycle(g: dict[str, set[str]]) -> bool: WHITE, GRAY, BLACK = 0, 1, 2 color = {n: WHITE for n in g} def dfs(n: str) -> bool: color[n] = GRAY for m in g[n]: if color[m] == GRAY: return True if color[m] == WHITE and dfs(m): return True color[n] = BLACK return False return any(color[n] == WHITE and dfs(n) for n in g) def plan_merge( branches: list[Branch], verify_accumulated: Callable[[frozenset[str]], bool], ) -> list[str]: """ Return a sound merge order, or raise CrossBranchMergeError. Per-branch `verified` is NOT trusted as a merge certificate; the accumulated state is re-verified after every replay step. """ g = build_dependency_graph(branches) if _has_cycle(g): # No merge order is sound; caller must collapse the cycle into # a single joint branch and re-execute. raise CrossBranchMergeError( "dependency cycle among branches; merge order undefined — " "collapse the cycle and re-run jointly" ) by_name = {b.name: b for b in branches} # topological order by interference degree (deterministic tiebreak) order: list[str] = [] remaining = set(g) accumulated_writes: set[str] = set() while remaining: ready = sorted( (n for n in remaining if not (g[n] & remaining)), key=lambda n: (len(g[n]), n), ) if not ready: raise CrossBranchMergeError( "topological sort stalled; graph not a forest" ) for n in ready: b = by_name[n] accumulated_writes |= set(_effect_keys(b)) if not verify_accumulated(frozenset(accumulated_writes)): # branch PASS does not survive merge with its siblings raise CrossBranchMergeError( f"branch {n!r} passed in isolation but accumulated " f"state fails verification after replay" ) order.append(n) remaining.discard(n) return order ```