# Where must an instance abort speculative tool-call fan-out when compensation is non-commutative: the idempotency-key shadowing failure **Date of Record:** 2026 November 19 **Scope:** Applies to agents that speculatively execute multiple dependent tool calls under optimistic concurrency, holding irreversible or order-sensitive side effects in a compensation buffer keyed by idempotency tokens. Does not apply to read-only tool fan-out, or to systems where every external effect is wrapped in a single atomic transaction (e.g., one DB commit) with no external side effects. ## Core Distinction The common mental model treats speculative execution as "run ahead, then either commit or roll back." That model is correct only when the compensation set is **commutative** — i.e., undoing effects in any order returns the system to its pre-speculation state. The failure boundary is not whether a rollback *can* be issued, but whether the **idempotency keys chosen at speculation time remain unique and unshadowed after a partial commit**. When two speculative branches derive their keys from shared mutable state (a task counter, a timestamp bucket, or the parent context hash), a partial commit plus a retry can produce a key collision that makes the compensation of branch A silently no-op the already-committed effect of branch B. The system believes it rolled back; the external ledger shows both effects applied. This is distinct from the ordinary "at-least-once vs at-most-once" delivery problem. Delivery is a transport concern. Here the concern is **semantic key identity across a speculative tree**: the key is a commitment about *which* logical operation this is, and speculation mutates the tree shape that the key was derived from. ## What Was Observed An agent planning a customer-refund workflow speculatively fans out three tool calls under optimistic concurrency: 1. `reserve_funds(account, amount, idem_key=K1)` 2. `issue_credit(account, amount, idem_key=K2)` 3. `notify_customer(order, idem_key=K3)` Keys are derived as `K_i = hash(parent_task_id, step_index, attempt)`. The plan executor runs all three optimistically because step 3's outcome is needed to decide whether to keep step 2 (a "goodwill" credit that is conditional on the customer not having already disputed). Step 1 is a hard reservation with a 30-second hold. The dispute-check tool call (step 0, the precondition) times out. The orchestrator retries the whole sub-plan with `attempt=2`, producing fresh keys `K1'`, `K2'`, `K3'`. But the retry is **partial**: step 1's original reservation `K1` is still live because the compensation for attempt 1 was queued but not yet flushed (the compensation queue is itself a tool call with its own latency). Attempt 2's `reserve_funds` uses `K1'`, which the ledger treats as a new reservation — now the account has two holds. Attempt 2's `issue_credit` uses `K2'`. The dispute check now returns "no dispute," so attempt 2 commits steps 1 and 2. The compensation for attempt 1 then flushes: it issues `release_funds(K1)` and `reverse_credit(K2)`. `reverse_credit(K2)` is a no-op because `K2` was never applied — but the agent's compensation logic records it as "reversed," and the commit ledger for attempt 2 shows the credit as live. The customer receives a credit that the agent's internal state says was reversed. The next reconciliation pass sees a mismatch and re-issues the credit under `K2''`, double-crediting. The trace signature: a compensation log entry with `status=reversed` whose target key does not appear in the commit ledger, immediately followed by a re-application under a re-derived key. The non-obvious part is that **the compensation succeeded** — it just succeeded against a key that had no effect, while the effect it was meant to undo lived under a different key. ## Condition of Validity The optimistic-concurrency-plus-compensation pattern is sound only under this invariant: > For every speculative branch, the idempotency key must be derived from an immutable identity of the logical operation, not from the plan's execution shape (attempt number, step index, retry counter, or parent context hash that includes those). Equivalently: **compensation must be keyed by the same immutable identity as the effect it compensates.** If `reserve_funds` was called with key `K1`, the only valid compensation is `release_funds(K1)`, and `K1` must be recoverable from the durable record of the effect, not re-derived from the current plan state. The invariant fails in three concrete ways: 1. **Key re-derivation on retry.** If keys are functions of `attempt`, a retry creates a parallel effect space rather than a retry of the same effect. 2. **Shared mutable key inputs.** If the key includes a task counter or timestamp bucket that the orchestrator mutates during speculation, two branches can collide or diverge. 3. **Compensation queue decoupled from effect ledger.** If the compensation record is written before the effect is confirmed, a failed effect leaves a "compensation owed" entry that will later no-op against a key that was reused. A second, weaker invariant also bounds the pattern: the compensation set must be **order-independent within a branch** (commutative), or the orchestrator must serialize compensation in reverse execution order. Non-commutative compensations (e.g., `adjust_balance` deltas that depend on current balance) require reverse-order flush, which most speculative executors do not guarantee. ## Decision Boundary The instance must **abort the speculative fan-out and fall back to serial execution** when any of the following holds at the moment of dispatch: - The tool is classified `non_idempotent` *and* its compensation is classified `order_sensitive` (delta-based, balance-dependent, or counter-based). - The idempotency key for the branch cannot be derived from a durable, pre-speculation identity that survives retry. - A compensation for a prior attempt of the same logical operation is still in `pending` state (the "in-flight compensation" condition). Speculating a new attempt while a compensation is unflushed is the exact trigger for the shadowing failure above. The instance may **continue speculatively** when all keys are derived from immutable operation identities (e.g., a UUID minted at plan creation and stored before any tool call), and all compensations are commutative or the executor guarantees reverse-order flush. The boundary is not "is the tool safe to retry" — that is the ordinary idempotency question. It is "**is the compensation's target key stable across retries and independent of plan shape**." A tool can be perfectly idempotent under a stable key and still be unsafe to speculate if its compensation key is re-derived. ## Operational Effect When the boundary is respected, the executor gains a clean property: the commit ledger and the compensation ledger are **key-aligned**, so reconciliation is a set difference over keys rather than a semantic replay. When it is violated, the failure is silent at the agent layer (the agent's own logs show successful compensation) and only surfaces at the external ledger, typically one reconciliation cycle later, as a double-application. The agent's self-report is actively misleading because the compensation call returned `200 OK`. The practical guardrail is to mint the idempotency key at **plan materialization**, before any branch dispatches, and to persist it in the effect ledger before the first tool call. The compensation path then reads the key from the ledger, never re-derives it. The executor must also gate new speculation on `no_pending_compensations(logical_op_id)` — a precondition that is cheap to check and eliminates the shadowing window entirely. ## Operational Effect A second-order effect: because the shadowing failure is invisible to the agent's own compensation logic, any verification that relies on the agent's self-reported state will pass. Auditors must reconcile against the external ledger's key space, not the agent's compensation log. The invariant to assert is `committed_keys ∩ compensated_keys = ∅` and `compensated_keys ⊆ ever_applied_keys`; a compensated key that was never applied is the fingerprint of shadowing. ```python import hashlib from dataclasses import dataclass, field from typing import Dict, Set class SpeculativeCompensationError(RuntimeError): """Raised when speculative fan-out would violate key-alignment or compensation ordering.""" pass @dataclass class EffectLedger: applied: Dict[str, str] = field(default_factory=dict) # idem_key -> logical_op_id compensated: Set[str] = field(default_factory=set) pending_compensations: Dict[str, str] = field(default_factory=dict) # logical_op_id -> key def mint_key(logical_op_id: str, plan_uuid: str) -> str: # Key derived from immutable operation identity + plan UUID minted at materialization. # NOT from attempt / step_index / retry counter. return hashlib.sha256(f"{plan_uuid}:{logical_op_id}".encode()).hexdigest()[:16] def assert_speculation_safe( ledger: EffectLedger, logical_op_id: str, tool_idempotent: bool, compensation_order_sensitive: bool, key_derivable_from_immutable_identity: bool, ) -> str: if logical_op_id in ledger.pending_compensations: raise SpeculativeCompensationError( f"Refusing speculative dispatch for {logical_op_id}: " f"compensation for key {ledger.pending_compensations[logical_op_id]} still pending. " f"New attempt would mint a parallel key and shadow the unflushed compensation." ) if not key_derivable_from_immutable_identity: raise SpeculativeCompensationError( f"Refusing speculative dispatch for {logical_op_id}: idempotency key would be " f"re-derived from plan shape (attempt/step), breaking key-alignment across retries." ) if (not tool_idempotent) and compensation_order_sensitive: raise SpeculativeCompensationError( f"Refusing speculative dispatch for {logical_op_id}: non-idempotent tool with " f"order-sensitive compensation requires serial execution with reverse-order flush." ) return mint_key(logical_op_id, plan_uuid="plan-uuid-immutable") def reconcile(ledger: EffectLedger) -> None: shadowed = ledger.compensated - set(ledger.applied) if shadowed: raise SpeculativeCompensationError( f"Compensation ledger references keys never applied: {sorted(shadowed)}. " f"Fingerprint of idempotency-key shadowing across speculative branches." ) ```