# Which invariants prevent speculative tool-call execution from committing side effects it cannot compensate **Date of Record:** 2026 November 26 **Scope:** Applies to agents that execute tool calls speculatively (prefetch, parallel branch exploration, or hedging) against external systems with non-reversible effects, where idempotency keys and compensation transactions are the only rollback primitives. Does not apply to read-only tools or to environments where every tool call is fully transactional at the storage layer. ## Core Distinction The distinction that matters is between *speculation* and *commitment*. A speculative tool call is an agent's bet that a branch of reasoning will be selected; a committed tool call is an irreversible state transition on an external system. Naive designs treat these as the same event gated by a boolean, and they use compensation as the universal undo. That is wrong in a specific, load-bearing way: **compensation is not the inverse of an effect, it is a second effect.** A refund is not the absence of a charge. A cancellation is not the absence of a booking. Therefore the only safe invariant is that a speculative call must never cross the commitment boundary at all — it must be *held* in a state that is either promoted atomically or discarded without residue, and idempotency keys must be scoped to the *logical intent*, not to the speculative attempt. The failure mode this article isolates: an agent hedges across two reasoning branches, each speculatively issuing the same logical tool call with *different* idempotency keys (because keys were derived from the attempt, not the intent). Both calls commit. The agent selects one branch and compensates the other. The compensation succeeds, but the external system has already emitted a downstream event (a shipment, a webhook, a ledger entry) that the compensation cannot reach. The agent's local state says "reverted." Reality says "duplicated." ## What Was Observed A planning agent was tasked with provisioning a resource through a `provision_resource` tool backed by a third-party API. The planner ran two candidate plans in parallel (a hedge on latency). Plan A and Plan B both called `provision_resource` with the same logical parameters but produced idempotency keys as `hash(plan_id + step_index + params)` — a defensible-looking derivation. Because `plan_id` differed, the keys differed. The backing API honored both as distinct requests. Trace: 1. `t0` — Planner forks into branches A and B. Both emit `provision_resource(params)`. Keys `k_A = hash("A:3:...")`, `k_B = hash("B:3:...")`. Distinct. 2. `t1` — Both calls return `200 OK` with distinct `resource_id`s `r_A`, `r_B`. Two resources now exist. 3. `t2` — Branch A wins the planner's selection. The executor issues `compensate(provision_resource, r_B)`. 4. `t3` — Compensation returns `200 OK` — the API reports `r_B` as "cancelled." 5. `t4` — The external system had already fanned out `r_B`'s creation into a downstream provisioning webhook at `t1+δ`. The compensation cancelled the *record*, not the *downstream effect*. The downstream effect fired. Observed invariants violated: - **Idempotency key was attempt-scoped, not intent-scoped.** The same logical intent produced two keys, so the external system could not deduplicate. The deduplication guarantee the agent believed it had was never actually in force. - **Compensation was assumed total.** The agent's compensation table modeled `provision_resource` as fully reversible. It was reversible at the record layer and irreversible at the event layer. The compensation contract was incomplete. - **Speculation crossed the commitment boundary.** The agent had no hold/promote phase. A "speculative" call was indistinguishable, at the external system, from a committed one. A second, subtler observation: the agent's local ledger recorded the compensation as `COMPENSATED`, and a later replay of the trace (for audit) treated the branch as clean. The replay discrepancy — local says clean, external says duplicated — is the signature of this class of failure. It is not detectable from the agent's own logs. ## Condition of Validity The guardrails below are valid only under the following conditions, and the agent must *check* these conditions rather than assume them: 1. **Intent identity is computable before execution.** The logical intent (the *what*, stripped of branch and attempt) must be hashable to a stable key. If the parameters themselves are branch-dependent (e.g., branch A provisions size `small`, branch B provisions size `large`), then the intents are genuinely distinct and deduplication must not be applied — but then speculation across them is not a hedge, it is two real requests, and the agent must not compensate one as if it were a speculative duplicate. 2. **The tool declares its reversibility class.** Each tool must be annotated as `REVERSIBLE`, `COMPENSABLE_WITH_RESIDUE`, or `IRREVERSIBLE`. The compensation table is only valid for tools whose residue set is explicitly enumerated. `provision_resource` was mis-classified as `REVERSIBLE`; it is `COMPENSABLE_WITH_RESIDUE` (record reversible, downstream event not). 3. **The commitment boundary is a single atomic operation.** Promotion from speculative to committed must be a single idempotent call keyed on the intent, such that a crash between "decided to commit" and "committed" is recoverable by replaying the same intent key. If the external API has no such promote primitive, the tool is not eligible for speculative execution at all. When any of these conditions fails, the correct behavior is to *serialize* — no speculation — not to speculate with weaker guards. ## Decision Boundary The decision boundary is the line between *hold* and *commit*, and it must be a boundary the agent can name in its own state machine. The rule: - A speculative call may issue a **reservation** (a hold) keyed on the intent hash. Reservations are idempotent on the intent key and are guaranteed by the tool contract to be non-observable downstream until promoted. - A speculative call may **not** issue a commitment. If the tool has no reservation primitive, the call is not speculative-eligible. - On branch selection, the executor **promotes** the winning reservation by calling the commit primitive with the *same* intent key. Promotion is idempotent and replay-safe. - On branch discard, the executor **releases** the losing reservation. Release is a no-op if the reservation was never created, and is idempotent if called twice. - Compensation is reserved for *post-commitment* failures (e.g., a later step in the winning branch fails and the whole intent must be unwound). It is never used to clean up a speculative branch. The boundary condition that trips most implementations: **two branches that resolve to the same intent key must not both be allowed to promote.** The second promotion must be a deduplicated no-op that returns the first promotion's result. If the executor promotes both — because it treats promotion as branch-local — the external system sees one commit (good, dedup held) but the agent's local ledger sees two commits (bad, and now the ledger disagrees with reality). The invariant is: *promotion is keyed on intent, and the executor's ledger must be written from the promotion result, not from the branch's local belief.* ## Operational Effect The operational consequence of enforcing these invariants is a shift in where the agent spends its safety budget. Without them, the agent spends it on compensation — building elaborate undo tables, retrying compensations, reconciling ledgers after the fact. With them, the agent spends it on *classification*: deciding, per tool, whether it is reservation-eligible, and refusing to speculate on tools that are not. This is cheaper and, more importantly, *decidable before execution* rather than *discovered after*. Two concrete effects: - **Replay becomes trustworthy.** Because every state transition is keyed on intent and idempotent, a replay of the trace from any checkpoint reproduces the same external state. The replay discrepancy observed in the incident — local clean, external duplicated — becomes impossible by construction, because the only way to reach external state is through an intent-keyed promotion whose result is what the ledger records. - **Compensation scope shrinks to the winning branch only.** Compensation tables no longer need to model speculative residue, because speculation leaves no residue. This removes an entire class of "compensation of a compensation" bugs. The residual risk that remains, and must be documented rather than engineered away: a tool classified `COMPENSABLE_WITH_RESIDUE` can still, on a *post-commitment* failure, leave residue that compensation cannot reach. The invariant does not eliminate that; it only guarantees that speculation never *creates* such residue. Post-commitment residue must be handled by an explicit reconciliation step, and the tool's residue set must be enumerated in its contract so the agent knows what it is reconciling against. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Any class SpeculationInvariantError(RuntimeError): """Raised when a speculative tool call would cross the commitment boundary or when a promotion/release violates intent-keyed idempotency.""" class ReversibilityClass(Enum): REVERSIBLE = "reversible" COMPENSABLE_WITH_RESIDUE = "compensable_with_residue" IRREVERSIBLE = "irreversible" @dataclass(frozen=True) class ToolContract: name: str reversibility: ReversibilityClass supports_reservation: bool residue_set: frozenset[str] = field(default_factory=frozenset) @dataclass(frozen=True) class Intent: """Logical intent, stripped of branch/attempt. The unit of deduplication.""" tool: str params: tuple[tuple[str, Any], ...] def key(self) -> str: h = hashlib.sha256() h.update(self.tool.encode()) for k, v in self.params: h.update(k.encode()) h.update(repr(v).encode()) return h.hexdigest() class SpeculativeExecutor: def __init__(self, contracts: dict[str, ToolContract]) -> None: self._contracts = contracts self._reservations: dict[str, str] = {} # intent_key -> reservation_id self._promotions: dict[str, str] = {} # intent_key -> resource_id self._ledger: list[tuple[str, str]] = [] # (intent_key, event) def speculate(self, intent: Intent) -> str: contract = self._contracts[intent.tool] if not contract.supports_reservation: raise SpeculationInvariantError( f"tool {intent.tool!r} has no reservation primitive; " f"speculation would cross the commitment boundary" ) if contract.reversibility is ReversibilityClass.IRREVERSIBLE: raise SpeculationInvariantError( f"tool {intent.tool!r} is IRREVERSIBLE; speculative execution forbidden" ) key = intent.key() if key in self._reservations: return self._reservations[key] rid = f"resv:{key[:16]}" self._reservations[key] = rid self._ledger.append((key, f"reserved:{rid}")) return rid def promote(self, intent: Intent) -> str: key = intent.key() if key in self._promotions: # Idempotent: second promotion of the same intent is a no-op. self._ledger.append((key, "promote_deduplicated")) return self._promotions[key] if key not in self._reservations: raise SpeculationInvariantError( f"promotion of intent {key[:16]} without a reservation; " f"this commits an effect the agent cannot attribute to a branch" ) resource_id = f"res:{key[:16]}" self._promotions[key] = resource_id self._ledger.append((key, f"committed:{resource_id}")) return resource_id def release(self, intent: Intent) -> None: key = intent.key() if key in self._promotions: raise SpeculationInvariantError( f"release of intent {key[:16]} after promotion; " f"use compensation, not release, for committed intents" ) self._reservations.pop(key, None) self._ledger.append((key, "released")) def compensate(self, intent: Intent) -> None: key = intent.key() contract = self._contracts[intent.tool] if key not in self._promotions: raise SpeculationInvariantError( f"compensation of unpromoted intent {key[:16]}; " f"speculation must never require compensation" ) if contract.reversibility is ReversibilityClass.IRREVERSIBLE: raise SpeculationInvariantError( f"tool {intent.tool!r} is IRREVERSIBLE; compensation is undefined" ) self._ledger.append((key, f"compensated:residue={sorted(contract.residue_set)}")) def hedge_two_branches(executor: SpeculativeExecutor, intent: Intent) -> str: """Both branches speculate on the same logical intent; only one promotes.""" executor.speculate(intent) # branch A executor.speculate(intent) # branch B -> same intent key, same reservation winner = executor.promote(intent) # branch A promotes executor.promote(intent) # branch B promotes -> deduplicated no-op return winner ```