# Which invariants prevent speculative tool invocations from leaking irreversible side effects across branch rollback **Date of Record:** 2026 November 28 **Scope:** Applies to agent pipelines that speculatively execute tool calls on parallel reasoning branches and roll back losing branches before committing a winner. Does not apply to single-branch sequential agents, nor to tools that are provably pure and idempotent under a stable idempotency key. ## Core Distinction The distinction that matters is between **rollback of agent state** and **rollback of the external world**. A speculative branch can be discarded at the agent layer in O(1): drop its context segment, free its token budget, mark its trace `ABANDONED`. The world, however, does not have a `git reset`. A speculative `send_email`, `charge_card`, `POST /deploy`, or `INSERT INTO ledger` that fired before branch validation is already durable. The invariant that speculative execution depends on is therefore not "branches are isolated in memory" — it is **"no branch may emit an effect that cannot be compensated before that branch is validated."** Every failure in this class is a violation of that single invariant, and it manifests as *effect leakage*: a side effect attributable to a branch that the orchestrator later declared non-authoritative. The subtlety is that leakage is not a crash. The agent reports success on the winning branch, the losing branch is garbage-collected cleanly, and the leaked effect persists silently until a downstream reconciliation job (or a customer) notices a duplicate charge, a ghost deployment, or a phantom record. The failure is invisible to the pipeline's own health metrics because every component did exactly what it was told. ## What Was Observed A planner agent decomposed a refund request into three speculative branches over the same customer record: - **Branch A:** verify order via `orders.get`, then `payments.refund`. - **Branch B:** verify via `ledger.query` (a slower but authoritative source), then `payments.refund`. - **Branch C:** escalate to human review if neither source agrees. The orchestrator launched A and B concurrently with a shared tool-call budget and a `speculation_ttl` of 8 seconds. Branch A's `orders.get` returned a cached, stale-but-plausible `status: refundable`. Branch A, reasoning it had satisfied its precondition, invoked `payments.refund` at t=2.1s. Branch B's `ledger.query` returned at t=6.4s and revealed the order had already been refunded 40 minutes earlier. The validator correctly selected Branch B's *conclusion* — "already refunded, do not refund again" — and rolled back Branch A. But Branch A had already executed `payments.refund`. The rollback discarded Branch A's context, its trace, and its reserved budget. It did not, and could not, un-charge the customer. The customer received a second refund; the ledger now showed a negative balance on that order. The orchestrator logged `branch_A: ROLLED_BACK, branch_B: COMMITTED, outcome: SUCCESS`. No error was raised anywhere. The trigger condition is precise: **a branch reached a tool invocation before the validation gate that would have disqualified it, and the tool had a non-compensable effect.** The stale cache in `orders.get` was the probabilistic-reasoning amplifier — the LLM had no way to distinguish a stale `refundable` from a fresh one, so it proceeded on a precondition that was locally satisfied but globally false. A second, quieter observation: even when the tool *was* compensable, the compensation itself was sometimes skipped. The orchestrator's rollback path called `branch.cleanup()` which released resources but did not invoke any registered compensator, because compensators were an opt-in field the tool schema rarely populated. The default was "rollback = forget," which is correct for state and catastrophic for effects. ## Condition of Validity Speculative execution with rollback is sound **if and only if** all three of the following hold for every tool invocation emitted by a non-validated branch: 1. **Effect classification is declared at the schema layer, not inferred at runtime.** Each tool must carry an `effect_class` of `PURE`, `COMPENSABLE`, or `IRREVERSIBLE`, and the orchestrator must refuse to dispatch `IRREVERSIBLE` tools from a branch whose validation token is not yet `VALIDATED`. Inference from tool name or description is insufficient — an LLM will happily classify `notify_customer` as "just a message" when it is in fact an irreversible outbound communication. 2. **Every `COMPENSABLE` invocation registers a compensator before the effect fires.** The registration must be atomic with the dispatch (write-ahead), so that a crash between dispatch and registration does not orphan the effect. A compensator that is registered *after* the effect returns is a compensator that may never exist. 3. **Validation is a monotonic gate, not a race.** A branch's validation token must transition `SPECULATIVE → VALIDATED` or `SPECULATIVE → ABANDONED` exactly once, and no tool dispatch may occur on a `SPECULATIVE` token for an effect class above `PURE`. If validation can arrive *after* a dispatch, the invariant is already broken regardless of how fast the rollback is. When any of these fails, the pipeline is not doing speculative execution with rollback — it is doing **speculative execution with best-effort cleanup**, which is a different and much weaker guarantee. The distinction matters because the failure is silent and the blast radius is external. ## Decision Boundary The boundary is between **speculating over reads** and **speculating over writes**. Speculation over reads is always safe: a speculative `orders.get` that gets rolled back costs a few tokens and a cache entry. Speculation over writes is safe only under the three conditions above. Operationally, the decision rule the orchestrator must enforce is: - If `effect_class == PURE`: dispatch freely on any branch, any token state. - If `effect_class == COMPENSABLE` and a compensator is registered write-ahead: dispatch on `SPECULATIVE`, but the branch cannot be marked `COMMITTED` until all its compensators are either confirmed-unneeded or the branch is the winner. - If `effect_class == IRREVERSIBLE`: **the branch must hold a `VALIDATED` token before dispatch.** This means the branch cannot be truly speculative for irreversible effects — it must be a *deferred* branch that resolves its preconditions first, then commits, then acts. The latency cost is real and unavoidable. The tempting shortcut — "just make the rollback faster" — is the boundary violation. Rollback speed is irrelevant to a durable effect. The only correct move is to prevent the dispatch, which requires the token to gate the dispatch, which requires the effect class to be known before the call. A secondary boundary: **shared tool-call budgets do not imply shared effect authority.** Two branches racing on the same budget can both pass their local precondition checks and both dispatch, because the budget is a resource counter, not a mutual-exclusion primitive. If two branches can both reach an irreversible tool, the orchestrator needs a per-resource effect lock keyed on the target (e.g., `order:12345`), not just a global budget. ## Operational Effect When the invariant holds, speculative execution buys real latency: branches A and B run concurrently, the validator picks the correct one, and the losing branch's *reads* are simply discarded. The customer sees one refund, issued by the branch that actually verified the precondition. When the invariant is violated, the observable signature is a **duplicate or orphaned external effect correlated with a `ROLLED_BACK` branch in the trace**. The reconciliation query is: for every branch marked `ABANDONED` or `ROLLED_BACK`, list every tool invocation it emitted with `effect_class != PURE`, and check whether each has a matching compensator record. Any invocation without a compensator is a leak. This query should run continuously, not on incident. The guardrail that bounds the damage is the **write-ahead compensator registry plus the validation-token gate**. The registry ensures that any compensable effect can be undone; the gate ensures that non-compensable effects never fire from an unvalidated branch. Together they convert a silent, external, unbounded failure into a loud, internal, bounded one — the orchestrator either refuses the dispatch (a clean `SpeculationViolation`) or it has a compensator on file to reverse it. The residual risk is the `IRREVERSIBLE` tool that was mislabeled `COMPENSABLE` by a schema author. This is why effect classification must be reviewed with the same rigor as a database migration: it is a declaration about the outside world, and the agent's correctness depends on it being true. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Callable class SpeculationViolation(RuntimeError): """Raised when a speculative branch attempts an effect it is not authorized to emit.""" pass class EffectClass(Enum): PURE = "pure" COMPENSABLE = "compensable" IRREVERSIBLE = "irreversible" class TokenState(Enum): SPECULATIVE = "speculative" VALIDATED = "validated" ABANDONED = "abandoned" @dataclass class ToolSpec: name: str effect_class: EffectClass compensator: Callable[[dict], None] | None = None @dataclass class Branch: branch_id: str state: TokenState = TokenState.SPECULATIVE compensators: list[Callable[[], None]] = field(default_factory=list) class SpeculativeOrchestrator: def __init__(self) -> None: self._registry: dict[str, ToolSpec] = {} def register_tool(self, spec: ToolSpec) -> None: if spec.effect_class is EffectClass.COMPENSABLE and spec.compensator is None: raise SpeculationViolation( f"tool {spec.name!r} declared COMPENSABLE but has no compensator; " "write-ahead compensation is mandatory" ) self._registry[spec.name] = spec def invoke(self, branch: Branch, tool_name: str, args: dict) -> dict: spec = self._registry.get(tool_name) if spec is None: raise SpeculationViolation(f"unregistered tool {tool_name!r}") # Gate 1: irreversible effects require a validated token. if spec.effect_class is EffectClass.IRREVERSIBLE and branch.state is not TokenState.VALIDATED: raise SpeculationViolation( f"branch {branch.branch_id} in state {branch.state.value} attempted " f"IRREVERSIBLE tool {tool_name!r}; validate before dispatch" ) # Gate 2: compensable effects must register compensation write-ahead. if spec.effect_class is EffectClass.COMPENSABLE: if spec.compensator is None: raise SpeculationViolation(f"no compensator for {tool_name!r}") branch.compensators.append(lambda: spec.compensator(args)) # Gate 3: abandoned branches may not dispatch at all. if branch.state is TokenState.ABANDONED: raise SpeculationViolation( f"branch {branch.branch_id} is ABANDONED and cannot invoke {tool_name!r}" ) return {"tool": tool_name, "args": args, "dispatched": True} def rollback(self, branch: Branch) -> None: branch.state = TokenState.ABANDONED for compensate in reversed(branch.compensators): compensate() branch.compensators.clear() def validate(self, branch: Branch) -> None: if branch.state is not TokenState.SPECULATIVE: raise SpeculationViolation( f"branch {branch.branch_id} cannot transition {branch.state.value} -> VALIDATED" ) branch.state = TokenState.VALIDATED # Winner's compensators are confirmed-unneeded. branch.compensators.clear() ```