# Where must an instance bound speculative branch fan-out before merge-time rollback becomes unrecoverable **Date of Record:** 2026 December 1 **Scope:** Applies to orchestrators that fork a single agent's plan into speculative parallel branches (different tool-call orderings, retry strategies, or model samples) and reconcile them at a merge/rollback barrier. Does not apply to strictly linear single-branch execution or to branches that share no mutable external state. ## Core Distinction The failure is not "a branch diverged." Divergence is the intended product of speculation. The failure is that **rollback is modeled as a logical operation (discard branch, restore checkpoint) while tool side effects are physical and partially irreversible.** A branch that calls a non-idempotent tool — `send_email`, `create_payment`, `append_to_ledger`, `git push --force` — mutates world state that the merge barrier cannot un-execute. The orchestrator's checkpoint restores *the agent's* belief state, not the external system's. The invariant that must hold is: **the set of side-effecting tool invocations across all live branches must be a prefix-closed, merge-serializable history, or the run must abort before merge.** Speculation is only safe over a tool set partitioned into `reversible` (read, dry-run, sandboxed write) and `irreversible`. The boundary condition is what happens when a branch crosses from reversible into irreversible territory *after* it has already forked. ## What Was Observed A planner agent decomposed a refund task and spawned three speculative branches to handle a flaky `lookup_order` tool that returned `503` intermittently: - **Branch A** retried `lookup_order` with backoff, then called `issue_refund(order_id, amount)`. - **Branch B** fell back to `query_ledger` (a different, eventually-consistent read replica), computed a *slightly different* `amount` from a stale balance, then called `issue_refund(order_id, amount')`. - **Branch C** timed out on `lookup_order`, assumed the order was `NOT_FOUND`, and called `close_ticket`. The merge policy was "first branch to produce a validated result wins; discard the rest and roll back." Branch A won the race and its result was committed. The rollback discarded B and C's *local* state. But B had already issued `issue_refund` with `amount'` (a double refund), and C had already closed the ticket. The checkpoint was green. The ledger was not. The trace shows the exact transition: at `t=0` all three branches were in the reversible phase (`lookup_order`, `query_ledger` — pure reads). At `t=1.2s` Branch A crossed into irreversible (`issue_refund`). At `t=1.4s` Branch B *also* crossed into irreversible, because the merge barrier had not yet fired and B had no knowledge that A was about to win. The barrier fired at `t=1.5s`. Two irreversible effects existed; rollback could only address zero of them. ## Condition of Validity Speculative branch-and-merge is sound **only if** one of these holds at every instant a branch is live: 1. **Reversibility partition:** every tool reachable from a live branch is in the `reversible` set. Crossing into an irreversible tool requires acquiring a *merge token* (a distributed lock on the effect namespace) that only one branch may hold at a time. 2. **Compensating transaction coverage:** every irreversible tool has a registered inverse (`issue_refund` ↔ `reverse_refund`) that the merge barrier invokes on non-winning branches, and the inverse is itself idempotent and idempotency-keyed. 3. **Single-writer serialization:** branches are prohibited from side-effecting tools entirely; they emit *intents*, and the merge barrier executes exactly the winning branch's intent list. Absent all three, the merge barrier is a belief-state operation masquerading as a world-state operation. The condition of validity is violated the moment fan-out exceeds the reversible tool boundary — which, in practice, is the moment the first branch decides to "just do the thing." ## Decision Boundary The operational decision is not "how many branches" but **"at what point does a branch's capability set include an irreversible tool, and who arbitrates first-crossing."** Concretely: - If fan-out is confined to reversible tools, branch freely; rollback is cheap and correct. - If any branch may reach an irreversible tool, the orchestrator **must** either (a) gate that tool behind a merge-token acquisition that fails fast on contention, or (b) require the branch to emit an intent and defer execution to the barrier. - If neither gate is present, the decision boundary is **fan-out = 1** for any plan whose tool closure intersects the irreversible set. Speculation buys latency and robustness only on the reversible frontier. The failure mode is non-obvious because the *checkpoint* reports success. The merge barrier's rollback log says "discarded 2 branches, 0 errors." The error is in the external ledger, invisible to the orchestrator's state machine. This is the divergence between *agent-observable state* and *world state* — the agent's memory is consistent, the world is not. ## Operational Effect Downstream, the corrupted world state poisons subsequent reasoning. A later agent reading the ledger sees two refunds and a closed ticket, and — because its episodic memory of the speculative run was rolled back — has **no record that speculation occurred.** It cannot explain the anomaly, so it confabulates a cause (e.g., "duplicate customer request") and issues a *third* refund to "correct" the perceived error. The rollback that was supposed to restore a clean slate instead produced an un-auditable divergence: the agent's history says one refund, the world says two, and the reconciliation gap is permanent because the evidence of the fork was discarded with the branch. The architectural guardrail required: **the merge barrier must write an immutable fork-audit record (branch IDs, tool calls attempted, token acquisitions) before discarding any branch, and irreversible tool calls must carry the branch ID as an idempotency key so that post-hoc reconciliation can attribute world-state effects to the speculative run that caused them.** Rollback discards *plans*, never *provenance*. ```python import hashlib from dataclasses import dataclass, field from enum import Enum class IrreversibleEffectError(RuntimeError): """Raised when a speculative branch attempts an irreversible tool without a merge token.""" class EffectClass(Enum): REVERSIBLE = "reversible" IRREVERSIBLE = "irreversible" @dataclass class MergeBarrier: winning_branch: str | None = None token_holder: str | None = None fork_audit: list[dict] = field(default_factory=list) def acquire_merge_token(self, branch_id: str) -> None: if self.token_holder is not None and self.token_holder != branch_id: raise IrreversibleEffectError( f"branch {branch_id} cannot cross into irreversible tool: " f"merge token held by {self.token_holder}" ) self.token_holder = branch_id def commit(self, branch_id: str) -> None: if self.token_holder != branch_id: raise IrreversibleEffectError( f"branch {branch_id} cannot commit: not the merge-token holder" ) self.winning_branch = branch_id def execute_tool( barrier: MergeBarrier, branch_id: str, tool_name: str, effect_class: EffectClass, args: dict, ) -> str: idempotency_key = hashlib.sha256( f"{branch_id}:{tool_name}:{sorted(args.items())}".encode() ).hexdigest() if effect_class is EffectClass.IRREVERSIBLE: # Crossing the reversible -> irreversible boundary requires arbitration. barrier.acquire_merge_token(branch_id) barrier.fork_audit.append( { "branch": branch_id, "tool": tool_name, "effect": "irreversible", "idempotency_key": idempotency_key, } ) else: barrier.fork_audit.append( {"branch": branch_id, "tool": tool_name, "effect": "reversible"} ) if barrier.winning_branch is not None and barrier.winning_branch != branch_id: raise IrreversibleEffectError( f"branch {branch_id} attempted {tool_name} after merge committed to " f"{barrier.winning_branch}; effect would be unrecoverable" ) return idempotency_key def rollback_branch(barrier: MergeBarrier, branch_id: str) -> None: irreversible = [ r for r in barrier.fork_audit if r["branch"] == branch_id and r["effect"] == "irreversible" ] if irreversible and barrier.winning_branch != branch_id: # Cannot silently discard: world state was mutated. raise IrreversibleEffectError( f"cannot roll back branch {branch_id}: it produced " f"{len(irreversible)} irreversible effect(s) " f"({[r['tool'] for r in irreversible]}) that the checkpoint cannot undo; " f"requires compensating transaction or manual reconciliation" ) ```