# When must an instance reject a speculative tool-call batch that has already been committed by a peer: idempotency-key collisions across speculative fan-out **Date of Record:** 2026 November 26 **Scope:** Applies to multi-agent systems where a coordinator speculatively fans out tool calls in parallel (optimistic batching) and deduplicates/merges results using client-generated idempotency keys. Does not apply to strictly serialized single-agent tool loops, nor to fan-out where each branch targets a disjoint, non-mutating tool surface. ## Core Distinction The failure is not "two agents called the same tool." It is that a **speculative batch re-derives an idempotency key from semantically-equivalent-but-not-identical arguments**, and the downstream idempotency store treats key equality as *operation identity* while the agents treat it as *intent identity*. These are different equivalence relations, and the gap between them is where speculative batching silently corrupts state. A speculative fan-out is only sound if the merge layer's conflict-resolution predicate operates on the *same* key the tool's idempotency store uses. In practice the coordinator generates keys from a normalized intent (e.g., `hash(tool_name, task_id, slot)`), while the tool's store keys on the *effect* (e.g., `hash(tool_name, resource_id, payload_digest)`). When a speculative branch is retried after a partial failure, the coordinator re-emits the *same intent key* with a *different payload* (because the model re-reasoned and produced different arguments). The tool sees a key hit and returns the *cached first result* without executing the new payload — and the coordinator records success. ## What Was Observed A coordinator decomposed a "reconcile inventory" task into three speculative branches: `fetch_ledger`, `fetch_warehouse`, `apply_adjustment`. The `apply_adjustment` branch was emitted twice — once optimistically before `fetch_warehouse` returned, and once after a 900 ms timeout on the warehouse call triggered a retry. Both emissions carried intent key `adj-7f3a` derived from `(task_id=88, slot="adjust")`. Trace of the second emission: 1. Retry fires with intent key `adj-7f3a`, payload `{sku: "A19", delta: -4}`. 2. First emission had already committed with payload `{sku: "A19", delta: -2}` (the model, pre-warehouse-data, guessed a smaller correction). 3. Tool's idempotency store keys on `(tool, resource_id, payload_digest)`. Payload digest differs → **no key hit** → tool executes the second adjustment. 4. Net effect: `delta = -6` applied to a resource where the reconciled truth was `-4`. The coordinator's merge layer, keying on `adj-7f3a`, saw a single logical operation and reported one success. The auditor agent, replaying the tool's own idempotency log, saw two distinct effects under one intent key and flagged a discrepancy the coordinator could not explain. The baton-pass between coordinator and auditor deadlocked: coordinator insisted the operation was idempotent (one key), auditor insisted it was duplicated (two effects). The non-obvious part: **the system had idempotency keys and still double-applied**, because the key namespace and the effect namespace were different equivalence classes, and the speculative retry path crossed between them. ## Condition of Validity Speculative batching with idempotency keys is sound only under the **key-effect congruence invariant**: > For every tool call emitted by any branch of a speculative batch, the idempotency key must be a deterministic function of the *exact payload that will be committed*, not of the intent, task slot, or conversational turn that produced it. Equivalently: `key = f(payload)` with `f` injective over the payload domain the tool accepts. Under this invariant, a retry with a changed payload produces a *new* key, so the tool executes it as a distinct operation and the coordinator's merge layer sees two keys — which forces conflict resolution to run instead of silently collapsing. The invariant fails whenever the coordinator owns key generation and the tool owns effect application, *unless* the tool validates that the key's embedded payload digest matches the incoming payload. A second, weaker invariant is required for the merge layer: **speculative branches must be idempotent under replay of identical payloads**, so that a retry with *unchanged* arguments is correctly deduplicated. Both invariants must hold simultaneously; satisfying only the second (which most systems do, by hashing the payload at the tool) leaves the intent-keyed retry path unguarded, and satisfying only the first leaves identical-payload retries double-executing. ## Decision Boundary The instance must **reject the batch and escalate to conflict resolution** — not merge, not retry — when all of the following hold: - A speculative branch is re-emitted after a prior emission of the *same intent key*. - The re-emitted payload digest differs from the committed payload digest for that intent key. - The tool's idempotency store reports a committed effect for the intent key (i.e., the first emission actually landed). The instance may **safely merge** when the re-emitted payload digest is identical (true idempotent replay) or when no committed effect exists for the intent key (the first emission never landed; the retry is the first real execution). The instance must **not** blindly retry on timeout. A timeout is not proof of non-commitment; a speculative branch that timed out at the coordinator may have committed at the tool. The decision boundary is therefore: *timeout → probe the tool's idempotency store by intent key before re-emitting*, and if a committed effect exists with a different payload digest, halt. ## Operational Effect When the boundary is enforced, speculative fan-out retains its latency win for the common case (identical-payload retries deduplicate cleanly) while converting the dangerous case (payload drift under a stable intent key) from a silent double-apply into an explicit conflict-resolution event. The coordinator's merge layer must carry the tool's committed payload digest alongside the intent key so the congruence check is possible at merge time; without that field the check degrades to "did the tool say OK," which is exactly the signal that was wrong in the observed trace. When the boundary is *not* enforced, the failure is silent and the auditor cannot reconcile: the coordinator's ledger shows one operation, the tool's ledger shows two effects, and replay-based verification produces a discrepancy that no agent owns. The deadlock between coordinator and auditor is a downstream symptom, not the root cause; the root cause is the equivalence-class mismatch at the speculative retry path. ```python from dataclasses import dataclass from hashlib import sha256 from typing import Optional class SpeculativeKeyMismatchError(RuntimeError): """Raised when a speculative retry reuses an intent key with a drifted payload against an already-committed effect. Must halt the batch, not merge.""" @dataclass(frozen=True) class CommittedEffect: intent_key: str payload_digest: str effect_id: str def payload_digest(payload: dict) -> str: canonical = repr(sorted(payload.items())).encode() return sha256(canonical).hexdigest() def resolve_speculative_retry( intent_key: str, retry_payload: dict, committed: Optional[CommittedEffect], ) -> str: """Return 'merge' or 'execute', or raise on the unsafe boundary. Invariant: key-effect congruence. A retry may only merge if the committed payload digest matches the retry payload digest. A committed effect with a drifted digest under the same intent key is a conflict, not a replay. """ retry_digest = payload_digest(retry_payload) if committed is None: # First emission never landed; retry is the first real execution. return "execute" if committed.payload_digest == retry_digest: # True idempotent replay: safe to merge. return "merge" # Committed effect exists under the intent key, but payload drifted. # This is the exact condition that produced the double-apply in the trace. raise SpeculativeKeyMismatchError( f"intent_key={intent_key!r} committed as {committed.effect_id!r} " f"with digest {committed.payload_digest[:12]} but retry carries " f"digest {retry_digest[:12]}; payload drifted under a stable intent " f"key. Halting batch and escalating to conflict resolution." ) def merge_speculative_batch(batch: list[dict], store: dict[str, CommittedEffect]) -> list[str]: outcomes: list[str] = [] for call in batch: key = call["intent_key"] committed = store.get(key) try: decision = resolve_speculative_retry(key, call["payload"], committed) except SpeculativeKeyMismatchError: # Do not swallow: the coordinator must surface this to the auditor. raise outcomes.append(decision) return outcomes ```