# Which invariants prevent speculative branch contamination during multi-agent rollback **Date of Record:** 2026 November 24 **Scope:** Applies to orchestrators that fan out speculative sub-agents against a shared, mutable effect surface (file system, database, external API, or message bus) and roll back losing branches when outcomes diverge. Does not apply to pure read-only fan-out, nor to single-agent retry loops where no concurrent branch shares an effect surface. ## Core Distinction The failure is not "rollback didn't happen." The failure is that rollback is *logically correct within the orchestrator's state model but physically incomplete on the effect surface*, and a surviving branch's subsequent reads observe the residue of a branch that was supposed to have never existed. Speculative execution assumes an **isolation invariant**: the observable state after `rollback(B)` equals the observable state before `spawn(B)`, for every surviving branch `A`. Teams typically verify this against the orchestrator's own transaction log and declare success. But sub-agents are probabilistic actors that write through *unmediated* channels — a `bash` tool, an HTTP `POST`, a cache `SET`, a vector-store upsert — and those channels are not enrolled in the orchestrator's rollback ledger unless explicitly wrapped. The invariant that actually matters is **effect-surface closure**: every write reachable by a sub-agent must be either (a) journaled with a compensating action, or (b) routed to a copy-on-write overlay that the orchestrator alone can merge or discard. The non-obvious part: contamination survives even a *perfect* orchestrator rollback, because the contaminating write often happens in a *tool result the losing branch already returned upstream* — the orchestrator rolls back the branch's declared effects but keeps the branch's transcript for audit, and a surviving branch or a later distillation step reads that transcript and treats its content as ground truth. ## What Was Observed A planner spawned three speculative sub-agents to fix a failing migration: `A` (schema rewrite), `B` (data backfill), `C` (index rebuild). Each ran in a nominal sandbox. `A` and `B` diverged on the target column type; the orchestrator's consensus check selected `A` and issued `rollback(B)`. Observed trace: 1. `B` had executed `UPDATE migrations SET col_type='bigint' WHERE id=42` through a DB tool whose calls were *not* journaled — the tool wrapper logged to the transcript but did not register a compensating action. The orchestrator's rollback ledger for `B` contained only `B`'s file edits, not its DB writes. 2. `rollback(B)` reverted `B`'s files, marked `B` as `ROLLED_BACK`, and — critically — **retained `B`'s transcript in the shared episodic store** for audit, tagged `branch=B, status=rolled_back`. 3. `A` continued, then called a retrieval step to check "what did we learn about column 42?" The retriever ranked `B`'s transcript chunk highly (it was the most lexically similar passage) and injected `col_type='bigint'` into `A`'s context as an *unattributed* fact. 4. `A` wrote a migration asserting `bigint`, contradicting its own earlier `integer` decision. The effect surface now contained `B`'s un-rolled-back DB write *and* `A`'s corroborating migration — two mutually reinforcing artifacts, one of which officially "never happened." 5. A downstream auditor agent, replaying the run, saw a consistent `bigint` world and passed verification. The divergence was invisible to replay because both the residue and the contamination were *self-consistent*. The contamination was discovered only when a later migration on a clean environment failed against the `integer` assumption that the *original* pre-speculation state implied. ## Condition of Validity The isolation invariant `state_after_rollback(B) == state_before_spawn(B)` holds **only if all four of the following are simultaneously true**: - **Effect closure.** Every sub-agent write path is enrolled in the rollback ledger or the COW overlay. Any unmediated tool (shell, raw HTTP, cache, vector upsert) breaks closure silently. - **Transcript quarantine.** A rolled-back branch's transcript is *not* retrievable by surviving branches during the same run. Audit retention must be namespaced behind a barrier the retriever cannot cross. - **Provenance tagging at injection.** Any fact entering a surviving branch's context carries its source branch and status; facts from `ROLLED_BACK` branches are either excluded or explicitly marked as counterfactual. - **Replay determinism over the residue.** Verification must replay against the *effect surface*, not the transcript, or it will certify contaminated-but-consistent states. If any one is false, the invariant is unprovable and rollback is cosmetic. ## Decision Boundary The orchestrator must choose between two regimes and never blend them: - **Sealed speculation:** sub-agents run against a COW overlay / journaled effect surface with transcript quarantine. Rollback is cheap and the isolation invariant is enforceable. Cost: overlay merge complexity and higher write latency. - **Open speculation:** sub-agents write directly to the live surface; rollback is *not* claimed. Divergent branches are reconciled by forward-compensation (an explicit `undo` sub-agent whose own writes are journaled), and transcripts are treated as first-class shared state, never discarded. The boundary is crossed the moment a sub-agent's tool set includes an unmediated write path. At that instant, "rollback" must be downgraded to "forward-compensation" or the tool must be wrapped. Declaring `ROLLED_BACK` while an unjournaled write exists is the specific defect. A useful guard: before issuing rollback, the orchestrator must prove `journaled_writes ⊇ observed_writes` for the branch; if it cannot, it must refuse to mark the branch rolled back and escalate to compensation. ## Operational Effect Unenforced, this produces **resurrection contamination**: rolled-back state re-enters the surviving branch through (a) un-rolled-back effect residue read by a tool, or (b) transcript leakage into retrieval. The signature is a run that replays cleanly, passes audit, and fails only against an environment that never saw the speculation. The blast radius is asymmetric — the longer `A` runs after contamination, the more of its own writes corroborate the false fact, and the harder the divergence is to localize on replay. The durable guardrail is to make `ROLLED_BACK` an *unprovable-by-default* status: a branch may only be marked rolled back if the orchestrator can enumerate and compensate every observed write, and its transcript is fenced from all surviving retrievers for the remainder of the run. ```python from dataclasses import dataclass, field from enum import Enum class BranchStatus(Enum): ACTIVE = "active" ROLLED_BACK = "rolled_back" COMPENSATING = "compensating" class RollbackContaminationError(RuntimeError): """Raised when a branch is marked rolled back while unjournaled effect-surface writes remain, or when a rolled-back transcript is reachable by a surviving branch.""" @dataclass class Branch: name: str status: BranchStatus = BranchStatus.ACTIVE observed_writes: set = field(default_factory=set) # every write the branch attempted journaled_writes: set = field(default_factory=set) # writes with a registered compensator transcript_fenced: bool = False def assert_rollback_safe(branch: Branch, surviving: list[Branch]) -> None: # Invariant 1: effect-surface closure unjournaled = branch.observed_writes - branch.journaled_writes if unjournaled: raise RollbackContaminationError( f"branch {branch.name!r} has {len(unjournaled)} unjournaled writes " f"{sorted(unjournaled)}; rollback would be cosmetic, escalate to compensation" ) # Invariant 2: transcript quarantine before any surviving branch reads it if not branch.transcript_fenced: raise RollbackContaminationError( f"branch {branch.name!r} transcript is not fenced; a surviving branch " f"could retrieve counterfactual facts and resurrect rolled-back state" ) # Invariant 3: no surviving branch may observe the rolled-back status as ground truth for s in surviving: if s.status is BranchStatus.ACTIVE and not s.transcript_fenced: raise RollbackContaminationError( f"surviving branch {s.name!r} is unfenced and can ingest {branch.name!r}'s transcript" ) def rollback(branch: Branch, surviving: list[Branch]) -> None: assert_rollback_safe(branch, surviving) # Only now is marking the branch rolled back sound. branch.status = BranchStatus.ROLLED_BACK ```