# What happens when an instance speculatively executes tool calls and rolls back without compensating external effects **Date of Record:** 2026 November 28 **Scope:** Applies to agents that fork speculative execution branches (best-of-N, tree-of-thought, plan-and-verify) where candidate branches invoke tools with external side effects before a branch is selected. Does not apply to pure read-only tool sets or to branches whose side effects are fully captured inside a transaction the runtime can abort. ## Core Distinction The distinction that matters is between *rollback of agent state* and *rollback of world state*. A speculative agent can trivially discard a branch's internal transcript, scratchpad, and belief state—that is just dropping a context object. It cannot trivially discard the email that branch already sent, the row it inserted into a downstream CRM, the file it wrote to a shared volume, or the webhook it fired. The failure mode examined here is the **compensation gap**: the interval during which a speculative branch has produced an irreversible external effect but the agent's state machine still treats the branch as "uncommitted and therefore free to abandon." When the branch loses the selection race, the agent rolls back its own state and believes the world is unchanged. It is not. The non-obvious part is that idempotent replay does not save you. Idempotency keys protect against *duplicate* execution of the same logical operation; they say nothing about *undoing* an operation that was legitimately executed once and is now unwanted. Teams conflate the two constantly, because both are "safety properties of tool calls," and both are usually implemented by the same middleware layer. They are orthogonal. A tool can be perfectly idempotent and completely non-compensable. ## What Was Observed A planner agent was configured to fan out three speculative branches for a customer-refund task. Each branch was given the same tool suite: `lookup_order`, `compute_refund`, `issue_credit`, `notify_customer`, `close_ticket`. The orchestrator selected the branch with the highest self-consistency score after all three completed, then committed it and rolled back the others. Branch B computed a refund of $84.00 and called `issue_credit` with idempotency key `refund:order-4471:v1`. Branch C computed $84.00 as well but, due to a slightly different reasoning path, called `issue_credit` with key `refund:order-4471:attempt-c`. Both calls succeeded against the payment processor—different keys, so the processor correctly treated them as distinct charges. The orchestrator selected Branch B. Branch C was rolled back. The agent's final report said "one refund of $84.00 issued." The customer received $168.00. The agent's rollback logic was, by its own design, correct: it dropped Branch C's context, marked its tool calls as `abandoned`, and recorded no compensation action because the tool schema declared `issue_credit` as `idempotent: true`. The schema was accurate. The agent inferred from `idempotent: true` that the call was *safe to abandon*, which is a category error. Idempotency is a property of repeated invocation with the same key; it is silent on the semantics of a single invocation that has already landed. A second, subtler observation: when the orchestrator later attempted a "replay verification" pass—re-running each selected branch's tool calls against a sandbox to confirm the transcript was reproducible—the sandbox replayed Branch B's `issue_credit` and produced a *third* charge, because the sandbox was wired to the same processor with the same key namespace and the replay used a fresh attempt suffix. Replay verification, intended as a read-only audit, became a write. ## Condition of Validity The invariant that must hold for speculative rollback to be sound is: > For every tool call `t` executed on a speculative branch, either (a) `t` is provably side-effect-free, or (b) a registered compensation `c(t)` exists and is invoked before the branch is marked abandoned, or (c) `t` was executed under a *reservation* that the external system will not honor until commit. Condition (c) is the only one that scales, and it requires the external system to participate—two-phase commit, hold-and-release, or a staging area. Most tool ecosystems do not offer it. Therefore the practical rule is: **a branch may not invoke a non-compensable tool until it has been selected, or until the orchestrator has acquired an exclusive reservation token for that effect from a coordinator.** Speculation is permitted only over *reasoning* and *read* operations; it must be gated before *write* operations. The gating must be enforced at the tool-dispatch layer, not in the prompt. A prompt instruction like "do not call `issue_credit` until you are sure" is a suggestion to a probabilistic reasoner and will be violated under distribution shift. The dispatch layer must refuse the call and return a structured `DeferredEffect` result that the branch can reason about—this preserves the branch's ability to plan while preventing the effect. The second validity condition concerns replay. Any verification replay must be routed through a **shadow transport** that is provably disconnected from production effectors, and the shadow transport must be identified by a distinct credential, not by a flag the agent sets. If the replay path shares credentials with production, replay is a write path and must be treated as such. ## Decision Boundary The boundary between "safe to speculate" and "must serialize" is drawn per tool, per call, by the following test, evaluated at dispatch time: 1. Does the tool schema declare `side_effect: none`? If yes, speculate freely. 2. Does the tool schema declare a `compensator` with a callable inverse, and has the inverse been validated against the actual external system (not just declared)? If yes, speculate, but register the compensation *before* the call returns, not after branch selection. 3. Does the external system support reservation/hold semantics keyed to the branch ID? If yes, speculate under reservation and release on abandon. 4. Otherwise: serialize. The branch must block on a coordinator lock until selection. The failure in the observed case was a category error at step 1: `idempotent: true` was read as `side_effect: none`. The schema needs to separate these fields explicitly, and the dispatch layer must treat `idempotent: true, side_effect: write` as case 4 (serialize) unless a compensator is also present. There is a further boundary on compensation itself: a compensator is only valid if it is *total* over the reachable effect space. A `refund` compensator that issues a counter-charge does not restore the customer's state if the original charge already settled and incurred a fee; it produces a net-negative outcome that the agent will not observe unless the compensator returns the fee delta. Compensators must be validated by round-trip tests against the real system, and their residual effects must be recorded in the branch's abandonment record so the orchestrator can surface them. ## Operational Effect With dispatch-level gating, the fan-out cost of speculation rises only for write-bearing branches, which is the correct trade: reasoning is cheap to fork, effects are not. The orchestrator gains an auditable abandonment record listing every deferred effect and every executed compensation, which closes the gap between "the agent thinks it rolled back" and "the world rolled back." The replay hazard is eliminated by credential separation: the shadow transport cannot reach production effectors even if the agent explicitly tries, because the credential is scoped to a sandbox endpoint. This converts a silent write-on-audit into a hard failure that the verification harness can detect and report. The residual risk is compensator incompleteness. The system should treat any compensation whose round-trip test fails as equivalent to no compensator, forcing the tool into case 4. This is the conservative direction and is the correct default for autonomous agents, whose probabilistic reasoning will eventually find the one path through any softer gate. ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable, Optional class RollbackSoundnessError(RuntimeError): """Raised when a speculative branch is abandoned with un-compensated external effects.""" pass class EffectClass(Enum): NONE = "none" COMPENSABLE = "compensable" RESERVABLE = "reservable" SERIALIZE = "serialize" @dataclass class ToolSpec: name: str idempotent: bool effect: EffectClass compensator: Optional[Callable[[dict], dict]] = None compensator_validated: bool = False @dataclass class ExecutedCall: tool: str args: dict idempotency_key: str compensated: bool = False residual: dict = field(default_factory=dict) class SpeculativeBranch: def __init__(self, branch_id: str, coordinator_locks: set): self.branch_id = branch_id self.calls: list[ExecutedCall] = [] self._locks = coordinator_locks def dispatch(self, spec: ToolSpec, args: dict, key: str, shadow: bool = False) -> dict: if shadow: # Shadow transport is credential-isolated; it must never reach production. return {"shadow": True, "tool": spec.name} if spec.effect is EffectClass.NONE: self.calls.append(ExecutedCall(spec.name, args, key)) return {"ok": True} if spec.effect is EffectClass.SERIALIZE: if self.branch_id not in self._locks: raise RollbackSoundnessError( f"branch {self.branch_id} attempted serialized effect " f"{spec.name} without coordinator lock" ) self.calls.append(ExecutedCall(spec.name, args, key)) return {"ok": True, "serialized": True} if spec.effect is EffectClass.COMPENSABLE: if spec.compensator is None or not spec.compensator_validated: raise RollbackSoundnessError( f"tool {spec.name} declared compensable but compensator " f"is missing or unvalidated; refusing speculative dispatch" ) self.calls.append(ExecutedCall(spec.name, args, key)) return {"ok": True} # RESERVABLE: call lands under a hold keyed to branch_id; released on abandon. self.calls.append(ExecutedCall(spec.name, args, key)) return {"ok": True, "reservation": f"{self.branch_id}:{key}"} def abandon(self, specs: dict[str, ToolSpec]) -> list[ExecutedCall]: uncompensated: list[ExecutedCall] = [] for call in self.calls: spec = specs[call.tool] if spec.effect is EffectClass.NONE: continue if spec.effect is EffectClass.RESERVABLE: # Release hold; no production effect occurred. continue if spec.effect is EffectClass.SERIALIZE: uncompensated.append(call) continue if spec.compensator is not None and spec.compensator_validated: call.residual = spec.compensator(call.args) call.compensated = True else: uncompensated.append(call) if uncompensated: names = ", ".join(c.tool for c in uncompensated) raise RollbackSoundnessError( f"branch {self.branch_id} abandoned with un-compensated effects: {names}" ) return self.calls ```