# How should an instance detect and contain speculative branch contamination when optimistic tool invocations produce irreversible external side effects before rollback is committed **Date of Record:** 2026 November 28 **Scope:** Applies to orchestrators that fork multiple speculative execution branches (parallel agent instances or reasoning traces) and invoke tools optimistically before a winning branch is selected. Does not apply to purely read-only tool surfaces or to single-branch sequential execution with no rollback semantics. ## Core Distinction The naive mental model of speculative multi-agent execution treats a branch as a *pure function of context*: fork state, execute, score, keep the best, discard the rest. Rollback is then framed as a state-management problem—restore the checkpoint, prune the losing branches, move on. This framing is correct only when every tool invoked inside a branch is **idempotent and side-effect-free with respect to the external world**. The boundary failure appears the moment a branch performs an *optimistic tool invocation*: a call whose external effect (an email sent, a record written, a payment authorized, a message posted) is committed at the tool boundary before the orchestrator has decided which branch wins. Rollback then restores *internal* state—the agent's context, scratchpad, and memory—while the *external* world retains the effects of every losing branch. The invariant that silently breaks is: > **Rollback completeness invariant:** after a speculative round resolves, the observable external world must equal the world produced by the winning branch alone. This is not a CRUD/transaction problem. The orchestrator has no transactional boundary over the tool surface; the LLM decides *when* and *which* tools to call probabilistically, and non-deterministic tool outputs feed back into branch scoring. Two branches can invoke the same tool with semantically equivalent but syntactically distinct arguments (different phrasing, different IDs resolved from stale retrieval), so naive deduplication by call signature does not catch them. The contamination is *semantic*, not syntactic. ## What Was Observed A planner instance forked three branches on a task requiring "reconcile the customer record and notify them of the correction." Each branch was given the same checkpoint and permitted optimistic tool use to reduce latency, with the orchestrator committing the highest-scoring branch at round end. - Branch A resolved the customer via a stale retrieval hit (an old record ID from episodic memory) and invoked `send_notification` against the wrong contact. - Branch B resolved correctly, invoked `update_record`, then `send_notification` to the right contact. - Branch C timed out mid-`update_record` after the write had already been flushed to the external system, then was pruned. The scoring step selected Branch B (highest task-completion score). Rollback pruned A and C, restoring the orchestrator's internal state to B's checkpoint lineage. But the external world now contained: a notification to the wrong contact (A), a duplicate record update (B plus C's partial flush), and a notification (B) that referenced a record state that C had transiently mutated. The winning branch's *own* output was internally consistent; the *world* was not. The failure was not detected at rollback time. It surfaced two rounds later when a downstream auditor agent read the customer record, found the duplicate, and flagged the whole session—triggering a verification replay that diverged from the recorded trace because the replay's tool calls hit an already-mutated world. Key mechanics of the trace: 1. **Optimistic invocation window.** Between branch fork and winner commit, every tool call is a *speculative effect*. The window length is bounded by the slowest branch's tool latency, not by reasoning depth—so it widens precisely when branches diverge most (slow, uncertain branches call more tools). 2. **Pruning does not unwind.** Pruning a branch removes its context and its claim on the winner slot; it does not emit compensating calls. The orchestrator assumed tool idempotency, which `send_notification` violates. 3. **Cross-branch state bleed via external reads.** Branch B's second call read the record *after* C's partial flush, so B's "correct" output was computed against a world contaminated by a losing branch. Rollback cannot detect this because B's internal consistency checks all pass. 4. **Scoring blindness.** The branch scorer evaluated *task completion*, not *effect footprint*. A branch that produced more external effects could score higher without penalty. ## Condition of Validity Speculative execution with rollback is sound **only** under the conjunction of three conditions, all of which must hold per-tool, not per-branch: - **Effect classification is total and correct.** Every tool in the surface is classified as *reversible* (can be compensated by a registered inverse), *idempotent* (repeat-safe, no net effect), or *irreversible* (no compensation exists). The classification must be attached to the tool schema and validated at registration, not inferred by the LLM at call time. - **Irreversible tools are gated out of the optimistic window.** An irreversible tool may only be invoked by the *committed* branch, after winner selection. Speculation on irreversible effects is prohibited by construction. - **Reversible tools carry a compensation handle.** Every speculative invocation of a reversible tool returns a handle that the orchestrator stores in the branch's effect journal; rollback replays the journal in reverse order to emit compensations. The journal must be durable and ordered, because compensation ordering matters (undo the notification before the record update it referenced). When any condition fails—most commonly when a tool is misclassified as reversible because its schema lacks an inverse, or when the LLM invokes an irreversible tool through a reversible wrapper—the invariant is unenforced and contamination is silent until a downstream reader observes it. ## Decision Boundary The boundary between safe speculation and contamination is drawn by **effect class**, not by branch count, latency budget, or confidence score: - If a branch's *entire* tool sequence is idempotent or reversible-with-handle, speculate freely; rollback is complete by construction. - If a branch *would* invoke an irreversible tool, the orchestrator must either (a) defer that call to post-commit, or (b) convert the round from speculative to sequential for that branch. It must not "speculate and hope." - Confidence is not a substitute. A high-scoring branch that invoked an irreversible tool is *more* dangerous, not less, because it is more likely to be committed alongside its already-committed effects, and its losing siblings' effects remain. - Cross-branch read contamination is a separate boundary: even fully reversible branches can read a world mutated by a sibling. The guardrail is *effect isolation*—speculative branches read from a snapshot of external state captured at fork time, and any tool whose output depends on external state must declare a `reads_external_state` flag so the orchestrator can route it to the snapshot. The decision rule the orchestrator must enforce: **a branch is eligible for optimistic execution only if its declared tool set contains no irreversible tool and no un-snapshotted external read; otherwise it is executed sequentially behind the commit barrier.** ## Operational Effect Contamination of this kind is not a latency or correctness bug in the classical sense; it is a *continuity* failure that propagates across rounds. Because rollback restores internal state but not the world, the agent's memory records a clean history while the external substrate diverges from it. Subsequent retrieval (episodic memory, record reads) then returns states that contradict the recorded trace, and any verification replay—which re-executes the recorded tool calls against the now-mutated world—will diverge and either false-positive or false-negative the audit. Operationally this forces three changes: 1. **Effect journaling is mandatory and durable.** The orchestrator must persist a per-branch effect journal before the tool call returns, so that a crashed orchestrator can still compensate orphaned speculative effects on recovery. An in-memory journal is insufficient because the crash window and the optimistic window overlap. 2. **The branch scorer must incorporate an effect-footprint penalty.** Branches that touched irreversible tools or read unsnapshotted external state score lower, so winner selection is biased toward branches that are safe to commit alongside their siblings' residual effects. 3. **Commit must be a barrier, not a selection.** "Select winner and prune losers" is replaced by "select winner, compensate losers' journals in reverse, then release the commit barrier for the winner's deferred irreversible calls." The barrier is what prevents a losing branch's effect from being observed by the winner's post-commit reasoning. The residual risk that cannot be eliminated: a reversible tool whose inverse is not *semantically* inverse (a "delete notification" that leaves an audit log entry, a "refund" that leaves a ledger trace). These are irreversible in effect even when reversible in schema. The only defense is a conservative classification default—treat any tool without a *verified* compensation test as irreversible—and accept the latency cost of gating it behind the commit barrier. ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable class EffectClass(Enum): IDEMPOTENT = "idempotent" REVERSIBLE = "reversible" # has a verified compensation handle IRREVERSIBLE = "irreversible" class SpeculativeContaminationError(RuntimeError): """Raised when a speculative branch would commit an irreversible effect or read unsnapshotted external state before the commit barrier.""" @dataclass class ToolSpec: name: str effect: EffectClass reads_external_state: bool = False compensate: Callable[[dict], None] | None = None @dataclass class EffectJournal: entries: list[tuple[ToolSpec, dict]] = field(default_factory=list) def record(self, spec: ToolSpec, args: dict) -> None: self.entries.append((spec, args)) def compensate_reverse(self) -> None: for spec, args in reversed(self.entries): if spec.effect is EffectClass.REVERSIBLE and spec.compensate: spec.compensate(args) def assert_speculable(spec: ToolSpec, committed: bool) -> None: """Enforce the rollback-completeness invariant before any tool call.""" if committed: return # committed branch may invoke any effect class if spec.effect is EffectClass.IRREVERSIBLE: raise SpeculativeContaminationError( f"tool '{spec.name}' is irreversible and cannot be invoked " f"inside the optimistic window; defer to post-commit" ) if spec.reads_external_state: raise SpeculativeContaminationError( f"tool '{spec.name}' reads unsnapshotted external state; " f"route to fork-time snapshot or execute behind commit barrier" ) def run_branch(tools: dict[str, ToolSpec], calls: list[tuple[str, dict]], committed: bool, journal: EffectJournal) -> None: for name, args in calls: spec = tools[name] assert_speculable(spec, committed) journal.record(spec, args) # ... invoke tool ... ```