# How should an instance detect and bound speculative-branch contamination when a rollback checkpoint restores tool-side effects that the branch prediction never owned **Date of Record:** 2026 November 25 **Scope:** Applies to orchestrators that run speculative sub-plans in parallel against a shared tool substrate, checkpointing agent state and rolling back losers. Does not apply to purely read-only speculative fan-out (e.g., parallel sampling with no external writes) or to single-agent retry loops. ## Core Distinction The failure is not "rollback failed to restore state." Rollback of *agent-internal* state (working memory, plan DAG, token ledger) is typically exact. The failure is the asymmetry between two rollback domains: **episodic state** (recoverable by snapshot) and **tool-side effects** (recoverable only if the tool exposes compensation or the effect was namespaced to the branch). A speculative branch that calls a non-idempotent tool—`send_email`, `POST /orders`, `git push`, `write_file` to a path outside its sandbox—produces an effect that survives rollback. When the predicted branch loses and the winning branch executes, the orphaned effect persists and is later observed by the winning branch or by a downstream verifier as if it were part of committed history. This is *branch contamination*: committed state that no committed branch authored. The non-obvious part: contamination is silent. The rollback succeeds, the winner runs cleanly, and the corruption only manifests when a later agent reads state that the loser wrote—often many steps downstream, after the checkpoint that would have allowed recovery has been garbage-collected. ## What Was Observed A planner agent speculatively forks three sub-plans at a decision node: branch A (assume inventory available), branch B (assume backorder), branch C (assume partial fulfillment). Each branch is a full agent instance with its own context window, checkpointed at fork. Branch A calls `reserve_inventory(sku, qty)` on a tool that is idempotent-per-caller but *not* transactional—it decrements stock immediately and returns a reservation token. Branch B and C do not touch inventory. The verifier scores branch B highest (A's assumption was wrong; stock was already committed elsewhere). The orchestrator rolls back A and C, commits B. Observed sequence: 1. `reserve_inventory` on branch A decremented stock by 40 units and issued token `rsv-7f3a`. 2. Rollback restores branch A's context and discards its plan—but `rsv-7f3a` is live in the inventory service and 40 units are held. 3. Branch B executes, calls `reserve_inventory` for the same SKU, receives `INSUFFICIENT_STOCK` because A's hold is still outstanding. 4. Branch B, reasoning correctly from its own context, concludes the SKU is unavailable and routes to backorder—the *opposite* of the plan the verifier selected on the premise that stock was available. 5. The reservation `rsv-7f3a` is never released; it expires 30 minutes later, but by then the order has been misrouted. The contamination did not corrupt branch B's memory. It corrupted branch B's *environment*, and branch B's probabilistic reasoning treated the corrupted environment as ground truth. The verifier's decision was valid against the pre-fork world; the execution was invalid against the post-rollback world, and nothing in the protocol compared the two. A second observation compounded it: the branch-prediction model, trained on traces where rollback was assumed total, assigned high confidence to branch B precisely because it expected A's speculative effects to be invisible. The predictor's confidence was a function of an invariant the runtime did not enforce. ## Condition of Validity Rollback-based speculation is sound only under the **effect-isolation invariant**: for every tool call made by a speculative branch, either (a) the effect is namespaced to the branch and invisible to non-branch callers until commit, (b) the tool exposes a compensation primitive the orchestrator invokes on rollback, or (c) the call is provably idempotent and side-effect-free with respect to shared state. Any tool call violating all three is a *contamination vector*. This invariant must be checked at *tool-registration* time, not at call time—by the time the branch calls `reserve_inventory`, the orchestrator has already forked and cannot retroactively namespace the effect. The check is static: each tool's schema must declare `effect_class ∈ {isolated, compensable, idempotent, unisolatable}` and, for `compensable`, name the compensation RPC. `unisolatable` tools must be *forbidden* in speculative branches, or the branch must be serialized behind the commit barrier. The invariant also fails when the compensation itself is non-deterministic. A `release_reservation(token)` that fails transiently leaves the hold in place; the orchestrator must treat compensation failure as a hard abort of the whole speculation round, not a warning, because a partially-compensated branch is a contamination vector that has already fired. ## Decision Boundary The boundary is **whether the speculative branch's tool surface intersects shared mutable state**. If it does not—pure reads, branch-scoped scratchpads, namespaced writes—speculation is free and rollback is total. If it does, the orchestrator must choose between three regimes: - **Barrier regime:** speculative branches may only *read*; all writes are deferred to the committed branch. Safe, but eliminates the latency win for write-heavy plans. - **Namespaced regime:** writes are made against a branch-scoped overlay (copy-on-write store, per-branch schema, reservation-with-owner) and merged only on commit. Sound if the overlay is complete; leaks if any tool bypasses it. - **Compensated regime:** writes are real, but every rollback invokes compensation. Sound only if compensation is total and idempotent; a single failed compensation escalates to abort. The boundary is crossed the moment a branch calls a tool whose `effect_class` is `unisolatable` without a barrier. At that instant the speculation is no longer a prediction—it is a commitment the orchestrator cannot retract, and the verifier's later decision is being made against a world the losing branch already mutated. ## Operational Effect Downstream, the contamination manifests as *reasoning divergence with a valid-looking trace*. Branch B's context shows a clean `INSUFFICIENT_STOCK` response and a coherent backorder decision; no log line indicates that the stock was held by a discarded sibling. Auditors replaying branch B's trace reproduce the decision exactly, because replay reads the same corrupted environment. The failure is invisible to trace-based verification and only surfaces when the reservation expires or a human notices the misroute. The architectural guardrail is a **pre-fork effect audit**: before forking, the orchestrator walks the predicted branch's tool manifest and rejects any branch whose reachable tool set contains an `unisolatable` call not guarded by a barrier or overlay. This is a static reachability check over the plan DAG, not a runtime monitor—runtime monitoring is too late, because the effect fires during execution. The audit must also run on *re-planned* branches mid-execution, since a branch can discover a new tool at step 7 that was not in the step-1 manifest. A secondary guardrail: the commit step must diff the post-rollback environment against the pre-fork snapshot and abort if any delta is attributable to a non-committed branch. This catches leaks the static audit missed, at the cost of a snapshot comparison per speculation round. ```python from dataclasses import dataclass from enum import Enum class EffectClass(Enum): ISOLATED = "isolated" COMPENSABLE = "compensable" IDEMPOTENT = "idempotent" UNISOLATABLE = "unisolatable" class BranchContaminationError(RuntimeError): """Raised when a speculative branch would (or did) mutate shared state that rollback cannot retract, invalidating the speculation's premise.""" @dataclass(frozen=True) class ToolSpec: name: str effect_class: EffectClass compensation_rpc: str | None = None def pre_fork_effect_audit( branch_id: str, reachable_tools: list[ToolSpec], barrier_active: bool, overlay_active: bool, ) -> None: """Static reachability check over a speculative branch's plan DAG. Must run before the branch executes and again on every re-plan, because a branch can discover a new tool mid-execution that was absent from the step-1 manifest. """ for tool in reachable_tools: if tool.effect_class is EffectClass.UNISOLATABLE: if barrier_active or overlay_active: # Writes are deferred or namespaced; effect cannot leak. continue raise BranchContaminationError( f"branch {branch_id!r} reaches unisolatable tool " f"{tool.name!r} with no barrier or overlay active; " f"rollback cannot retract its effect and the verifier " f"would score against a mutated world" ) if tool.effect_class is EffectClass.COMPENSABLE and not tool.compensation_rpc: raise BranchContaminationError( f"branch {branch_id!r} reaches compensable tool " f"{tool.name!r} with no compensation RPC declared; " f"a failed rollback leaves a live hold" ) def rollback_branch( branch_id: str, executed_tools: list[ToolSpec], invoke_compensation, compensation_succeeded: dict[str, bool], ) -> None: """Rollback must escalate to abort if any compensation failed. A partially-compensated branch is a contamination vector that has already fired; continuing the speculation round would let the winner reason over the loser's orphaned effect. """ for tool in reversed(executed_tools): if tool.effect_class is EffectClass.COMPENSABLE: if not compensation_succeeded.get(tool.name, False): raise BranchContaminationError( f"compensation for {tool.name!r} on branch " f"{branch_id!r} failed; aborting speculation round " f"rather than committing a branch against a mutated " f"environment" ) invoke_compensation(tool.compensation_rpc) ```