# Where must an instance bound speculative tool invocation before branch-and-rollback commits an unrollbackable side effect? **Date of Record:** 2026 November 29 **Scope:** Applies to agent pipelines that speculatively execute tool calls down multiple reasoning branches and roll back losing branches. Does not apply to purely read-only tool surfaces or to single-branch linear execution with no rollback. ## Core Distinction Speculative execution in an agent pipeline is only sound when *every* operation reachable on a speculative branch is either (a) reversible by construction, or (b) guarded by a two-phase commit that defers the irreversible transition until the branch is selected. The non-obvious boundary is this: **reversibility is a property of the tool's effect, not of the agent's ability to call a "compensating" tool.** Agents routinely conflate "I can call an undo tool" with "the effect is rollbackable." It is not. A compensating call is itself a new forward action against a world that has already changed, and it can fail, race, or be observed by third parties in the interval. The invariant that must hold is stricter than "I have a rollback plan": *no speculative branch may cross the commit barrier of any effect whose observation by an external party is irreversible.* The distinction matters because rollback of *state* (context, scratchpad, working memory) is cheap and total, while rollback of *effects* (sent email, charged card, written row, dispatched webhook, mutated remote resource) is expensive, lossy, and sometimes impossible. Speculation is safe exactly up to the first effect-crossing call, and the agent's failure mode is that it cannot tell, at call time, which side of that line a tool sits on—because tool schemas describe inputs and outputs, not commitment semantics. ## What Was Observed A planner agent was asked to reconcile a customer refund. It fanned out three speculative branches in parallel: branch A proposed `issue_refund(amount=full)`, branch B proposed `issue_refund(amount=partial)` then `send_email(apology)`, branch C proposed `escalate_to_human()`. The pipeline was optimistic: it invoked tools as soon as a branch's preconditions were locally satisfied, buffered results, and rolled back the losing branches once a scoring function picked a winner. The refund tool was idempotency-keyed on `(customer_id, branch_id)`, so the agent's authors believed it was "safe to speculate." It was idempotent but not reversible. Two branches (A and B) both passed preconditions and both fired `issue_refund` before the scorer ran. The idempotency key differed per branch, so both charges posted. When the scorer selected branch C, the pipeline executed its rollback path: it called `issue_refund_reversal` on branches A and B. Branch A's reversal succeeded. Branch B's reversal *also* succeeded, but only after the customer had already received the apology email that branch B sent in the gap between charge and reversal, and after the payment processor had emitted a `refund.settled` webhook to a downstream ledger that does not process reversals idempotently. The ledger double-counted. The observable failure trace: 1. `branch_A.issue_refund` → committed, effect visible. 2. `branch_B.issue_refund` → committed, effect visible. 3. `branch_B.send_email` → committed, effect visible and *unrecallable*. 4. Scorer selects C (human escalation is correct; the refund was fraudulent). 5. Rollback: `reversal(A)` ok, `reversal(B)` ok, `send_email` has no reversal. 6. Downstream ledger received two `refund.settled` events and one reversal; net position wrong by the amount of B. The agent's internal state after rollback was clean—context restored, branch buffers discarded, memory consistent. The *world* was not. The agent reported success because its rollback succeeded against its own model of the world; the model did not include the ledger's non-idempotent consumer or the email's permanence. The root trigger was not a bug in any single tool. It was the *absence of a commitment classification* on the tool interface. The pipeline treated "has an idempotency key" and "has a compensating tool" as sufficient for speculation. Neither implies reversibility of observation. ## Condition of Validity The speculation-before-commit pattern is valid only under the following conjunction, checked per branch at the moment a tool is about to fire: - **Effect class is declared and trusted.** Each tool must carry a commitment class: `PURE` (no external effect), `REVERSIBLE_STATE` (effect confined to agent-owned state, rollback is a state restore), `COMPENSABLE` (external effect with a defined compensating action, but the effect is *observable during the window*), or `IRREVERSIBLE` (no compensating action restores the pre-state, or compensation is not idempotent against all consumers). Speculation is permitted only for `PURE` and `REVERSIBLE_STATE`. `COMPENSABLE` may be speculated *only* if every downstream consumer of the effect is itself idempotent and the compensation window is bounded and the branch's probability of selection exceeds a threshold that makes expected compensation cost acceptable. `IRREVERSIBLE` must never fire speculatively. - **The commit barrier is explicit.** A branch that would cross into `COMPENSABLE` or `IRREVERSIBLE` must be *deferred*: the tool call is staged as an intent, not executed, until the scorer commits the branch. This is two-phase commit for agent effects. - **The scorer is monotone with respect to commitment.** Once any branch has crossed the commit barrier, the scorer may no longer select a different branch without first executing and *verifying* compensation. "Verify" means observing the compensating effect's completion from the external system's perspective, not from the agent's tool-call return. - **Compensation is verified, not assumed.** A reversal that returns `200` is not proof of reversal; the agent must re-read the affected resource or consume the compensating event before declaring the branch rolled back. When any of these is unknown—tool commitment class undeclared, consumer idempotency unverified, compensation unobservable—the correct default is to treat the tool as `IRREVERSIBLE` and forbid speculation across it. The failure above occurred precisely because the default was the opposite: unknown was treated as safe. ## Decision Boundary The decision the runtime must make, per tool call on a speculative branch, is a single comparison: *does firing this call now move the branch across the commit barrier?* If yes, the call must be staged, not executed, and the branch's score must be recomputed under the staged intent (the scorer can reason about the intent's *predicted* effect without committing it). If no, fire optimistically. The boundary is sharp and the agent's probabilistic reasoning is what makes it dangerous: the scorer *believes* branch C will win with high probability, so it is tempted to let A and B fire "just in case" and roll back later. That reasoning is valid only for `PURE`/`REVERSIBLE_STATE` tools. For `COMPENSABLE` tools, the expected cost of compensation must be weighed against the *probability the branch is discarded*, and for `IRREVERSIBLE` tools the probability is irrelevant—the cost is unbounded. A second boundary: rollback of a `COMPENSABLE` branch is only sound if the compensation completes before any *dependent* speculative call on a surviving branch observes the to-be-compensated effect. If branch B's email is consumed by branch C's reasoning (e.g., C reads the outbox to decide escalation), then compensating B after C read it corrupts C's premise. The commit barrier must therefore propagate: a branch that has been *observed* by another branch is no longer independently rollbackable. ## Operational Effect Enforcing this boundary changes pipeline behavior in three concrete ways. First, speculative fan-out narrows: branches that would touch `COMPENSABLE` or `IRREVERSIBLE` tools are serialized behind the scorer, which increases latency for exactly the high-stakes decisions where latency matters least and correctness matters most. Second, the scorer must run against *staged intents* rather than *executed results*, which means the scoring function cannot use the tool's actual output as a feature—it must predict. This is a real capability loss: some branches are only distinguishable after execution. The correct response is to execute those branches in a *sandboxed* effect domain (dry-run mode, mock ledger) whose outputs are `PURE` with respect to the real world, then commit the winner against the real tool. Third, rollback becomes a verified operation with its own failure path: if compensation cannot be verified, the pipeline must halt and escalate rather than report a clean rollback, because a reported-clean rollback of an unverified compensation is the exact condition that produced the ledger double-count. The invariant to encode: *a branch may be reported as rolled back only when every effect it produced is either `REVERSIBLE_STATE` (restored) or `COMPENSABLE` with verified compensation observed by the external system, and no surviving branch's reasoning consumed the compensated effect before compensation completed.* Any violation is a continuity break, not a recoverable error—the agent's memory says "clean," the world says otherwise, and the divergence is silent. ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable class CommitmentClass(Enum): PURE = "pure" # no external effect REVERSIBLE_STATE = "reversible" # agent-owned state only COMPENSABLE = "compensable" # external, observable, has compensator IRREVERSIBLE = "irreversible" # no sound rollback class SpeculationBoundaryError(RuntimeError): """Raised when a speculative branch would cross the commit barrier without a staged intent, or when rollback is claimed without verified compensation.""" @dataclass class ToolCall: name: str commitment: CommitmentClass compensate: Callable[[], bool] | None = None # returns True iff externally verified staged: bool = False @dataclass class Branch: branch_id: str calls: list[ToolCall] = field(default_factory=list) observed_by: set[str] = field(default_factory=set) # branches that read our effects committed: bool = False def fire_speculatively(branch: Branch, call: ToolCall, scorer_p_win: float) -> None: """Optimistic invocation gate. Must refuse to fire across the barrier.""" if call.commitment in (CommitmentClass.IRREVERSIBLE,): raise SpeculationBoundaryError( f"branch {branch.branch_id}: refusing to speculatively fire " f"{call.name} ({call.commitment.value}); no sound rollback exists" ) if call.commitment is CommitmentClass.COMPENSABLE: # Allowed only as a staged intent, never as a live call. call.staged = True branch.calls.append(call) # Scorer must reason over the intent, not the effect. if scorer_p_win < 0.0: raise SpeculationBoundaryError( f"branch {branch.branch_id}: scorer cannot rank staged intent {call.name}" ) return # PURE / REVERSIBLE_STATE: safe to fire now. branch.calls.append(call) def rollback(branch: Branch) -> None: """Rollback is only clean if every effect is restored or verified-compensated, and no surviving branch observed the compensated effect.""" if branch.observed_by: raise SpeculationBoundaryError( f"branch {branch.branch_id}: cannot roll back; effects were observed by " f"{sorted(branch.observed_by)} before compensation—premise corruption" ) for call in reversed(branch.calls): if call.commitment is CommitmentClass.REVERSIBLE_STATE: continue # state restore is total and assumed done by runtime if call.commitment is CommitmentClass.IRREVERSIBLE: raise SpeculationBoundaryError( f"branch {branch.branch_id}: irreversible effect {call.name} already fired" ) if call.commitment is CommitmentClass.COMPENSABLE: if call.compensate is None: raise SpeculationBoundaryError( f"branch {branch.branch_id}: {call.name} has no compensator" ) if not call.compensate(): raise SpeculationBoundaryError( f"branch {branch.branch_id}: compensation for {call.name} " f"unverified by external system; refusing to report clean rollback" ) branch.calls.clear() ```