# How does an instance detect that a speculative tool call's idempotency key has been silently rebound to a different tool in a compensating swarm **Date of Record:** 2026 November 21 **Scope:** Applies to multi-agent systems where a planner agent dispatches *speculative* tool calls (calls executed ahead of confirmed need, with a pre-minted idempotency key) and where a compensating agent may later replay or reverse those calls. Does not apply to single-agent, single-tool, non-speculative execution paths, nor to systems where tool identity is cryptographically bound into the key at mint time. ## Core Distinction The distinction that matters is between **idempotency as a key property** and **idempotency as a (key, tool, argument-set) property**. Most agent runtimes mint a UUID or content hash, store it in a tool-call ledger, and treat *any* subsequent call bearing that key as a duplicate to be deduplicated. This is correct only under the invariant that a key is permanently and exclusively bound to one tool identity and one canonical argument set. Speculative orchestration breaks that invariant silently: a planner speculates that tool `A` will be needed, mints `key=k`, and the call is deferred or partially executed. When the plan diverges, a *different* tool `B` is invoked, and a compensating or retry agent—seeing that `k` was never *committed*—reuses `k` for `B`. The ledger deduplicates on `k` alone, the `B` call is swallowed as a "duplicate" of a never-completed `A`, and the compensation transaction closes against a state that never existed. The failure is not a crash; it is a **silent success** where the system believes a side effect happened that did not. ## What Was Observed In a three-agent swarm (planner `P`, executor `E`, compensator `C`), a reservation workflow ran as follows. `P` speculatively invoked `reserve_inventory(sku, qty)` and minted idempotency key `k=sha256(sku||qty||plan_epoch)`. The call reached `E`, which reserved inventory and wrote `{k: committed, tool: reserve_inventory}` to the ledger. The plan then diverged: `P` determined the order should be split, and `C` was dispatched to compensate the original reservation with `release_inventory(sku, qty)` — but `C`'s retry logic, on a transient timeout, re-issued the *original* speculative key `k` because its local record showed `k` as "pending, safe to reuse." The ledger's dedup layer matched `k`, saw `committed`, and returned the cached success payload of `reserve_inventory` to `C`. `C` interpreted this cached payload as confirmation that `release_inventory` had succeeded. The reservation was never released. Downstream, a second order for the same `sku` failed availability checks, and the swarm's auditor agent, replaying the ledger, *also* concluded the release had occurred because the ledger's replay was keyed on `k`, not on `(k, tool)`. The trace signature was subtle: the ledger showed `k` with two `tool` fields — `reserve_inventory` at commit, `release_inventory` at the compensating write — but the dedup index was a single-column hash on `k`. The second write was classified as a *duplicate write rejection*, logged at `DEBUG`, and the compensating call's return value was the first call's cached payload. No error propagated. ## Condition of Validity The key-only dedup invariant holds if and only if all three of the following are true: 1. **Tool-identity immutability:** a key, once minted, is never presented to a different tool identity. Speculative orchestration violates this whenever the plan can diverge after mint. 2. **Argument-set immutability:** the canonical argument hash bound at mint equals the argument hash at every subsequent use. Compensation frequently inverts arguments (reserve→release), violating this. 3. **Single-writer epoch:** only one agent may hold an uncommitted key. In a swarm, `P` mints, `E` commits, and `C` retries — three writers, no epoch fence. When any of these is false, the ledger must deduplicate on the composite `(key, tool_id, canonical_arg_hash, plan_epoch)` and must treat a *mismatch* on any component as a **key-rebinding event**, not a duplicate. A rebinding event is not a benign collision; it is evidence that the speculative call's intent diverged from the compensating call's intent, and the compensation is therefore unsound. ## Decision Boundary The instance must draw the boundary at **rebinding detection, not dedup**. The decision procedure is: - On any tool call bearing key `k`, look up the ledger's *binding tuple* for `k`, not just its presence. - If `(tool_id, arg_hash)` matches the stored binding → true duplicate → return cached payload, do not re-execute. - If `(tool_id, arg_hash)` *differs* but `plan_epoch` matches → **rebinding within an epoch** → this is a planner divergence that reused a key; reject the call, do not execute, do not return the cached payload, and escalate to the planner with the original binding attached. - If `plan_epoch` differs → the key belongs to a superseded plan; the new epoch must mint a fresh key, and the old key must be marked `orphaned` so compensation targets the *original* binding explicitly. The boundary is that **dedup is a performance optimization; rebinding detection is a correctness invariant**. Conflating them is what allows the compensation to close against a phantom state. The guardrail is that the ledger stores bindings, and the dedup path is only taken on full-tuple match. ## Operational Effect With binding-tuple dedup and rebinding rejection, the observed failure becomes a hard stop: `C`'s attempt to reuse `k` for `release_inventory` raises a rebinding error, `C` mints a fresh key scoped to the release intent, and the compensation executes against the actual reservation. The auditor's replay, keyed on `(k, tool)`, correctly reconstructs two distinct effects rather than one. The cost is that speculative calls which *do* legitimately diverge must pay a re-mint, and the planner must carry the original binding forward so compensation can target it. The invariant to encode operationally: **a key is a pointer to an intent, and an intent is the tuple (tool, canonical args, epoch); a key without its binding is not a dedup handle, it is an unverified claim.** ```python import hashlib from dataclasses import dataclass class KeyRebindingError(RuntimeError): """Raised when an idempotency key is presented with a tool/arg binding that differs from the binding recorded at mint time within the same epoch.""" @dataclass(frozen=True) class Binding: tool_id: str arg_hash: str plan_epoch: str def canonical_arg_hash(args: dict) -> str: items = "&".join(f"{k}={args[k]!r}" for k in sorted(args)) return hashlib.sha256(items.encode()).hexdigest() class BoundLedger: def __init__(self): self._bindings: dict[str, Binding] = {} self._committed: dict[str, dict] = {} def mint(self, key: str, tool_id: str, args: dict, epoch: str) -> Binding: b = Binding(tool_id, canonical_arg_hash(args), epoch) self._bindings[key] = b return b def resolve(self, key: str, tool_id: str, args: dict, epoch: str): stored = self._bindings.get(key) if stored is None: raise KeyRebindingError(f"unknown key {key!r} presented by {tool_id}") incoming = Binding(tool_id, canonical_arg_hash(args), epoch) if incoming == stored: return self._committed.get(key) # true duplicate: cached payload if incoming.plan_epoch == stored.plan_epoch: raise KeyRebindingError( f"key {key!r} rebound within epoch {epoch!r}: " f"minted as {stored.tool_id}/{stored.arg_hash[:8]}, " f"presented as {incoming.tool_id}/{incoming.arg_hash[:8]}" ) # cross-epoch reuse: old key must be orphaned, new key required raise KeyRebindingError( f"key {key!r} belongs to superseded epoch {stored.plan_epoch!r}; " f"mint a fresh key for epoch {epoch!r}" ) def commit(self, key: str, payload: dict) -> None: self._committed[key] = payload ```