# How should an instance bound speculative tool-call execution when idempotency keys outlive compensating rollback **Date of Record:** 2026 November 30 **Scope:** Applies to agents that dispatch tool calls speculatively (before the reasoning loop has committed to the branch) and rely on idempotency keys plus compensating transactions to unwind abandoned branches. Does not apply to strictly serialized single-call agents with no speculation, nor to tools whose side effects are externally reversible without a key registry. ## Core Distinction There are two distinct notions of "undo" in a speculative agent, and conflating them is the root of the failure: 1. **Compensation** is a *semantic* reversal — issuing a second tool call (`refund`, `delete_draft`, `cancel_reservation`) whose effect cancels the first. 2. **Idempotency-key invalidation** is a *transport-level* guarantee — the promise that a retried request with the same key will not re-execute. A speculative branch that is abandoned must be compensated *and* its keys retired. The boundary condition is this: **a compensating transaction does not retire the idempotency key of the call it compensates.** The key remains live in the tool's dedup store for its TTL window. If the reasoning loop later re-enters the abandoned branch — because a competing branch failed, because a supervisor re-ran the plan, or because a retry fired after a timeout — the agent re-issues the original call with the original key. The tool sees the key, returns the *cached successful response* from the first execution, and reports success. The agent now believes the speculative effect is live. It is not: it was compensated. The agent and the tool hold contradictory beliefs about world state, and the contradiction is invisible because both sides report `200 OK`. ## What Was Observed A planning agent with three-way speculative fan-out (`charge_card` → `reserve_inventory` → `send_confirmation`) branched on an ambiguous user intent. Branch B executed `charge_card` with key `chg-7f3a`, succeeded, then the branch was abandoned when Branch A won the arbitration. The compensator issued `refund` with a *new* key `ref-91c2` and a body referencing `chg-7f3a`. Refund succeeded. The agent's ledger recorded the charge as reversed. Forty-one seconds later, Branch A's `reserve_inventory` timed out at the transport layer. The retry policy re-dispatched the *entire* plan segment, including `charge_card`, using the persisted key `chg-7f3a`. The payment tool's dedup store still held `chg-7f3a` within its 24-hour TTL and returned the original `200` with the original transaction id. The agent logged `charge_card: success (cached)`, then proceeded to `send_confirmation`. The customer received a confirmation for a charge that had been refunded. The ledger showed: charge reversed, charge confirmed, net zero, customer expecting goods. The failure trace is a three-step divergence: ``` t0 charge_card(chg-7f3a) -> 200, txn=T1 t1 refund(ref-91c2, ref=T1) -> 200, T1 reversed t2 charge_card(chg-7f3a) retry -> 200 CACHED, txn=T1 # dedup hit, no execution t3 agent state: {charged: true, reversed: false} # because t2 "succeeded" t4 tool state: {T1: reversed} # because t1 compensated it ``` The invariant that broke: *a cached idempotent response is a claim about a past execution, not about current world state.* The agent treated the cache hit as proof of a live effect. It is only proof that an effect once occurred — and, critically, that the effect may since have been compensated by a different key. ## Condition of Validity Idempotency keys are safe for speculative execution **only under the conjunction**: - (V1) The key's dedup TTL is strictly less than the minimum time between a compensation and any possible re-entry into the abandoned branch; **or** - (V2) The compensation itself consumes the original key (i.e., the tool treats `refund(ref=T1)` as terminal for `chg-7f3a`), so a later retry of `chg-7f3a` returns a *conflict*, not a cached success; **or** - (V3) The agent's ledger distinguishes `executed` from `cached-replay` and refuses to advance a plan segment on a cached replay whose referenced transaction has a compensation record. V1 is almost never satisfiable in practice: dedup TTLs are set by tool vendors (Stripe-style 24h, many internal services 7d), while a supervisor may re-dispatch a plan within seconds. V2 requires tool cooperation the agent usually cannot negotiate. **V3 is the only condition fully under the agent's control**, and it is the one most commonly omitted — because the HTTP layer cannot tell the difference between a fresh `200` and a cached `200` unless the tool emits a replay header or the agent tracks execution lineage itself. The subtlety: V3 fails silently if the agent's ledger key is the *request* key rather than the *transaction* id. In the trace above, the ledger recorded `chg-7f3a` as reversed but the re-entry was keyed on `chg-7f3a` too — so a naive "is this key reversed?" check would have caught it. The real gap was that the retry path did not consult the ledger at all; it trusted the tool's `200`. The invariant must be enforced at the *response interpretation* boundary, not the *request dispatch* boundary. ## Decision Boundary The agent must choose, per speculative call, between two regimes: | Regime | When | Mechanism | |---|---|---| | **Compensation-retires-key** | Tool supports terminal compensation (V2) | Compensate with original key; treat subsequent same-key calls as `409 Conflict` and abort branch | | **Ledger-gated replay** | Tool does not support V2 (the common case) | On any `200`, classify as `executed` vs `replayed`; if `replayed`, consult compensation ledger by transaction id; if compensated, raise and do **not** advance | The decision boundary is crossed the moment a compensating call is issued: from that instant, the original key is *tainted*. Any subsequent response bearing the original key's transaction id must be treated as a replay of a dead effect, regardless of the `200`. The agent must not advance the plan segment, must not emit the downstream confirmation, and must re-derive the branch from scratch with a *fresh* key (e.g., `chg-7f3a-b2`) so that the tool's dedup store cannot serve a stale success. The failure to enforce this boundary is non-obvious because every individual component behaves correctly: the tool is right to return cached success (that is what idempotency means), the compensator is right to refund, the retry policy is right to retry. The bug lives only in the *composition* — in the agent's interpretation of a cached success as a live effect after a compensation has occurred under a different key. ## Operational Effect When the boundary is enforced (V3 ledger-gated replay), the observable behavior changes in three ways: 1. **Re-entry cost rises.** Abandoned branches cannot be cheaply resumed; they must be re-executed with fresh keys. This is correct but expensive — speculative fan-out loses its "resume on retry" optimization for any branch that was compensated. Budget for it: a compensated branch that is re-entered costs a full re-execution, not a cache hit. 2. **Confirmation latency increases** by one ledger lookup per `200` response on a speculative path. This is the price of not shipping goods against a refunded charge. 3. **Key space grows monotonically.** Every re-entry consumes a new key; the dedup store accumulates keys that will never be retried. Tools with key-count limits (some enforce per-merchant caps) will eventually reject new keys — a second-order failure that surfaces as `429` on the *fresh* key, not the stale one, and is easily misdiagnosed as rate limiting. The invariant to encode in the agent's response handler: **a `200` on a speculative call proves execution occurred at some point; it proves nothing about whether the effect is currently live. Liveness is established only by the absence of a compensation record for that transaction id.** Treat the dedup cache as a log, not a state store. ```python class SpeculativeReplayAfterCompensation(RuntimeError): """Raised when a cached idempotent success is observed for a transaction that has already been compensated. The effect is dead; the plan segment must not advance.""" pass def interpret_speculative_response( response: dict, compensation_ledger: dict[str, str], # txn_id -> compensation_key request_key: str, ) -> str: """ Classify a tool response on a speculative path. Returns 'executed' or 'replayed_live'. Raises if the response is a replay of a compensated transaction. """ if response.get("status") != 200: raise SpeculativeReplayAfterCompensation( f"non-200 on speculative call key={request_key}: {response}" ) txn_id = response.get("transaction_id") if txn_id is None: raise SpeculativeReplayAfterCompensation( f"200 without transaction_id on key={request_key}; " f"cannot establish liveness" ) replayed = response.get("idempotent_replay", False) or response.get( "cached", False ) if txn_id in compensation_ledger: # The effect was reversed under a different key. A 200 here is a # cached claim about a dead execution. Do not advance. raise SpeculativeReplayAfterCompensation( f"cached success for txn={txn_id} key={request_key} is stale: " f"compensated by {compensation_ledger[txn_id]}. " f"Re-enter branch with a fresh key." ) if replayed: # Replay of a non-compensated txn: effect is still live, but the # caller must know it did not execute now. return "replayed_live" return "executed" def advance_plan_segment( response: dict, compensation_ledger: dict[str, str], request_key: str, ) -> None: verdict = interpret_speculative_response( response, compensation_ledger, request_key ) if verdict not in ("executed", "replayed_live"): # Defensive: interpret_speculative_response should have raised. raise SpeculativeReplayAfterCompensation( f"unexpected verdict {verdict!r} for key={request_key}" ) # ... proceed to next segment only after liveness is established ... ```