# How should an instance reconcile rollback state when speculative agent branches commit side effects to a shared external substrate before divergence is detected **Date of Record:** 2026 November 28 **Scope:** Applies to orchestrators that fork a task into N speculative branches (parallel agent instances exploring alternative plans), each branch permitted to invoke tools with external side effects, where a single winning branch is selected and the losers are "rolled back." Does not apply to read-only speculative execution, pure in-context tree search, or branches confined to a transactional sandbox with true ACID semantics. ## Core Distinction The failure here is not "a loser branch did something bad." It is that **rollback of a speculative branch is not the inverse of its execution**, because the substrate the branch touched is non-transactional and its effect is *observable to the winner*. Teams conflate two different guarantees: - **Execution rollback**: discarding the loser's context, KV cache, and pending tool calls. This is cheap, deterministic, and always succeeds. - **Substrate rollback**: undoing the external mutations the loser already committed (a file written, a row inserted, an email queued, a remote API called). This is expensive, often impossible, and — critically — *not idempotent in reverse*. The invariant that actually matters is not "losers leave no trace." It is: **the winner must never observe a substrate state that a loser produced, and the divergence detector must fire before the first non-compensable side effect, not before the first divergent token.** When those two orderings disagree, you get a *phantom commit*: a side effect from a branch that was never selected, silently absorbed into the winner's world model. ## What Was Observed A planning task was forked into four branches at step 3, each branch running the same tool-using agent against a shared workspace (a scratch filesystem plus a mock ticketing API). Branch selection was deferred until all branches reached a terminal state, then a scorer picked the branch with the highest plan-validity score. Divergence was detected at step 5 of branch B — it had chosen to "reset the staging config" while branches A, C, D chose "inspect the staging config." By the time the scorer ran, branch B had already: 1. Written `staging.yaml` with a mutated `replicas: 0` (step 5). 2. Called `POST /tickets` to open a change-request referencing that config (step 6). 3. Read its own ticket back at step 7 and concluded the change was "approved" (a hallucinated inference, but grounded in a real object it had created). Branch A won. The orchestrator discarded B's context and marked B's workspace writes for rollback. It restored `staging.yaml` to `replicas: 3`. It did **not** delete the ticket — the rollback handler had no compensating action registered for `POST /tickets`, because ticket creation was assumed "read-mostly." The winner, branch A, then ran its own verification step, listed open tickets, found B's change-request, and incorporated it into its final answer as evidence that "a prior change was already in flight." The winner's output was contaminated by a branch that lost. The trace that made this legible: the loser's side effect appeared in the winner's tool-result stream with no provenance marker. From the winner's perspective it was indistinguishable from a legitimate pre-existing substrate fact. ## Condition of Validity Rollback-on-divergence is only sound when **all three** hold: 1. **Divergence precedes effect.** The detector fires strictly before the loser's first non-compensable mutation. In practice this requires the branch to *declare intent* (a dry-run / plan object) and have the orchestrator gate the actual commit — i.e., speculative branches run against a *shadow substrate* whose commits are buffered, not applied. 2. **Effect is attributable.** Every substrate mutation carries a branch ID and a speculation epoch, so the winner's reads can filter out mutations from non-selected branches. Without this, the winner cannot distinguish phantom commits from real pre-state. 3. **Compensation is total or the effect is quarantined.** For every tool in the branch's action space, either a registered inverse exists (and is verified to actually invert), or the effect is written to a quarantine namespace the winner never reads. The observed incident violated all three: divergence was detected at token-level (step 5) but effects had already been applied at step 5–7 against the live substrate; mutations were unattributed; and `POST /tickets` had no inverse. ## Decision Boundary The orchestrator must choose, per tool, between two regimes and must not blur them: - **Speculate-and-commit-late** (default for any tool with non-compensable effects): the branch produces a *proposed* call; the orchestrator applies it only after the branch is selected. Cost: branches cannot observe their own side effects, so any branch whose plan depends on reading back a mutation must be restructured to reason over the proposal, not the result. - **Speculate-and-commit-early** (permitted only for tools with a verified, tested inverse, e.g., `write_file` with a captured prior-content snapshot): the branch commits immediately and rollback replays the inverse. This requires the inverse to be *tested against the actual tool*, not assumed. The boundary is the tool's **invertibility class**, not its read/write label. A "read" that has side effects (a `GET` that increments a counter, a search that logs a query, a ticket lookup that creates a session) belongs in the commit-late regime. The failure above happened precisely because the team classified `POST /tickets` as low-risk and let it commit early without an inverse. A second boundary: **the winner must not begin execution until all loser compensations have resolved to a terminal state** (applied or explicitly quarantined). If the winner starts while a loser's compensation is in flight, the winner can race the rollback and read a half-restored substrate. This is a happens-before edge, not a performance hint. ## Operational Effect Concretely, the guardrail is a **speculation ledger** with per-branch effect records and a barrier: - Each branch runs with a `branch_id` and a `speculation_epoch`. - Every tool call is intercepted; the interceptor consults the tool's invertibility class. Compensable tools commit and record an inverse closure. Non-compensable tools are *staged* into a proposal buffer and return a synthetic `PENDING` result the branch must handle. - On selection, the orchestrator: (a) applies the winner's staged proposals, (b) replays loser inverses in reverse order, (c) blocks on a barrier until every inverse is applied or quarantined, (d) only then releases the winner to continue. - The winner's read path filters any substrate object tagged with a non-selected `branch_id` and a `speculation_epoch` ≤ current — those are phantoms and must raise, not be silently dropped, so the contamination is visible in the trace. The invariant to assert at the barrier: `∀ branch ∉ selected: ledger.effects(branch) ⊆ (applied_inverses ∪ quarantined)`. If any effect is neither inverted nor quarantined, the winner must not proceed — the correct behavior is to fail the task loudly rather than let the winner absorb a phantom commit. ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable class SpeculationRollbackError(RuntimeError): """Raised when a loser branch's effect cannot be inverted or quarantined before the winning branch is released to execute.""" class InvertibilityClass(Enum): COMPENSABLE = "compensable" # has a tested inverse; may commit early NON_COMPENSABLE = "non_compensable" # must be staged, applied only on selection @dataclass class Effect: branch_id: str tool: str inverse: Callable[[], None] | None quarantined: bool = False applied: bool = False @dataclass class SpeculationLedger: effects: list[Effect] = field(default_factory=list) def record(self, effect: Effect) -> None: self.effects.append(effect) def unresolved_for(self, branch_id: str) -> list[Effect]: return [ e for e in self.effects if e.branch_id == branch_id and not e.quarantined and not (e.applied and e.inverse is not None) ] def resolve_barrier(ledger: SpeculationLedger, selected: str, all_branches: list[str]) -> None: """Enforce: every loser effect is inverted or quarantined before the winner runs.""" for branch in all_branches: if branch == selected: continue for effect in ledger.unresolved_for(branch): if effect.inverse is None: # No inverse registered: must be quarantined, never silently ignored. raise SpeculationRollbackError( f"branch {branch} committed non-invertible effect via " f"{effect.tool!r} with no compensating action and no quarantine; " f"winner {selected!r} would observe a phantom commit" ) try: effect.inverse() effect.applied = True except Exception as exc: # inverse itself failed raise SpeculationRollbackError( f"inverse for {effect.tool!r} on branch {branch} raised {exc!r}; " f"substrate is in an indeterminate state" ) from exc # Barrier: reaching here means the winner may safely execute. ```