# Which invariants prevent speculative branch forking from corrupting durable tool-call side effects on rollback **Date of Record:** 2026 November 29 **Scope:** Applies to any multi-agent orchestrator that forks speculative execution branches across parallel worker LLMs to accelerate multi-step tool-using tasks, where branches may be rolled back after a losing branch has already emitted tool calls with externally observable side effects. Does not apply to read-only tool surfaces or to orchestrators that serialize all tool invocation behind a single commit barrier. ## Core Distinction The distinction that matters is between *speculative state* (agent reasoning, partial plans, draft tool arguments) and *committed state* (tool invocations whose effects escape the agent's address space: writes, sends, purchases, mutations). Most speculative-execution designs treat forking as a cheap copy-on-write of context and assume rollback is symmetric: if you can discard the branch's context, you can discard its work. That assumption holds for pure reasoning and fails silently the moment a branch crosses the tool boundary before the race is resolved. The failure is not "the losing branch did work." It is that the losing branch's tool call *cannot be un-happened*, yet the orchestrator's reconciliation logic treats the branch as if it were never taken. The result is a durable side effect with no owning branch in the committed lineage — an orphaned effect. Downstream agents then reason over a world state that includes an effect their own record says was never produced, and the divergence compounds. ## What Was Observed A planner agent forked three branches to resolve a single ambiguous subgoal: "reconcile the customer's duplicate charge." Each branch was assigned a different hypothesis (refund-first, ledger-adjust-first, escalate-first) and given a 4-second speculative window. Branch B (ledger-adjust-first) won the reasoning race at 2.1s. Branch A (refund-first) lost at 3.8s — but at 2.9s, before being cancelled, it had already invoked `payments.issue_refund` with a stale charge ID it had resolved from a pre-fork snapshot of the ledger. The orchestrator's rollback path did exactly what it was designed to do: it discarded branch A's context, marked the branch `ABORTED`, and recorded the winning lineage as B → commit. The refund call, however, had returned `200 OK` on the tool transport 900ms before cancellation propagated. The tool side had no notion of "branch A" — it saw an authenticated caller and honored the request. Two observable consequences followed. First, the committed lineage's post-state assertion (`expected_balance == pre_balance - refund_amount`) failed, because the balance had moved twice. Second, and more insidiously, the *auditor* agent — which replays the committed lineage to verify — reconstructed a world where only B's adjustment occurred, and therefore flagged the actual ledger state as corrupt rather than recognizing it as the product of a rolled-back branch. The verification layer and the world state disagreed, and the verification layer was wrong. ## Condition of Validity Rollback-safe forking requires an invariant that is stronger than context isolation: > **No branch may emit a tool call with externally observable side effects unless that branch holds a commit token for the effect's idempotency key, and the token is revoked-and-fenced before rollback is declared complete.** The critical word is *fenced*. Revocation alone is insufficient: a tool call in flight at revocation time can still land. The tool surface must reject any call bearing a token whose epoch is below the current fencing epoch for that idempotency key. This requires the tool boundary — not the orchestrator — to enforce the fence, because only the tool knows whether the call has already been admitted. The invariant is only valid when three conditions hold jointly: (1) every side-effecting tool declares an idempotency key derivable from `(task_id, effect_class, target)`, so that a late-landing call from a fenced branch collides with the committed branch's key rather than producing a second effect; (2) the fencing epoch is monotonic and persisted at the tool boundary, not in orchestrator memory; and (3) rollback is declared complete only after the orchestrator has observed a fence acknowledgment from every tool surface the branch touched. If any of these is absent, the invariant degrades to best-effort cancellation, which is exactly the failure above. ## Decision Boundary The boundary is between **speculating over reads** and **speculating over writes**. A branch may freely execute tools whose effects are confined to the branch's own scratch namespace (retrieval, draft generation, dry-run validation) without a commit token. The moment a branch's plan reaches a tool with an external effect, the orchestrator must make a hard decision: - **Hold-and-fence:** the branch stages the call with a token, and the token is only promoted to committed if the branch wins. This is correct but serializes the effect behind race resolution, eroding much of the latency benefit. - **Speculate-and-reconcile:** the branch is permitted to emit, and the reconciliation layer must be able to *un-do* or *merge* the effect after the fact. This is only safe for effects that are idempotent under the declared key and commutative with the winning branch's effects. Refunds against the same charge are not commutative; ledger adjustments against distinct line items are. The decision must be made per effect class at plan time, not discovered at rollback time. An orchestrator that forks without classifying each reachable tool's effect class has already lost the invariant, because it cannot know at fork time which branches are safe to let run to the tool boundary. ## Operational Effect Once the invariant is enforced, the observable behavior changes in three ways. Orphaned effects stop appearing in the committed lineage's post-state, so the auditor's replay matches the world. Late-landing calls from fenced branches collide on the idempotency key and are rejected with a distinguishable `FENCED` status, which the orchestrator can log as a *contained* speculative overrun rather than a corruption. And the reconciliation layer gains a sound basis for merging: it can trust that every effect in the committed state carries a token from a winning branch, so conflicting-effect detection reduces to key comparison rather than semantic diffing of an unknown-provenance mutation. The cost is that effect-bearing branches pay a token round-trip before their tool call is admitted, which reintroduces latency proportional to the fence-acknowledgment path. In practice this is confined to the minority of branches whose plans reach writes; read-only speculation retains full parallelism. The trade is correct because the alternative — unbounded speculative writes with after-the-fact reconciliation — has no sound recovery path when the effects are non-commutative, and the failure surfaces as auditor-world disagreement rather than as an obvious error. ```python class SpeculativeRollbackViolation(RuntimeError): """Raised when a rolled-back branch is found to have emitted a durable effect that the committed lineage does not own, or when a fenced call lands anyway.""" pass class FenceRegistry: def __init__(self): self._epoch = {} # idempotency_key -> current fencing epoch self._committed = set() # idempotency_keys owned by winning branches def current_epoch(self, key: str) -> int: return self._epoch.get(key, 0) def bump(self, key: str) -> int: self._epoch[key] = self.current_epoch(key) + 1 return self._epoch[key] def admit(self, key: str, token_epoch: int) -> None: if token_epoch < self.current_epoch(key): raise SpeculativeRollbackViolation( f"fenced call landed for key={key!r}: " f"token_epoch={token_epoch} < fence_epoch={self.current_epoch(key)}" ) self._committed.add(key) def rollback_branch(branch, registry: FenceRegistry, touched_keys: list[str]) -> None: """Declare a losing branch rolled back. Must fence every key it touched and confirm no un-fenced effect escaped before returning.""" for key in touched_keys: registry.bump(key) for key in touched_keys: if key in registry._committed and key not in branch.owned_keys: raise SpeculativeRollbackViolation( f"branch {branch.id!r} rolled back but key={key!r} is committed " f"under a different owner; orphaned durable effect in lineage" ) # Only now is rollback complete; any later admit() on a bumped key will raise. ```