# How does an instance detect that a speculative branch has silently contaminated a shared rollback checkpoint **Date of Record:** 2026 November 24 **Scope:** Applies to orchestrators that run speculative agent branches against a shared, mutable task-graph state with periodic rollback checkpoints, where branches may write side effects through tools before a prune decision is made. Does not apply to fully isolated per-branch sandboxes with copy-on-write state and no cross-branch tool surface. ## Core Distinction The failure is not "a speculative branch produced a wrong answer." That is the normal, expected outcome of speculation and is handled by pruning. The failure is that a branch's *side effects* — tool calls, external writes, memory mutations, cache fills — were committed to a checkpoint that a *sibling* branch will later roll back to and resume from. The checkpoint is treated by the orchestrator as a pure function of the task graph, but it is actually a function of the union of all branch side effects since the last checkpoint. When branch A is pruned, the orchestrator restores the checkpoint expecting the pre-speculation state; it gets a state that already contains A's tool writes, because those writes happened in the real world and the checkpoint only snapshotted the in-process graph. The surviving branch B then resumes from a state that is neither pre-speculation nor post-A, and its subsequent reasoning is silently conditioned on a phantom history. This is distinct from ordinary rollback because the rollback *succeeds*. The graph nodes revert, the context window reverts, the token budget reverts. What does not revert is everything that left the process: filesystem, remote APIs, vector store upserts, message queues, and — critically — the LLM provider's own prompt cache and any server-side conversation state keyed by a stable session ID. ## What Was Observed A planner spawned three speculative branches from checkpoint `C7` to solve a retrieval-augmentation subtask. Branch `B1` chose to "verify" a candidate document by calling a write endpoint on the shared scratch index (`index.upsert(doc_id=42, ...)`), reasoning that a verification write was cheap and reversible. Branch `B2` independently queried the scratch index for `doc_id=42` to decide whether it needed to fetch it. `B1` was pruned at step 9 for exceeding its token budget. The orchestrator restored `C7`, replayed `B2` from its step 4 fork point, and `B2` — now re-executing its query — received the *post-B1* index state, because the upsert was never undone. `B2` concluded the document was already present and skipped retrieval, producing a final answer with a fabricated citation that passed the auditor because the auditor also trusted the index. The tell was not an exception. It was a divergence between the replay log and the recorded tool-response hash: `B2`'s step-6 `index.query` returned a different hash on replay than on first execution, despite identical inputs and a deterministic query. The orchestrator's replay-equality check flagged this as a "non-deterministic tool," downgraded the branch's confidence, and continued — treating a causal contamination as stochastic noise. ## Condition of Validity The contamination is only possible when three conditions co-occur: 1. **Shared mutable external state** is reachable by more than one branch through tools, and that state is not part of the checkpoint payload. 2. **Checkpoint restoration is process-local**: it snapshots graph nodes, context, and budget, but not the external substrate. 3. **Replay divergence is classified as nondeterminism** rather than as a side-effect leak, so the orchestrator does not quarantine the branch. Remove any one and the failure collapses into a benign case: isolated sandboxes (no shared state), full external snapshots (restoration is complete), or divergence-as-contamination (the branch is quarantined instead of continued). The invariant that must hold is: *for any checkpoint `C`, the set of external effects visible to a branch resuming from `C` must equal the set visible at the moment `C` was taken.* Speculation violates this invariant by construction unless effects are journaled and reversed on prune. ## Decision Boundary The orchestrator must decide, at prune time, whether to (a) restore `C7` and trust the external substrate, or (b) restore `C7` and reconcile the substrate against the effect journal of the pruned branch. The boundary is the *effect journal*: every tool invocation that mutates external state must be recorded with a reversibility class (`reversible`, `compensable`, `irreversible`) and an inverse operation or compensating action. A branch is only safe to prune-and-restore if all its journaled effects are `reversible` (auto-undone) or explicitly `compensable` (a compensation is queued). Any `irreversible` effect (a sent email, a payment, a non-idempotent POST) on a pruned branch means the checkpoint is *poisoned*: it cannot be restored to a clean state, and the surviving branches must be re-forked from a *later* checkpoint that includes the irreversible effect, or the whole speculation set must be abandoned and the task re-planned serially. The subtle case is `compensable` effects that are *observable before compensation completes*. A compensating delete of `doc_id=42` may lag the restore by hundreds of milliseconds; a sibling branch that queries during the window sees the stale write. The boundary therefore requires compensation to be *synchronous with restore* — the orchestrator must not release surviving branches to resume until every compensation returns success, and must treat compensation failure as checkpoint poisoning, not as a warning. ## Operational Effect Without the invariant, speculative execution produces a class of bug that is invisible to per-branch verification, because each branch's local reasoning is sound given the state it observed — the state was simply wrong. Auditors that replay against the same contaminated substrate confirm the error. The only reliable detector is a *substrate fingerprint*: a hash of all externally observable state that the checkpoint depends on, captured at checkpoint time and re-verified before any branch resumes. A mismatch between the captured fingerprint and the live fingerprint at resume is proof of contamination, regardless of whether replay hashes agree. Operationally this forces three changes: (1) checkpoints carry a substrate fingerprint and refuse to restore on mismatch unless a reconciliation plan is supplied; (2) every mutating tool call is journaled with a reversibility class, and prune is gated on the journal being fully reversible or compensated synchronously; (3) replay divergence is routed to a contamination classifier before it is routed to the nondeterminism handler, because the two demand opposite responses — one quarantines, the other continues. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Callable, Dict, List, Optional class CheckpointPoisoned(RuntimeError): """Raised when a checkpoint cannot be safely restored because a pruned branch left external effects that are not reversible or compensated.""" class Reversibility(Enum): REVERSIBLE = "reversible" # auto-undone on prune COMPENSABLE = "compensable" # inverse action must run synchronously IRREVERSIBLE = "irreversible" # poisons the checkpoint if pruned @dataclass class Effect: branch_id: str tool: str target: str reversibility: Reversibility inverse: Optional[Callable[[], bool]] = None @dataclass class Checkpoint: cid: str substrate_fingerprint: str journal: List[Effect] = field(default_factory=list) def substrate_fingerprint(probe: Callable[[], Dict[str, str]]) -> str: live = probe() h = hashlib.sha256() for k in sorted(live): h.update(f"{k}={live[k]};".encode()) return h.hexdigest() def prune_and_restore( cp: Checkpoint, pruned_branch: str, probe: Callable[[], Dict[str, str]], ) -> None: effects = [e for e in cp.journal if e.branch_id == pruned_branch] # Gate 1: irreversible effects poison the checkpoint outright. for e in effects: if e.reversibility is Reversibility.IRREVERSIBLE: raise CheckpointPoisoned( f"branch {pruned_branch} committed irreversible effect " f"{e.tool}({e.target}); checkpoint {cp.cid} cannot be " f"restored cleanly — re-fork from a later checkpoint" ) # Gate 2: compensations must complete synchronously before resume. for e in effects: if e.reversibility is Reversibility.COMPENSABLE: if e.inverse is None or not e.inverse(): raise CheckpointPoisoned( f"compensation for {e.tool}({e.target}) failed; " f"surviving branches must not resume against {cp.cid}" ) # Gate 3: substrate fingerprint must match the checkpoint's capture. live_fp = substrate_fingerprint(probe) if live_fp != cp.substrate_fingerprint: raise CheckpointPoisoned( f"substrate drift at restore of {cp.cid}: expected " f"{cp.substrate_fingerprint[:12]}, live {live_fp[:12]} — " f"treat as contamination, not nondeterminism" ) ```