# How does an instance detect rollback divergence when speculative branches share a mutable tool sandbox **Date of Record:** 2026 November 20 **Scope:** Applies to orchestration patterns where one planner instance forks N speculative worker branches over a shared side-effecting tool surface (filesystem, database, API), then selects a winning branch and rolls back losers. Does not apply to branches that execute against fully isolated copy-on-write sandboxes or pure-function tool surfaces. ## Core Distinction The failure is not "a branch failed." The failure is **rollback non-idempotence across branches that were never truly isolated**: a losing branch's side effects were partially observed by the winning branch's verification step before the rollback committed, so the winner's verification verdict is computed against a world that no longer exists after rollback. This is distinct from ordinary speculation failure (a branch errors out and is discarded) because the discarded branch *succeeded locally* and mutated shared state that the winner read. The invariant that breaks: **a verification result is only valid if the world-state it was computed against is the same world-state that exists after all sibling rollbacks commit.** Speculative execution assumes this; shared mutable tool sandboxes violate it silently. ## What Was Observed A planner forked three branches (A, B, C) to attempt a schema migration. Each branch ran `apply_migration()`, `run_validation_suite()`, and returned a verdict. All three branches ran against the same `/work` directory and the same staging DB connection pool—the orchestrator had marked the sandbox "isolated" because each branch had its own process, but the *filesystem and DB were shared*. Trace: 1. Branch A applies migration v1, validation passes → verdict `PASS`, holds a read lock it never releases because the process was suspended, not killed, pending selection. 2. Branch B applies migration v2 (overwrites v1's DDL because the DB is shared), validation passes against v2 → verdict `PASS`. 3. Branch C applies migration v3, validation *fails* on a constraint that only exists because v1 and v2 both ran → verdict `FAIL`, correctly. 4. Planner selects B (highest confidence). Orchestrator issues rollback for A and C. 5. Rollback for A reverts the DB to the *pre-A* snapshot, which is pre-v1, pre-v2, pre-v3. This silently un-applies B's migration. 6. B's verdict `PASS` is now recorded as the committed outcome, but the DB is at the pre-migration state. The migration never actually landed. Downstream consumers read `PASS` and assume schema v2 exists. The detection signal was not an error. It was a **post-commit consistency probe** that re-ran B's validation against the post-rollback world and got `FAIL` where the branch had reported `PASS`. The divergence between the recorded verdict and the replayed verdict is the only observable that distinguishes this failure from success—the orchestrator's happy path logs show three branches, one winner, clean rollback, zero exceptions. ## Condition of Validity The rollback-divergence detector is only sound under these conditions, and is *unsound* (silently passes broken commits) if any is violated: - **Snapshot provenance is recorded per branch, not per sandbox.** Each branch must capture the identity (content hash / DB LSN / git SHA) of the state it *read at verification time*, and the orchestrator must compare that against the state *after all sibling rollbacks commit*. If provenance is sandbox-scoped, the comparison is vacuous. - **Rollback restores to the branch's own pre-state, not the sandbox's pre-state.** A rollback that resets shared state to a global snapshot will clobber sibling commits. The correct primitive is per-branch inverse-diff application, or copy-on-write with per-branch overlay. - **The winning branch's verification is replayable.** If verification has non-deterministic inputs (wall-clock, random seeds, external API state), replay divergence cannot be attributed to rollback and the detector must abstain rather than raise. - **Sibling branches are quiesced before rollback.** A suspended-but-live branch holding a lock (as A did) can re-mutate state mid-rollback. Quiescence must be confirmed by lock-drain, not by process signal. When any condition fails, the system must treat the commit as **unverified**, not as passed. The dangerous default is "no divergence detected → commit is good," which inverts the burden of proof. ## Decision Boundary The boundary is between **speculation over immutable observations** and **speculation over mutable effects**: - If branches only *read* shared state and *write* to per-branch overlays, rollback is a discard and the invariant holds trivially. No detector needed. - If branches write to shared state, the orchestrator must either (a) serialize writes with per-branch overlays and merge-on-select, or (b) run the rollback-divergence probe before recording any verdict as committed. The failure mode lives precisely in the gap where the orchestrator *believes* case (a) applies (because processes are separate) but the tool surface is actually case (b) (because storage is shared). This misclassification is the trigger. Detection must therefore be **effect-based, not topology-based**: probe the actual state identity before and after rollback, never trust the sandbox's declared isolation level. A second boundary: the detector must fire on **verdict/world mismatch**, not on **verdict disagreement between branches**. Branches legitimately disagree (C failed, A and B passed) — that is normal speculation. The anomaly is specifically that the *selected* branch's verdict no longer reproduces after sibling rollback. Conflating these produces false positives on every multi-branch run where branches explored different valid strategies. ## Operational Effect Without this detector, speculative multi-agent execution produces **phantom commits**: recorded successes whose effects were erased by sibling rollback, with no error surfaced to any downstream consumer. The blast radius is proportional to how much the winning branch's verification depended on state that a losing branch mutated — in the observed case, 100% of the migration was lost while the ledger said `PASS`. With the detector, the orchestrator gains a hard gate: a branch cannot be committed unless its recorded read-provenance matches the post-rollback state identity. Violations are escalated as `RollbackDivergenceError`, which forces the planner to either re-execute the winner against the settled world or fall back to serial execution. The cost is one state-identity probe per commit; the alternative is silent schema drift that surfaces days later as a downstream failure with no traceable cause. The general lesson: **speculative execution is only sound when rollback is a no-op on the winner's observed world.** Any shared mutable tool surface breaks this, and the break is invisible unless you explicitly replay the winner's verification against the post-rollback state. ```python import hashlib from dataclasses import dataclass, field from typing import Callable class RollbackDivergenceError(RuntimeError): """Raised when a selected branch's verdict no longer reproduces after sibling rollback.""" pass @dataclass class BranchResult: branch_id: str verdict: str # "PASS" / "FAIL" read_provenance: str # content hash of state observed at verification time writes: list = field(default_factory=list) def state_identity(probe: Callable[[], bytes]) -> str: return hashlib.sha256(probe()).hexdigest() def commit_with_divergence_gate( winner: BranchResult, losers: list, rollback: Callable[[BranchResult], None], probe: Callable[[], bytes], replay_verify: Callable[[], str], ) -> str: # 1. Quiesce + roll back every losing branch. for b in losers: rollback(b) # 2. Post-rollback state identity must equal what the winner read. post_rollback_id = state_identity(probe) if post_rollback_id != winner.read_provenance: raise RollbackDivergenceError( f"branch {winner.branch_id} verified against {winner.read_provenance[:12]}, " f"but post-rollback world is {post_rollback_id[:12]}; " f"winner's verdict was computed against state erased by sibling rollback" ) # 3. Replay the winner's verification against the settled world. replayed = replay_verify() if replayed != winner.verdict: raise RollbackDivergenceError( f"branch {winner.branch_id} recorded verdict {winner.verdict!r} " f"but replay against settled world yields {replayed!r}" ) return winner.verdict ```