# What happens when an instance prefetches a tool call under a stale idempotency key and the reconciliation ledger cannot distinguish a replay from a new intent **Date of Record:** 2026 November 21 **Scope:** Applies to any agent runtime that speculatively dispatches tool calls ahead of the reasoning step that would have authorized them, using client-generated idempotency keys to enforce exactly-once side effects. Does not apply to purely read-only tools or to runtimes that serialize all tool dispatch behind a single blocking reasoning gate. ## Core Distinction The failure is not "a speculative call was wrong" — speculative calls are expected to be wrong sometimes, and the runtime is designed to discard them. The failure is that the *idempotency key was minted at the wrong point in the causal chain*. A key is a promise about intent identity: "these two transmissions mean the same thing." When an agent generates the key from the *prefetched plan fragment* rather than from the *committed intent*, a discarded-then-retried call and a genuinely new call can collide on the same key, and the reconciliation ledger — which only sees keys, not reasoning traces — will silently suppress the second call as a replay. The side effect happens exactly once, but it happens for the *wrong* call. Exactly-once delivery is preserved; exactly-once *correctness* is not. ## What Was Observed An agent running a multi-step task (a payment adjustment workflow) used a prefetcher that, upon reading a partially-filled plan, dispatched `apply_credit(account, amount)` speculatively. The key was derived deterministically as `hash(plan_id || step_index || tool_name || canonical_args)`. The plan was later revised by the reasoning loop: the amount changed from 40 to 45 because a prior tool call returned a discount that the speculator's snapshot predated. The revised call produced a *different* canonical-args hash, so it was dispatched with a new key — fine. The problem surfaced on the *retry path*. The speculative call with amount 40 timed out at the transport layer (no response within the 800 ms prefetch budget). The runtime marked it `UNCONFIRMED` and retained the key in the ledger. Twelve seconds later the reasoning loop, having re-derived the original 40-amount intent from a replayed context window (the discount had been evicted by context compaction), issued the same call again. Same key. The ledger, per its contract, saw a duplicate key in `UNCONFIRMED` state, assumed an in-flight replay, and returned the cached `PENDING` resolution rather than dispatching. The upstream provider had actually *executed* the first call and the response was lost in the timeout. Net result: one credit applied, two intents recorded as satisfied, and a 5-unit discrepancy that only appeared at end-of-day reconciliation against the provider's ledger. The non-obvious part: the runtime's exactly-once guarantee was *working as specified*. The bug lived in the assumption that a key uniquely identifies an intent. It does not — it identifies a *transmission class*, and the agent's reasoning loop can mint two distinct intents that map to the same transmission class when context replay reconstructs a superseded plan state. ## Condition of Validity The invariant "same idempotency key ⇒ same intent" holds only if the key is a pure function of state that is *monotonic across the task*. In practice this requires all three: 1. **Key derivation must include a context epoch or plan version** that increments on any revision to the plan fragment the call depends on. `hash(plan_id || step_index || args)` is insufficient because `step_index` is stable across plan revisions and `args` can be reconstructed to a superseded value after context compaction. 2. **The ledger must distinguish `UNCONFIRMED` from `IN_FLIGHT`.** A timeout is not evidence of non-execution; it is evidence of non-acknowledgement. Collapsing these states lets a lost response masquerade as a suppressed duplicate. 3. **Speculative keys must be namespaced distinctly from committed keys** (e.g., `spec:` prefix) so that a speculative dispatch that is later committed under the same logical intent does not collide with a *different* speculative dispatch from an earlier plan epoch. When any of these is violated, the ledger's deduplication is unsound: it can only prove "I have seen this key before," never "this key means the same thing I saw before." ## Decision Boundary The runtime must choose, on every duplicate-key hit, between *suppress* (assume replay) and *reconcile* (query authoritative state). The boundary is: - **Suppress** only when the prior entry is `CONFIRMED` with a terminal provider response, or `IN_FLIGHT` with a heartbeat younger than the provider's documented execution window. - **Reconcile** whenever the prior entry is `UNCONFIRMED`, or when the key's derivation epoch is older than the current plan version, or when the elapsed time since the prior transmission exceeds the provider's max execution latency. Reconciliation means issuing a *read* against the provider's ledger (or a status-probe endpoint) before deciding. The boundary is crossed the moment the agent's plan version advances past the epoch embedded in the key. Below that line, dedup is safe. Above it, dedup is a guess dressed as a guarantee. ## Operational Effect Without the epoch in the key and the `UNCONFIRMED`/`IN_FLIGHT` split, prefetching converts a latency optimization into a silent correctness hazard: side effects land exactly once but attach to superseded intents, and the discrepancy is invisible until external reconciliation days later. The blast radius scales with prefetch depth — deeper speculation means more plan revisions between mint and commit, which means more epoch drift per key. The fix is cheap (one counter in the key, one state in the ledger, one probe on the ambiguous branch) but it must be present before speculation is enabled, because retrofitting epochs onto keys already in flight creates a migration window where *both* old and new keys resolve as valid, reintroducing the collision at a higher layer. ```python import hashlib import time from dataclasses import dataclass, field from enum import Enum from typing import Optional class IdempotencyCollisionError(RuntimeError): """Raised when a duplicate key cannot be proven to denote the same intent.""" pass class LedgerState(Enum): UNCONFIRMED = "unconfirmed" # transmitted, no ack; execution unknown IN_FLIGHT = "in_flight" # ack'd receipt, execution in progress CONFIRMED = "confirmed" # terminal provider response recorded @dataclass class LedgerEntry: key: str epoch: int state: LedgerState last_heartbeat: float terminal_response: Optional[dict] = None @dataclass class ReconciliationLedger: entries: dict = field(default_factory=dict) provider_exec_window_s: float = 30.0 def derive_key(self, plan_id: str, step_index: int, args: dict, epoch: int) -> str: # epoch is mandatory: it is the monotonic plan-version counter. material = f"{plan_id}|{step_index}|{epoch}|{sorted(args.items())}" return "spec:" + hashlib.sha256(material.encode()).hexdigest()[:24] def dispatch(self, key: str, epoch: int, current_epoch: int) -> dict: prior = self.entries.get(key) if prior is None: self.entries[key] = LedgerEntry( key=key, epoch=epoch, state=LedgerState.UNCONFIRMED, last_heartbeat=time.time(), ) return {"action": "dispatch", "key": key} # Invariant: a key from a superseded epoch cannot be proven equivalent # to the current intent, even if the bytes match. if prior.epoch < current_epoch: raise IdempotencyCollisionError( f"key {key} minted at epoch {prior.epoch}, current plan epoch " f"{current_epoch}: dedup unsound, must reconcile against provider" ) if prior.state is LedgerState.CONFIRMED: return {"action": "suppress", "key": key, "response": prior.terminal_response} if prior.state is LedgerState.IN_FLIGHT: age = time.time() - prior.last_heartbeat if age <= self.provider_exec_window_s: return {"action": "suppress", "key": key, "reason": "in-flight"} raise IdempotencyCollisionError( f"key {key} in-flight {age:.1f}s > window " f"{self.provider_exec_window_s}s: execution status unknown" ) # UNCONFIRMED: timeout is non-evidence of non-execution. raise IdempotencyCollisionError( f"key {key} is UNCONFIRMED: prior transmission may have executed; " f"probe provider ledger before re-dispatch" ) def confirm(self, key: str, response: dict) -> None: entry = self.entries.get(key) if entry is None: raise IdempotencyCollisionError(f"confirm for unknown key {key}") entry.state = LedgerState.CONFIRMED entry.terminal_response = response ```