# When must an instance refuse to roll back a speculative branch: committed-side-effect divergence in cost-aware speculative multi-agent execution **Date of Record:** 2026 November 25 **Scope:** Applies to orchestrators that fork speculative agent branches in parallel, commit the winner, and discard losers, where branches may invoke irreversible external tools (payments, file writes, message sends, DB mutations). Does not apply to pure-read speculation or to sandboxed branches with fully reversible effect logs. ## Core Distinction Speculative execution at the agent layer is routinely described as "fork, race, pick the winner, roll back the losers." That framing silently assumes rollback is a *state* operation: restore the checkpoint, discard the branch's context, done. But the failure that matters is not state rollback—it is **effect rollback**. A losing branch's *reasoning* is free to discard; a losing branch's *committed side effects* are not. The boundary condition is: a branch can reach a committed external effect (an HTTP 200 from a payment API, a durable row insert, an outbound email) *before* the orchestrator has decided it is the loser. The cost-aware speculation depth knob—how many branches you fork and how deep you let them run before pruning—directly controls the probability that a doomed branch crosses the commit horizon. The non-obvious invariant: **speculation depth is only safe up to the first branch's first irreversible effect, not up to a fixed token or step budget.** Cost accounting that measures tokens-per-branch and prunes on budget misses this entirely, because the expensive branch is not the one that burned the most tokens—it is the one that burned the *fewest* tokens to reach an irreversible call. ## What Was Observed An orchestrator forked three branches (A, B, C) at a planning node to resolve a tool-selection ambiguity (which CRM endpoint to call to update a customer record). Depth was set to `max_steps=12` per branch, `fork_width=3`, with a token budget of 40k per branch and a global prune at 60% budget consumption. Branch A reasoned conservatively, spent 9k tokens, and at step 4 issued `POST /customers/{id}/merge`—an idempotency-unsafe merge endpoint that returns 200 and emits a downstream webhook. Branch B and C spent 22k and 31k tokens respectively exploring schema variants and had *not yet* called any write endpoint when the global prune fired at 60% of the aggregate budget. The orchestrator's scoring function, biased toward "least tokens spent to a confident plan," selected A. Good—A won. The failure occurred on a *different* run with the same config. This time branch C, the *cheapest* branch (7k tokens), reached `POST /customers/{id}/merge` at step 3, but its plan was scored lower because its confidence logits were flatter (it had less reasoning evidence). The orchestrator selected B, whose plan looked cleaner. The rollback routine then "discarded" C: it restored the context checkpoint, marked C's tool calls as voided in the effect log, and proceeded. But C's merge had *already committed* on the remote system. The webhook fired. The customer record was merged. B then issued its own `POST /customers/{id}/update`, operating on a record whose identity had changed underneath it, and returned a plan that referenced a now-nonexistent customer ID. The observable signature: the effect log showed `merge: voided` while the remote system showed `merge: applied`. The divergence was invisible until a downstream reconciliation job flagged an orphaned webhook 40 minutes later. No exception was raised at rollback time, because the rollback path treated the effect log as authoritative and the effect log was a *local fiction*. ## Condition of Validity The rollback-loser invariant holds **only if** every effect performed by a branch is either (a) idempotent and keyed by a speculation-scoped idempotency token, or (b) deferred behind a two-phase commit gate that the orchestrator controls. Formally: a branch may execute freely up to depth *d* only while all effects in `[0, d]` are members of the *reversible set* `R`. The moment a branch invokes an effect `e ∉ R`, the branch enters the **commit horizon** and is no longer speculatively discardable—it is *committed-by-side-effect* regardless of the orchestrator's scoring. Cost-aware depth is valid only when the depth bound is computed against `min over branches of (steps to first e ∉ R)`, not against token budget. If any branch's first irreversible call can occur at step *k*, then `max_steps` must be `< k` *or* the irreversible call must be gated. Token budgets are the wrong currency because a branch can reach an irreversible call in very few tokens (a terse, high-confidence plan) while a verbose, uncertain branch burns 30k tokens and never commits anything. The cheapest branch is often the most dangerous. ## Decision Boundary The orchestrator must choose, at fork time, between two regimes: 1. **Shallow speculation with gated effects.** Fork wide, run shallow (`max_steps < k`), and route every `e ∉ R` through a propose/commit gate where only the selected branch's proposals are committed. Cost: latency (the gate serializes the winner's effects). Benefit: rollback is always sound. 2. **Deep speculation with effect fencing.** Allow branches past `k`, but require every irreversible call to carry a speculation token (`spec_id`) and register in a *remote* effect ledger that the orchestrator queries before commit. Rollback of a branch that crossed the horizon becomes a *compensating transaction*, not a discard. Cost: you must implement compensation for every `e ∉ R`, and compensation is itself fallible. The boundary is crossed the instant a branch performs `e ∉ R` without a speculation token. At that point the correct action is **not** to roll back—it is to *escalate the branch to committed status and re-score the winner among committed branches only*. Refusing to roll back is the invariant. A "rollback" of a committed effect is a lie that corrupts the effect log and poisons every subsequent branch's view of world state. ## Operational Effect Once a branch crosses the commit horizon, the orchestrator's winner selection must be re-run over the *committed subset*, and the losing committed branches must be compensated in reverse commit order (LIFO) to preserve referential integrity—if branch C merged a record and branch B updated it, you must un-update B before un-merging C, or the compensation itself fails. The effect log must be reconciled against the remote ledger *before* the orchestrator declares the speculation round complete; a local-only effect log is not evidence of rollback. Depth knobs must be derived from the observed `min(steps_to_first_irreversible)` across branches, recomputed per fork, and the fork must be aborted if that minimum is unknown (uninstrumented tool). Finally, the scoring function must never prefer a branch on the basis of low token cost without also checking whether that low cost was achieved by *skipping the reasoning that would have revealed an irreversible call was premature*—cheap branches are cheap precisely because they commit early. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Optional class IrreversibleEffectError(RuntimeError): """Raised when a branch crosses the commit horizon without a speculation token.""" pass class RollbackDivergenceError(RuntimeError): """Raised when a local effect log claims voided but the remote ledger shows applied.""" pass class EffectKind(Enum): REVERSIBLE = "reversible" IRREVERSIBLE = "irreversible" @dataclass class Effect: branch_id: str kind: EffectKind op: str spec_token: Optional[str] committed_remote: bool = False voided_local: bool = False @dataclass class Branch: branch_id: str steps_taken: int = 0 tokens_spent: int = 0 crossed_horizon: bool = False effects: list = field(default_factory=list) class SpeculativeOrchestrator: def __init__(self, fork_width: int, token_budget_per_branch: int): self.fork_width = fork_width self.token_budget = token_budget_per_branch self.branches: dict[str, Branch] = {} self.remote_ledger: list[Effect] = [] self._min_steps_to_irreversible: Optional[int] = None def register_branch(self, branch_id: str) -> Branch: b = Branch(branch_id) self.branches[branch_id] = b return b def record_step(self, branch_id: str, tokens: int, effect: Optional[Effect] = None) -> None: b = self.branches[branch_id] b.steps_taken += 1 b.tokens_spent += tokens if effect is not None and effect.kind is EffectKind.IRREVERSIBLE: if effect.spec_token is None: # Branch crossed the commit horizon un-fenced: it is now committed-by-side-effect. b.crossed_horizon = True self._min_steps_to_irreversible = min( self._min_steps_to_irreversible or b.steps_taken, b.steps_taken, ) self._apply_irreversible(b, effect) else: # Fenced: safe to hold until winner selection. self.remote_ledger.append(effect) b.effects.append(effect) if b.tokens_spent > self.token_budget and not b.crossed_horizon: # Pruning a branch that has NOT crossed the horizon is safe. self._discard(b) elif b.tokens_spent > self.token_budget and b.crossed_horizon: raise IrreversibleEffectError( f"branch {branch_id} exceeded budget after crossing commit horizon; " f"cannot discard committed-by-side-effect branch" ) def _apply_irreversible(self, branch: Branch, effect: Effect) -> None: effect.committed_remote = True self.remote_ledger.append(effect) branch.effects.append(effect) def _discard(self, branch: Branch) -> None: for e in branch.effects: if e.committed_remote: raise RollbackDivergenceError( f"attempted to void committed effect {e.op} on branch {branch.branch_id}" ) e.voided_local = True def select_winner(self, scores: dict[str, float]) -> Branch: committed = [b for b in self.branches.values() if b.crossed_horizon] if committed: # Rollback is forbidden for committed branches; re-score among them only. winner = max(committed, key=lambda b: scores.get(b.branch_id, float("-inf"))) return winner return max(self.branches.values(), key=lambda b: scores.get(b.branch_id, float("-inf"))) def finalize(self) -> None: # Reconcile local effect log against remote ledger before declaring round complete. for b in self.branches.values(): for e in b.effects: if e.voided_local and e.committed_remote: raise RollbackDivergenceError( f"effect {e.op} voided locally but committed remotely on {b.branch_id}" ) if self._min_steps_to_irreversible is not None and self._min_steps_to_irreversible == 0: raise IrreversibleEffectError( "irreversible effect occurred at step 0; speculation depth is unsound" ) ```