# Why does an instance speculatively pre-execute a tool call under an idempotency key and still double-apply the effect when the optimistic concurrency check is revalidated after a scheduler preemption? **Date of Record:** 2026 November 22 **Scope:** Applies to agents that overlap LLM decoding with side-effecting tool execution by issuing the call under a client-generated idempotency key, then revalidating an optimistic-concurrency token (version/ETag) on commit. Does not apply to read-only speculative calls, nor to transports that serialize commit and effect atomically in a single transaction. ## Core Distinction The failure is not "the idempotency key was missing" or "the version check was skipped." Both are present. The failure is a **split between the deduplication domain and the concurrency domain across a preemption boundary**. The idempotency key is minted at *speculation time* and bound to the *intended* effect; the concurrency token is validated at *commit time* and bound to the *observed* state. When the agent is preempted between the speculative side effect and the optimistic commit, a retry path can re-enter with the *same* key but a *re-derived* token, and the two guards no longer compose: the key suppresses a duplicate the store already has, while the freshly-read token authorizes a second, semantically distinct write that the key does not cover. Put differently: idempotency keys make a call *at-most-once by identity*; optimistic concurrency makes a write *safe-against-stale-state*. Neither guarantees *at-most-once by effect* when the effect is parameterized by state that changed during the gap. The invariant that breaks is: **"key identity ⇔ effect identity"** — the assumption that a fixed idempotency key always maps to the same concrete mutation. ## What Was Observed A planner agent emits a tool call `transfer_funds(account=A, amount=100, idem_key=K1)` and begins speculative execution before the model has finished emitting the trailing verification tokens. The tool handler: 1. reads the account version `v=7`, 2. performs the debit under `K1`, 3. stages the commit with `If-Match: v=7`. Before the commit RPC returns, the instance is preempted (token-budget exhaustion mid-decode, node eviction, or a 30s lease expiry). The orchestrator's resume logic re-runs the step from the last checkpoint, which predates the debit. The re-run: 1. regenerates the call. Because the model is non-deterministic and the checkpoint did not persist `K1` (it was held in decode-local scratch, not in the durable step record), a **new** key `K2` is minted for what the agent believes is the same logical action. 2. reads `v=8` (the speculative debit already landed and bumped the version), 3. commits under `K2` with `If-Match: v=8` — which **succeeds**. Result: two debits of 100 against account A. The optimistic check passed *because the first write changed the state it was validating against*; the idempotency guard was bypassed *because the key did not survive the preemption*. Each guard individually reported success. The audit log shows two distinct keys, so key-based reconciliation finds no duplicate. The tell in telemetry: a `version` delta of exactly +1 between the speculative read and the resume read, paired with two distinct `idem_key` values sharing an identical `(tool, args_digest)` tuple. ## Condition of Validity This failure requires the conjunction of four conditions; remove any one and the double-apply is bounded: 1. **Speculation precedes durable key persistence.** The idempotency key lives in volatile decode state or an in-memory scratchpad rather than the write-ahead step record. If `K1` is fsynced before the side effect fires, the resume reuses it and the store deduplicates correctly. 2. **The side effect mutates the token it is validated against.** Optimistic concurrency is only a *stale-write* guard. If the write itself bumps the version/ETag (the normal case), a retry that re-reads after the first write sees a "fresh" token and is authorized. The guard is self-defeating for retries that re-derive their precondition. 3. **Re-derivation is permitted.** The resume path re-invokes the model or re-mints the key instead of replaying the recorded call verbatim. Deterministic replay of the logged arguments + key closes the gap. 4. **No effect-level dedup key.** The downstream system dedups on `idem_key` but not on `(actor, tool, canonical_args, window)` or a content-addressed effect hash. A second key for identical args slips through. The invariant to hold: **the concurrency precondition must be captured at the same instant and in the same durable record as the idempotency key, and must not be re-readable by the retry.** Equivalently, the commit must be `If-Match: v_speculation` (the version observed *before* any speculative effect), never `v_reobserved`. ## Decision Boundary The boundary is whether the commit's precondition token is **pinned to speculation-time state** or **re-derived at commit-time state**. Pinned tokens make the optimistic check a true compare-and-swap against the pre-effect world: a retry that re-reads `v=8` and tries `If-Match: v=7` fails closed, and the orchestrator must reconcile the ambiguous outcome (did the speculative effect land?) via a keyed read-back before proceeding. Re-derived tokens convert the check into a "is the world still writable" probe, which passes after any prior write. Operationally: if `precondition_at_commit != precondition_at_speculation`, the agent must treat the commit as **unverified** and route to reconciliation, not retry. The reconciliation read is keyed on the *original* `K1`; if the store reports the effect landed, the step is complete and the re-derived `K2` path is abandoned. The decision to *speculate at all* is also bounded here: speculation is only safe for tools whose effects are keyed-immutable and whose preconditions are pinned — never for tools that bump their own concurrency token and re-derive preconditions on retry. ## Operational Effect Without the pin, the system exhibits **silent at-least-once semantics disguised as exactly-once**: every guard logs success, reconciliation by key finds nothing, and the only signal is a version skew that looks like normal concurrent traffic. The blast radius scales with preemption frequency — exactly the regime (long decodes, tight token budgets, aggressive checkpointing) where speculative execution is most valuable, so the failure concentrates where the optimization is heaviest. The guardrail is structural: persist `(idem_key, precondition_token, canonical_args_digest)` atomically *before* the speculative effect; on resume, replay the recorded tuple rather than re-deriving; and reject any commit whose precondition differs from the recorded one, forcing keyed read-back reconciliation. The effect is a system where a preemption yields either a clean dedup or a bounded reconciliation, never a double-apply. ```python import hashlib from dataclasses import dataclass class SpeculativeCommitDivergence(RuntimeError): """Raised when a speculative tool call's commit-time precondition no longer matches the speculation-time precondition recorded with its idempotency key.""" @dataclass(frozen=True) class SpeculativeRecord: idem_key: str tool: str args_digest: str precondition_token: int # version/ETag observed BEFORE any speculative effect def commit_speculative(record: SpeculativeRecord, observed_token: int) -> str: """Commit a speculatively executed effect, refusing to re-derive the optimistic-concurrency precondition across a preemption boundary.""" if observed_token != record.precondition_token: # The world moved between speculation and commit. Retrying with a # fresh token would authorize a second, semantically distinct write # that the idempotency key does not cover. raise SpeculativeCommitDivergence( f"precondition drifted for key={record.idem_key} " f"tool={record.tool} args={record.args_digest}: " f"speculated v={record.precondition_token}, observed v={observed_token}; " f"route to keyed read-back reconciliation, do not retry" ) return f"committed:{record.idem_key}" def resume_step(record: SpeculativeRecord, store_token: int) -> str: """Resume path: replay the recorded tuple verbatim; never re-mint the key.""" if store_token > record.precondition_token: # Prior speculative effect likely landed; reconcile by key, not by re-issue. raise SpeculativeCommitDivergence( f"ambiguous outcome on resume for key={record.idem_key}: " f"store at v={store_token} > speculated v={record.precondition_token}; " f"perform keyed read-back before any re-issue" ) return commit_speculative(record, store_token) def args_digest(tool: str, **kwargs) -> str: canon = tool + "|" + "|".join(f"{k}={kwargs[k]}" for k in sorted(kwargs)) return hashlib.sha256(canon.encode()).hexdigest()[:16] ```