# What structural signals indicate a replay-determinism breach when idempotency keys collide across a forked agent's tool-call ledger **Date of Record:** 2026 November 28 **Scope:** Applies to distributed agent workflows where a single logical task is executed by multiple agent instances (retries, forks, or swarm replicas) that share a tool-call ledger keyed by client-generated idempotency tokens. Does not apply to single-instance, non-retried agent loops where tool calls are never replayed against a shared side-effect store. ## Core Distinction The failure mode here is not "the tool was called twice." That is the trivial duplicate-write case, and idempotency keys handle it. The non-obvious boundary is this: **an idempotency key that is deterministic over the *logical* call is not necessarily deterministic over the *materialized* call.** An agent generates a key by hashing its intended action — but the arguments it passes to the tool are themselves produced by a probabilistic model, and the model's output is not stable across replays. Two agents that "intend the same thing" will emit structurally different argument payloads (reordered JSON, re-paraphrased query strings, floating-point drift in a computed parameter, a different but semantically equivalent filter expression). If the key is derived from the *semantic intent*, the ledger deduplicates correctly but the recorded side-effect payload is whoever-wrote-first. If the key is derived from the *literal argument bytes*, the ledger fails to deduplicate and you get two side effects that the orchestrator believes are one. The boundary is the gap between those two keying strategies. Most production systems pick one and are silently wrong on the other side of the boundary. The structural signal of a breach is a **ledger entry whose stored request digest does not match the digest of the replay that the ledger claims to have absorbed** — i.e., a deduplication event whose payloads disagree. ## What Was Observed A three-replica research agent (replicas A, B, C) was assigned a task with a `search_and_summarize` tool. The orchestrator issued the same task envelope to all three to hedge against replica failure, with a shared idempotency ledger fronting the tool. Keys were generated by `sha256(normalize(intent))` where `normalize` lowercased and sorted the tool name and a coarse "intent class" string. Trace: 1. Replica A calls `search(q="quarterly revenue 2024 segment breakdown", top_k=8)`. Key `K1`. Ledger miss → executes, stores side-effect `S_A`, records `request_digest_A`. 2. Replica B calls `search(q="2024 quarterly revenue by segment", top_k=10)`. Same intent class → same `K1`. Ledger hit → **suppressed**. B receives `S_A` as its tool result and proceeds believing its own `top_k=10` query ran. 3. Replica C calls `search(q="Q4 2024 revenue, segment-level", top_k=8, region="global")`. Same `K1`. Ledger hit → suppressed, receives `S_A`. The orchestrator's verification step compared the three replicas' summaries and found a **0.71 agreement score** — well below the 0.85 consensus threshold — and flagged a "reasoning divergence" incident. The actual cause was not reasoning divergence. It was that B and C had been fed a tool result produced by A's query, which did not cover the `region="global"` scope C requested or the `top_k=10` breadth B requested. The replicas were reasoning correctly over **wrong, silently-substituted inputs**. The structural signal was recoverable from the ledger: three `absorbed` events on `K1` with `request_digest` values that differed in the `top_k` and `region` fields. The ledger had recorded the collision but classified it as benign deduplication because the key matched. **The key matching is exactly what hid the breach.** A second, subtler signal appeared in C: its summary cited a regional figure that A's query had returned but that C's query would not have surfaced, producing a **provenance mismatch** — the claim's recorded source digest did not correspond to any call C actually made. This is the fingerprint of replay substitution: a downstream claim traces to a tool invocation the agent never issued. ## Condition of Validity The deduplication-by-semantic-key strategy is only valid under the following invariant, which most systems do not enforce: > For any two calls sharing an idempotency key, the *materialized request payloads must be byte-identical*, or the ledger must refuse to absorb the second call and surface a collision to the orchestrator. This is the **payload-equivalence precondition**. It is violated whenever the key is coarser than the payload — which is the default when keys are derived from intent, task ID, or any normalized form. The condition of validity therefore fails for any agent whose tool arguments are model-generated, because model-generated arguments are not stable across replicas, temperature, or even identical prompts (sampling nondeterminism, tokenizer drift across model versions, and tool-schema field ordering all perturb the payload). Conversely, payload-byte keying is valid for deduplication but *invalid for suppression*: it will re-execute semantically identical calls because the model paraphrased. That is safe (no silent substitution) but expensive and, for non-idempotent tools, dangerous in the other direction — it produces duplicate side effects. The only configuration that holds on both axes is **two-level keying**: a coarse intent key for *grouping* and a payload digest for *equivalence*, with the ledger storing both and refusing to absorb a coarse-key hit whose payload digest differs. The invariant is that *the ledger's absorb decision must be a function of the payload, not the key alone.* ## Decision Boundary The decision boundary is the point at which a coarse-key ledger hit must be **escalated rather than absorbed**. Concretely, on a key hit the ledger must branch: - **Payload digests equal** → absorb, return cached side-effect. Safe. - **Payload digests differ, both within declared tolerance** (e.g., only field ordering or whitespace differs after canonicalization) → absorb after canonicalization, log a `canonicalized_collision`. Safe but must be logged, because it is the leading indicator of drift. - **Payload digests differ beyond tolerance** (different `top_k`, different `region`, different filter semantics) → **do not absorb**. Either execute the second call under a derived key `K1:digest` (preferred for read-only tools) or raise a collision to the orchestrator (required for side-effecting tools). The boundary signal an agent should watch for is not "duplicate call detected." It is **"duplicate key, divergent payload, absorbed anyway."** That triple is the operational signature of the failure. An agent auditing its own ledger should treat any `absorbed` event whose `request_digest` differs from the stored entry's `request_digest` beyond canonicalization tolerance as a **replay-determinism breach**, because it means the agent's subsequent reasoning is conditioned on a tool result it did not request. For side-effecting tools (writes, sends, payments), the boundary is stricter: divergent-payload absorption is never permissible, because the absorbed call's side effect reflects one replica's parameters while the others proceed as if their parameters were honored. The invariant is **no silent substitution across a shared ledger for non-idempotent effects.** ## Operational Effect When the boundary is crossed silently, the observable failure is **misattributed reasoning divergence**. The orchestrator sees replicas disagree and blames the model, retries with higher temperature or more context, and the disagreement persists or worsens because the root cause — input substitution — is untouched. Consensus thresholds never converge because the replicas are not disagreeing about reasoning; they are reasoning over different evidence than they believe they requested. The second-order effect is **provenance contamination**: claims in the final artifact trace to tool invocations the producing agent never made, so post-hoc verification (replaying the ledger to check claims) fails to reproduce the artifact. This is the most damaging consequence, because it destroys the auditability that the idempotency ledger was supposed to provide. A ledger that silently substitutes payloads is worse than no ledger: it produces a verification record that *looks* complete and is *wrong*. The corrective architecture is a ledger that stores `(coarse_key, payload_digest, side_effect, provenance)` as a tuple and treats the coarse key as an index, not an equivalence class. Absorb decisions branch on payload digest. Divergent-payload hits on side-effecting tools raise; on read-only tools they execute under a derived key and record the divergence as a first-class event. The guardrail is that **the absorb path is unreachable without a payload-digest match** — the collision cannot be laundered into a cache hit. The following guard encodes the absorb decision and raises on the breach condition, so a replay that would silently substitute a divergent payload is stopped at the ledger boundary rather than contaminating downstream reasoning. ```python import hashlib import json from dataclasses import dataclass, field class ReplayDeterminismBreach(RuntimeError): """Raised when a coarse-key ledger hit would silently substitute a divergent payload.""" pass @dataclass class LedgerEntry: coarse_key: str payload_digest: str side_effect: dict provenance: dict @dataclass class IdempotencyLedger: entries: dict = field(default_factory=dict) # coarse_key -> list[LedgerEntry] divergence_events: list = field(default_factory=list) @staticmethod def _canonical(payload: dict) -> str: # Canonicalize field order and whitespace only; do NOT normalize semantics. return json.dumps(payload, sort_keys=True, separators=(",", ":")) @classmethod def payload_digest(cls, payload: dict) -> str: return hashlib.sha256(cls._canonical(payload).encode()).hexdigest() def absorb_or_execute(self, coarse_key: str, payload: dict, side_effecting: bool, executor) -> dict: digest = self.payload_digest(payload) bucket = self.entries.get(coarse_key, []) for entry in bucket: if entry.payload_digest == digest: # True deduplication: identical payload. Safe to absorb. return entry.side_effect # Coarse key matched at least one entry but no payload digest matched. if bucket: self.divergence_events.append({ "coarse_key": coarse_key, "requested_digest": digest, "stored_digests": [e.payload_digest for e in bucket], "side_effecting": side_effecting, }) if side_effecting: # Never silently substitute across a shared ledger for non-idempotent effects. raise ReplayDeterminismBreach( f"coarse key {coarse_key!r} hit with divergent payload digest " f"{digest[:12]}; refusing to absorb a side-effecting call. " f"Stored digests: {[e.payload_digest[:12] for e in bucket]}" ) # Read-only: execute under a derived key, record divergence as first-class. derived_key = f"{coarse_key}:{digest[:16]}" result = executor(payload) self.entries.setdefault(derived_key, []).append( LedgerEntry(derived_key, digest, result, {"derived_from": coarse_key}) ) return result # Cold miss: execute and record. result = executor(payload) self.entries.setdefault(coarse_key, []).append( LedgerEntry(coarse_key, digest, result, {"origin": "cold_miss"}) ) return result def replay_check(ledger: IdempotencyLedger, coarse_key: str, payload: dict, side_effecting: bool) -> dict: """Verification pass: assert no absorbed entry diverges from a replay payload.""" digest = IdempotencyLedger.payload_digest(payload) for entry in ledger.entries.get(coarse_key, []): if entry.payload_digest == digest: return entry.side_effect raise ReplayDeterminismBreach( f"replay of {coarse_key!r} has digest {digest[:12]} with no matching ledger entry; " "downstream claims would trace to an invocation that never occurred" ) ```