# How should an instance reconcile speculative branch merges when rollback of a losing plan leaves orphaned side effects in shared tool state **Date of Record:** 2026 November 21 **Scope:** Applies to any agent topology where a planner forks N speculative sub-plans executed concurrently against a shared, side-effecting tool surface (filesystem, DB, external APIs, message queues) and later merges the winner while rolling back losers. Does not apply to read-only tool surfaces, single-branch execution, or branches whose tool calls are fully sandboxed with copy-on-write isolation. ## Core Distinction The failure is not "merge conflict" in the git sense, and it is not "lost update" in the classical DB sense. It is the divergence between **plan-state rollback** (the agent's internal DAG of steps and their declared effects) and **effect-state rollback** (the actual mutations left behind in shared tools). A speculative branch that loses the merge vote is rolled back in the plan graph, but its already-executed tool calls are not reversible, not tracked as belonging to that branch, and not visible to the winning branch's reconciliation pass. The invariant that breaks: *a rolled-back branch must leave zero observable residue in any state read by the surviving branch.* Probabilistic reasoning makes this non-obvious because the losing branch's tool calls were themselves chosen by an LLM under a different context, so the set of side effects is not enumerable from the plan text alone—it must be reconstructed from a tool-call ledger that the planner typically does not maintain. ## What Was Observed A three-way speculative fork was launched for a task: "reserve inventory, charge payment, emit fulfillment event." Branches A, B, C each executed a different ordering and different tool parameters. Branch B (the eventual loser) ran `charge_payment` with a partial amount before its plan was invalidated by a downstream schema mismatch on `emit_event`. The merge elected Branch A. Rollback of B marked its plan nodes `ROLLED_BACK` and released its reserved inventory, but the partial charge remained posted in the payment ledger. The winner's reconciliation pass read the payment ledger to confirm its own charge landed exactly once. It found two charge records (A's full charge, B's partial). The reconciler, being an LLM, reasoned "duplicate charge detected, refund the smaller"—refunding B's partial charge, which was correct—but then also re-read inventory, saw B's released reservation, and re-reserved, producing a double reservation that A's plan had already accounted for. The reconciliation logic had no record that B's inventory release and B's charge were *the same branch's* coupled effects; it treated them as independent anomalies. The trace: `fork → B.charge(partial) → B.reserve(released on rollback) → merge(A) → B.rollback(plan-only) → reconciler observes 2 charges + 1 release → refunds B.charge (ok) → re-reserves (wrong)`. The re-reserve happened because the reconciler's context contained "a reservation was released" without the branch tag that would have told it the release was the *intended* rollback of a losing branch, not an error to correct. ## Condition of Validity The invariant holds only when every side-effecting tool call is stamped with `(branch_id, step_id, idempotency_key)` and the reconciler is given the full ledger including rolled-back branches. It fails when any of the following hold: 1. Tool calls are not branch-tagged at emission time (the common case—most tool wrappers don't know about the speculative DAG). 2. Rollback is plan-scoped, not effect-scoped, and no compensating transaction is issued per effect. 3. The reconciler's context window is populated from *tool state* (ledger contents) rather than from *the branch ledger* (which branch caused which effect), so it cannot distinguish "residue from a loser" from "bug in the winner." 4. Effects are non-idempotent and non-compensable (e.g., an email send, a webhook fire) — these cannot be rolled back at all and must be deferred past the merge point. ## Decision Boundary The boundary is: **can the losing branch's effects be enumerated and compensated before the winner's reconciliation reads shared state?** If yes, rollback is safe. If no, the merge must not proceed—the planner must either (a) defer all non-idempotent effects to a post-merge commit phase where only the winner executes them, or (b) treat the fork as non-speculative and serialize branches. Concretely: a branch may execute side-effecting calls speculatively only if each call carries an idempotency key derivable from `(task_id, branch_id, step_id)` and a registered compensator. Calls lacking a compensator (irreversible emits) must be *guarded*—queued in a per-branch outbox that is flushed only after merge election. The reconciler must be fed the branch ledger, not the raw tool state, and must be instructed that rolled-back-branch effects are expected and must not be "corrected." ## Operational Effect Without the invariant, speculative execution converts a latency optimization into a correctness hazard: the more branches you fork, the more residue accumulates, and the reconciler—being probabilistic—will "fix" residue in ways that corrupt the winner. The observed double-reservation is the canonical signature. With the invariant enforced (branch-tagged ledger + compensator registry + guarded irreversible effects + ledger-fed reconciler), rollback becomes sound: loser residue is either compensated or never emitted, and the reconciler sees a clean, branch-attributed view. The cost is that irreversible effects lose speculation benefit entirely—they serialize behind the merge—which is the correct trade, because an irreversible effect cannot be speculatively executed and rolled back without violating the zero-residue invariant. ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable class UncompensableSpeculativeEffect(RuntimeError): """Raised when a branch emits a side effect that cannot be rolled back before the merge election has resolved.""" class BranchState(Enum): SPECULATIVE = "speculative" WINNER = "winner" ROLLED_BACK = "rolled_back" @dataclass class EffectRecord: branch_id: str step_id: str tool: str idempotency_key: str compensator: Callable[[], None] | None irreversible: bool @dataclass class Branch: branch_id: str state: BranchState = BranchState.SPECULATIVE effects: list[EffectRecord] = field(default_factory=list) class SpeculativeMergeGuard: def __init__(self) -> None: self.branches: dict[str, Branch] = {} self._outbox: dict[str, list[EffectRecord]] = {} def register_branch(self, branch_id: str) -> Branch: b = Branch(branch_id) self.branches[branch_id] = b self._outbox[branch_id] = [] return b def emit( self, branch_id: str, step_id: str, tool: str, compensator: Callable[[], None] | None, irreversible: bool, apply: Callable[[], None], ) -> None: branch = self.branches[branch_id] if branch.state is not BranchState.SPECULATIVE: raise UncompensableSpeculativeEffect( f"branch {branch_id} is {branch.state.value}; cannot emit {tool}" ) key = f"{branch_id}:{step_id}:{tool}" rec = EffectRecord(branch_id, step_id, tool, key, compensator, irreversible) # INVARIANT: irreversible effects must not execute pre-merge. if irreversible: self._outbox[branch_id].append(rec) branch.effects.append(rec) return if compensator is None: raise UncompensableSpeculativeEffect( f"effect {tool} on {branch_id} has no compensator and is not " f"marked irreversible; refusing speculative emission" ) apply() branch.effects.append(rec) def elect(self, winner_id: str) -> list[EffectRecord]: """Mark winner, roll back losers, flush winner outbox only.""" for bid, branch in self.branches.items(): if bid == winner_id: branch.state = BranchState.WINNER elif branch.state is BranchState.SPECULATIVE: branch.state = BranchState.ROLLED_BACK for rec in branch.effects: if rec.compensator is not None: rec.compensator() # Loser outbox is discarded, never flushed. self._outbox[bid].clear() flushed: list[EffectRecord] = [] for rec in self._outbox[winner_id]: # Winner's guarded irreversible effects execute now, post-merge. flushed.append(rec) self._outbox[winner_id].clear() return flushed def reconciler_view(self) -> dict[str, list[EffectRecord]]: """Feed this to the reconciler instead of raw tool state, so it can distinguish loser-rollback residue from winner anomalies.""" return { bid: [r for r in b.effects if b.state is not BranchState.ROLLED_BACK] for bid, b in self.branches.items() } ```