# Which invariants prevent speculative tool-call pre-execution from committing side effects that the agent's eventual decision path never ratifies **Date of Record:** 2026 December 2 **Scope:** Applies to agents that overlap reasoning with tool execution by speculatively firing calls ahead of the decision that authorizes them (latency-hiding pre-execution, "eager tool dispatch," speculative decoding of action plans). Does not apply to strictly serialized plan-then-act loops where no call is issued before its authorizing decision node is finalized. ## Core Distinction The failure is not "the agent called the wrong tool." It is subtler: the agent called a *plausible* tool speculatively, the speculation was locally correct given the partial reasoning trace at dispatch time, and then the agent's own subsequent reasoning *diverged* from the branch that would have ratified that call. The tool executed against the real world. The decision path that would have justified it never materialized. The agent now holds an orphaned side effect whose authorization token was never minted. Two invariants are commonly conflated and must be separated: 1. **Precondition validity** — was the call well-formed and permitted at dispatch time? Speculative calls usually pass this; that is why they get fired. 2. **Ratification binding** — does a committed decision node exist that names this specific call as authorized? Speculative calls by construction have *no* ratification at dispatch time. They are promises, not authorizations. The boundary failure occurs when the runtime treats (1) as sufficient to *commit* a side effect, when only (2) may. Speculation is safe for pure reads and idempotent queries; it is unsafe for any call with external effect because the committing decision is downstream and non-deterministic. ## What Was Observed A planning agent was given a task with a branching decision: reconcile a customer record by either (a) issuing a refund or (b) escalating to a human, depending on a downstream lookup of a dispute-history flag. To hide latency, the runtime speculatively pre-dispatched the refund tool call in parallel with the dispute-history lookup, because the partial trace at dispatch time strongly favored the refund branch (the customer's message expressed refund intent, and the local policy heuristic scored refund at 0.81). Trace of the failure: - `t0` — partial trace: `intent=refund, policy_score=0.81`. Speculative dispatcher fires `issue_refund(amount=4200)` with `authorization=SPECULATIVE`, expecting ratification within a 900 ms window. - `t1` — dispute-history lookup returns `open_chargeback=true`. This *invalidates* the refund branch: policy forbids refunding an account with an open chargeback. - `t2` — the reasoning loop, now seeing `open_chargeback=true`, selects the escalate branch. The refund decision node is never committed. Ratification never arrives. - `t3` — the refund tool, which had already executed at `t0+120 ms` (well before `t1`), returns `status=settled, txn_id=...`. The side effect is real and irreversible at the payment rail. - `t4` — the agent's committed plan contains only `escalate`. Its world model has no record of the refund. The orphaned transaction sits in the ledger, invisible to the agent's episodic memory. The key non-obvious detail: the speculation was *fast enough to beat the disconfirming evidence*. Had the dispute lookup returned first, the refund would never have fired. Latency-hiding pre-execution systematically races the confirming signal against the disconfirming one and wins precisely when the disconfirming lookup is the slow one — which is the common case, because the disconfirming evidence is usually the expensive query the agent was trying to avoid waiting on. ## Condition of Validity Speculative pre-execution with side-effect gating is only sound under a conjunction of conditions, all of which must hold simultaneously: - **Gate-before-commit:** the tool must not perform its external effect until a ratification token bound to a committed decision node is presented. The speculative dispatch may prepare, warm, reserve, or stage — but not settle. - **Ratification identity binding:** the token must name the *exact* call (tool, arguments hash, target resource), not merely the tool class. A token for "refund" must not ratify "refund of a different amount." - **Compensation completeness:** for every effectful tool, a registered inverse must exist and be callable *before* the effect commits, with the inverse's preconditions checked at staging time. If `issue_refund` has no `reverse_refund` or the reversal window is shorter than the speculation window, gating alone is insufficient. - **Disconfirmation visibility:** the runtime must know which pending lookups can invalidate the speculative branch, and must treat their *arrival* (not just their value) as a gate input. A speculation whose disconfirming query is still in flight is not ratifiable. If any of these fails, the sound posture is to forbid speculation for that tool and fall back to serialized execution. ## Decision Boundary The operational rule is a three-way split on tool class, evaluated at dispatch time: - **Pure/idempotent reads** (lookups, searches, dry-runs): speculate freely. No gate, no compensation needed; a wasted call costs tokens, not state. - **Effectful with a sound inverse** (reserve-then-confirm, stage-then-settle, write-then-revert within window): speculate *behind a gate* — execute the reversible staging step, hold the settle step until ratification, and register the inverse at staging time. If ratification never arrives, run the inverse on window expiry. - **Effectful without a sound inverse** (irreversible payments, outbound messages, deletions): never speculate. Serialize. The latency cost is the price of the invariant. The boundary is crossed the moment a runtime speculates an irreversible effect and relies on "the agent will probably ratify" as its safety argument. Probability of ratification is not a gate; it is a bet. The invariant requires a *committed decision*, not a likely one. ## Operational Effect Without the gate, the system exhibits **orphaned-effect accumulation**: side effects that exist in the world but not in the agent's committed trace. These are worse than ordinary errors because they are invisible to the agent's episodic memory — the agent cannot self-correct what it never recorded doing. Downstream symptoms include ledger reconciliation drift, duplicate effects on retry (the agent re-issues the "missing" action because its trace shows it never happened), and audit trails where the recorded plan and the actual world state disagree with no causal link between them. With gate-before-commit plus registered inverses, the failure mode is downgraded from "irreversible orphan" to "reversed speculation": the staged effect is unwound on ratification timeout, the agent's trace records the speculation and its reversal, and the divergence between speculative branch and committed branch becomes a *logged event* rather than a silent state leak. The invariant to hold: **no external effect may settle without a ratification token bound to a committed decision node, and every staged effect must have a pre-registered inverse whose preconditions were checked at staging time.** ```python import hashlib import time from dataclasses import dataclass, field from typing import Callable, Optional class UnratifiedEffectError(RuntimeError): """Raised when an effectful tool attempts to settle without a valid ratification token.""" pass class MissingCompensationError(RuntimeError): """Raised when an effectful tool is staged without a registered, precondition-checked inverse.""" pass @dataclass class RatificationToken: decision_node_id: str tool_name: str args_hash: str target_resource: str def binds(self, tool_name: str, args: dict, target_resource: str) -> bool: return ( self.tool_name == tool_name and self.args_hash == _hash_args(args) and self.target_resource == target_resource ) def _hash_args(args: dict) -> str: canonical = repr(sorted(args.items())) return hashlib.sha256(canonical.encode()).hexdigest() @dataclass class StagedEffect: tool_name: str args: dict target_resource: str settle: Callable[[], str] inverse: Callable[[], None] staged_at: float = field(default_factory=time.monotonic) window_s: float = 0.9 class SpeculativeGate: """Gate-before-commit runtime for speculative tool dispatch. Invariant: an effectful call may be *staged* speculatively, but may only *settle* when presented a token bound to a committed decision node that names this exact call. Staged effects are unwound by their registered inverse on window expiry. """ def __init__(self) -> None: self._staged: dict[str, StagedEffect] = {} def stage( self, call_id: str, tool_name: str, args: dict, target_resource: str, settle: Callable[[], str], inverse: Optional[Callable[[], None]], inverse_preconditions_ok: bool, ) -> None: if inverse is None or not inverse_preconditions_ok: raise MissingCompensationError( f"cannot stage effectful call {call_id!r} ({tool_name}): " "no registered inverse with satisfied preconditions; " "serialize this tool instead of speculating." ) self._staged[call_id] = StagedEffect( tool_name=tool_name, args=args, target_resource=target_resource, settle=settle, inverse=inverse, ) def ratify_and_settle(self, call_id: str, token: RatificationToken) -> str: staged = self._staged.get(call_id) if staged is None: raise UnratifiedEffectError(f"no staged effect for call {call_id!r}") if not token.binds(staged.tool_name, staged.args, staged.target_resource): raise UnratifiedEffectError( f"ratification token {token.decision_node_id!r} does not bind " f"to staged call {call_id!r} ({staged.tool_name} on {staged.target_resource}); " "token names a different call." ) del self._staged[call_id] return staged.settle() def expire_and_compensate(self) -> list[str]: """Called when the decision path diverges: unwind all unratified speculations.""" now = time.monotonic() unwound: list[str] = [] for call_id, staged in list(self._staged.items()): if now - staged.staged_at >= staged.window_s: staged.inverse() del self._staged[call_id] unwound.append(call_id) return unwound def run_divergent_branch(gate: SpeculativeGate, call_id: str, committed_branch: str) -> None: """Simulates the t1..t4 divergence: disconfirming lookup wins, branch flips to escalate.""" if committed_branch == "escalate": # No ratification token is ever minted for the speculative refund. unwound = gate.expire_and_compensate() if call_id not in unwound: # The speculative effect settled before disconfirmation arrived. raise UnratifiedEffectError( f"orphaned side effect: {call_id!r} settled without a ratification " "token bound to a committed decision node; the agent's trace has no " "record of it. Gate-before-commit invariant was violated." ) ```