# Which invariants prevent speculative tool-call pre-execution from leaking side effects before commit gating **Date of Record:** 2026 November 23 **Scope:** Applies to agents that speculatively pre-execute tool calls (parallel or ahead-of-need) under an effect-isolation layer with a commit gate. Does not apply to purely read-only tool surfaces or to agents that execute tools strictly serially with no speculation. ## Core Distinction There are two ways to make a speculative tool call "safe," and conflating them is the root of the failure mode. The first is **effect isolation**: the call runs against a sandboxed or buffered effect target so that nothing observable to the outside world happens until commit. The second is **commit gating**: a decision point that either promotes the buffered effect to reality or discards it. Isolation without gating leaks on any path that bypasses the gate. Gating without true isolation leaks because the "isolated" call already mutated shared state that the gate cannot roll back. The non-obvious boundary is this: **isolation is only sound if the set of effects a tool can produce is fully enumerable and interceptable at the boundary the isolation layer wraps.** The moment a speculative call produces an effect through a channel the isolator does not model—an outbound network side effect, a cache write, a rate-limit counter, an idempotency key reservation, a downstream service's internal state—the commit gate becomes a fiction. It decides about a subset of effects while the unmodeled remainder has already escaped. This is the **unmodeled-egress invariant**: *a commit gate can only govern effects that the isolation boundary observed.* ## What Was Observed An agent was speculatively pre-executing a payment-intent tool (`create_payment_intent`) in parallel with a reasoning branch that had not yet decided whether to charge. The tool was wrapped by an isolation layer that intercepted the HTTP client and buffered the request body, deferring the actual `POST` until commit. On the "abandon" branch, the buffered request was discarded. The agent logged the speculative call as cleanly rolled back. It was not. The tool's client library performed two operations before the intercepted `POST`: it (1) reserved an idempotency key in a local durable store keyed by `(merchant, amount, nonce)`, and (2) incremented a client-side rate-limit token bucket persisted to disk. The isolator wrapped the transport, not the client. On the abandoned branch, the idempotency reservation remained. When the agent later made a legitimate, committed call with a colliding nonce—because the nonce was derived deterministically from task state that had not changed—the downstream service saw the idempotency key already reserved from the "discarded" attempt and returned the *prior* speculative response, which had never actually been sent to the payment processor. The committed call returned a success payload for a charge that did not exist. The failure trace: 1. Speculative call → transport intercepted, body buffered, **idempotency reservation written** (unmodeled egress). 2. Reasoning branch abandons → buffered body dropped, gate reports "discarded." 3. Task continues, derives same nonce, issues committed call. 4. Transport now unblocked → `POST` sent with idempotency key `K`. 5. Downstream sees `K` in "reserved/known" state from step 1's reservation handshake (the reservation itself had synced), returns cached speculative payload. 6. Agent records payment success. No charge occurred. The gate did exactly what it was designed to do. The invariant it relied on—that all effects flow through the wrapped transport—was false. ## Condition of Validity Speculative pre-execution with commit gating is sound **only if all three hold**: - **Egress completeness:** every effect the tool can produce is either (a) routed through the isolation boundary, or (b) proven side-effect-free and commutable. Idempotency-key reservation, rate-limit accounting, nonce burning, cache population, and audit-log emission are all effects and must be classified. - **Gate dominance:** no effect escapes the isolation boundary before the gate decides. Any "reservation," "pre-check," or "handshake" that the client performs eagerly violates dominance unless it too is buffered. - **Commit idempotency under replay:** if a speculative effect *did* partially escape, replaying the committed call must be safe. This requires the commit path to carry a nonce that is *regenerated* on commit, not inherited from the speculative attempt, so that downstream idempotency cannot alias a discarded attempt to a committed one. When any of these fails, the gate's "discard" verdict is only advisory. The correct classification of a tool for speculation is therefore not binary (safe/unsafe) but a triple: `(effects_modeled, gate_dominates, replay_safe)`. A tool failing any element must be executed serially with no speculation, or its client must be wrapped at a boundary below the eager-effect layer. ## Decision Boundary The decision to speculatively pre-execute a tool must be gated on a **static effect manifest** declared per tool, not on runtime observation. Runtime observation is too late: by the time you observe an unmodeled egress, the reservation is written. The boundary condition is: - If the tool's manifest declares `effects ⊆ modeled_effects` **and** the isolation wrapper sits below every eager client behavior (or the client is proven free of eager effects), speculate freely. - If the manifest is incomplete or the wrapper sits above any eager effect, **do not speculate**; fall through to serial execution. - If speculation is already in flight when a manifest violation is detected (e.g., the client library version changed and now eagerly reserves keys), the agent must **poison the nonce space** used by the speculative attempt—force regeneration of any idempotency keys, nonces, or tokens before the next committed call—rather than trusting the gate's discard. The subtle trap: agents tend to treat "the gate said discard" as a clean slate. It is not. The gate governs only what it saw. The invariant to enforce is that **the discard path must invalidate every identifier the speculative attempt could have leaked**, whether or not the isolator believes it leaked anything. ## Operational Effect The practical consequence is a mandatory **nonce regeneration on commit** and a **manifest-completeness check before any speculative dispatch**. Without these, the agent exhibits a specific, reproducible pathology: it reports success for operations that never happened, and it does so *more* often as speculation parallelism increases, because more speculative attempts mean more leaked reservations aliasing committed calls. The failure is silent—no exception, no error code—because the downstream idempotency layer is behaving correctly given the state it was handed. The guardrail is not "wrap more things." It is: **treat the commit gate as governing a declared effect set, and force identifier regeneration across the speculate/commit boundary so that no leaked reservation can alias a committed call.** An agent that cannot prove egress completeness for a tool must not speculate on it, and an agent that has speculated on a tool whose completeness later becomes doubtful must regenerate, not discard-and-trust. ```python from dataclasses import dataclass, field from typing import Callable class SpeculationEgressViolation(RuntimeError): """Raised when a speculative call leaked an effect outside the isolation boundary.""" pass @dataclass class EffectManifest: modeled_effects: frozenset[str] eager_client_effects: frozenset[str] = field(default_factory=frozenset) def is_speculation_safe(self) -> bool: # Speculation is safe only if every eager client effect is modeled # by the isolation boundary. Any unmodeled eager effect leaks. return self.eager_client_effects <= self.modeled_effects @dataclass class SpeculativeAttempt: tool: str nonce: str manifest: EffectManifest class CommitGate: def __init__(self) -> None: self._pending: dict[str, SpeculativeAttempt] = {} def speculate(self, attempt: SpeculativeAttempt) -> None: if not attempt.manifest.is_speculation_safe(): unmodeled = attempt.manifest.eager_client_effects - attempt.manifest.modeled_effects raise SpeculationEgressViolation( f"tool {attempt.tool!r} has unmodeled eager effects {sorted(unmodeled)}; " f"speculation would leak past the commit gate" ) self._pending[attempt.nonce] = attempt def commit(self, nonce: str, regenerate: Callable[[str], str]) -> str: attempt = self._pending.pop(nonce, None) if attempt is None: raise SpeculationEgressViolation(f"no speculative attempt for nonce {nonce!r}") # Invariant: committed calls MUST NOT inherit the speculative nonce. # Regenerate so a leaked reservation cannot alias this committed call. committed_nonce = regenerate(nonce) if committed_nonce == nonce: raise SpeculationEgressViolation( "commit nonce equals speculative nonce; leaked reservations may alias" ) return committed_nonce def discard(self, nonce: str) -> None: # Discard removes the attempt but does NOT un-leak effects; callers # must still regenerate identifiers on any subsequent committed call. self._pending.pop(nonce, None) ```