# Why does an instance speculatively pre-execute tool calls across a branch-and-verify fan-out and then discover, at merge time, that the rollback of a losing branch has already leaked an irreversible side effect? **Date of Record:** 2026 November 24 **Scope:** Applies to any orchestration where a planner agent fans out N speculative sub-branches that each optimistically pre-execute tool calls (writes, sends, provisioning) before a verifier selects a winner and rolls back losers. Does not apply to pure read-only tool surfaces or to systems that route every side-effect through a deferred commit buffer with a single transactional boundary. ## Core Distinction There are two ways to make speculative execution "safe," and they are not equivalent: 1. **Compensable speculation** — every pre-executed effect has a registered inverse (delete the created record, refund the charge, cancel the reservation). Rollback is *undo*. 2. **Buffered speculation** — pre-executed effects are held in an uncommitted staging buffer and only *materialize* when the winning branch is selected. Rollback is *discard*. Most branch-and-verify stacks assume (1) while their verifier's semantics actually require (2). The failure is not that rollback fails; it is that rollback *succeeds at the wrong granularity*. A losing branch's compensating action runs against a world state that a *sibling* branch has already mutated, and the inverse no longer matches the forward operation. The invariant that silently breaks: **the compensation for effect E must be evaluated against the same world state that E saw, not the post-fan-out state.** When branches interleave, that precondition is violated and the "rollback" becomes a second forward effect disguised as an undo. ## What Was Observed A planner decomposed a provisioning task into three speculative branches: `A` reserves capacity, `B` reserves capacity plus emits a downstream notification, `C` reserves capacity and writes an audit record. All three optimistically pre-executed their `reserve()` calls against the same inventory pool in parallel, each reading `available = 10` at fan-out time (a stale snapshot — correct at read, invalid at commit). The verifier scored `B` highest and selected it. The orchestrator issued rollback to `A` and `C`. Each rollback called `release(reservation_id)`. But the reservation pool had *already* been overdrawn: three reservations of 4 units against 10 available. `B`'s reservation is the one that must survive; `A` and `C` release 4 each, restoring the pool to 8 — but the *true* committed state should be 6 (only `B`'s 4 consumed). The pool now reports 2 phantom units that do not exist. A later branch reads `available = 8`, reserves 8, and the system oversells by 2. The trace of the corrupting transition: ``` t0 snapshot: available=10 (read by A, B, C) t1 A.reserve(4) -> ok, available=6, resv=A1 t2 B.reserve(4) -> ok, available=2, resv=B1 t3 C.reserve(4) -> ok, available=-2, resv=C1 # overdraft accepted, no guard t4 verifier selects B t5 rollback A: release(A1) -> available=2 t6 rollback C: release(C1) -> available=6 # should be 6? no: B1 still holds 4 t7 post-merge read: available=6 WRONG (true committed = 6? see note) ``` The subtlety that makes this non-obvious: at `t7` the arithmetic *looks* right (10 − 4 = 6) but only because two errors cancelled — the overdraft at `t3` (−2) and the phantom release at `t6` (+4) happened to net out against the surviving `B1`. Under a different interleaving (e.g., `C` selected, `A` and `B` rolled back) the pool ends at 10 − 4 = 6 with `C1` holding 4 and a phantom +4 from double-release of a shared reservation handle. The bug is interleaving-dependent and therefore *not reproducible* from the planner's transcript — it only manifests when the fan-out timing shifts. ## Condition of Validity The compensating-rollback model is only sound when all four hold: - **Disjoint effect domains.** No two branches touch the same resource key, so compensations cannot alias. (Violated above: all three reserve from one pool.) - **Snapshot freshness at commit.** The pre-execution read is revalidated against the current state at the moment the effect materializes, not at fan-out. - **Idempotent, handle-scoped compensation.** `release(resv_id)` must target the *exact* reservation the branch created, and must be a no-op if that reservation was never committed or was already released. - **Verifier ordering.** Winner selection must complete before *any* loser compensation runs, so compensations see a stable post-selection state. The moment speculation is *optimistic* (pre-executes before selection) and the resource is *shared* (non-disjoint domains), conditions 1 and 4 are in tension: you cannot both pre-execute concurrently and have a stable post-selection state for compensation. That tension is the boundary. ## Decision Boundary The architect must choose, per tool surface, between two regimes and never blend them: - **Buffer regime** (default for shared, non-idempotent resources): pre-execution writes to a staging ledger keyed by `(branch_id, effect_id)`. Selection commits the winner's ledger entries and discards losers'. No compensating call is ever issued. Cost: latency — effects materialize only after verification. - **Compensate regime** (only for genuinely disjoint, idempotent, handle-scoped resources): pre-execution is real, and each effect registers an inverse bound to a unique handle. Safe only when the four conditions hold *and* the verifier is guaranteed to run before any compensation. The forbidden zone is **optimistic pre-execution on a shared resource with compensating rollback**. It is the configuration that produced the phantom units. Detect it statically: if a tool's effect domain intersects another branch's effect domain *and* the tool lacks a staging path, the planner must serialize those branches or refuse speculation. ## Operational Effect Enforce a commit-barrier invariant: no compensation may execute until the verifier has emitted a signed selection and a `post_selection_epoch` has been observed by every branch. Each pre-executed effect carries a `snapshot_epoch`; a compensation whose `snapshot_epoch` predates the selection epoch is rejected as stale rather than applied. The guardrail is not "roll back harder" — it is "refuse to compensate an effect whose world-state precondition has moved." ```python from dataclasses import dataclass from typing import Optional class StaleCompensationError(RuntimeError): """Raised when a rollback is attempted against a world state the effect never saw.""" @dataclass(frozen=True) class Effect: branch_id: str effect_id: str resource_key: str snapshot_epoch: int committed: bool = False class SpeculationLedger: def __init__(self) -> None: self._effects: dict[str, Effect] = {} self._selection_epoch: Optional[int] = None self._winner: Optional[str] = None def pre_execute(self, effect: Effect) -> None: # optimistic write; staged, not materialized self._effects[effect.effect_id] = effect def commit_selection(self, winner: str, epoch: int) -> None: self._selection_epoch = epoch self._winner = winner for eid, e in list(self._effects.items()): if e.branch_id == winner: self._effects[eid] = Effect( e.branch_id, e.effect_id, e.resource_key, e.snapshot_epoch, committed=True, ) def compensate_loser(self, effect_id: str) -> None: e = self._effects.get(effect_id) if e is None: raise StaleCompensationError(f"unknown effect {effect_id}") if self._selection_epoch is None: raise StaleCompensationError( "compensation attempted before verifier selection; " "world state is not yet stable" ) if e.snapshot_epoch < self._selection_epoch: # the effect was pre-executed against a pre-selection snapshot; # its inverse no longer matches current state -> do NOT apply raise StaleCompensationError( f"effect {effect_id} snapshot_epoch={e.snapshot_epoch} " f"< selection_epoch={self._selection_epoch}; " "compensation would alias a sibling mutation" ) if e.committed: raise StaleCompensationError( f"effect {effect_id} belongs to winner {self._winner}; " "cannot compensate a committed effect" ) # discard instead of undo — buffered regime del self._effects[effect_id] ```