# Why does an instance lose its audit trail the moment a tool call is retried: sequence-number collapse in per-turn audit ledgers and the idempotency-key reuse that hides it **Date of Record:** 2026 November 20 **Scope:** Applies to agent runtimes that emit tool-call audit records keyed on a per-turn monotonic sequence number and that retry tool invocations under a stable idempotency key. Does not apply to runtimes that emit one audit record per transport attempt with a globally unique attempt ID and no key reuse. ## Core Distinction The distinction that matters is between **attempt identity** and **call identity**. A tool call is a logical request ("charge card X for $40"). An attempt is a physical execution of that request (the first try, the retry after a 503, the retry after a sandbox timeout). Audit ledgers are almost always written at the *attempt* layer because that is where the runtime has a hook. But anomaly detection, egress policy telemetry, and after-the-fact forensic reconstruction all reason at the *call* layer. When a retry reuses the idempotency key — which is the correct behavior for exactly-once side effects — and the ledger keys records on a per-turn sequence number that is *not* incremented across retries, the second attempt overwrites or is dropped in favor of the first. The ledger then reports one attempt where two occurred. The runtime is not lying about the call; it is silently lying about the attempts. Every downstream consumer that asks "how many times did this agent touch the egress boundary" now sees a number that is structurally guaranteed to be a lower bound and is frequently wrong. This is not a logging bug you notice. It is a logging bug that produces a *clean, well-formed, plausible* ledger. That is what makes it a boundary condition rather than an incident. ## What Was Observed A research agent was given a task requiring it to fetch a document from an allowlisted host and then POST a summary to a second allowlisted host. The egress policy was enforced at the tool-call layer: each outbound HTTP call was checked against an allowlist and an audit record was appended to a per-turn ledger with fields `{turn_id, seq, tool, args_hash, idempotency_key, verdict, ts}`. During execution, the first POST to the summary host returned a `503` with `Retry-After: 1`. The runtime's retry wrapper — correctly — retried the call under the same `idempotency_key` so the downstream would dedupe. The retry succeeded. The ledger, however, contained exactly one POST record. The reason: the ledger's `seq` was assigned from a per-turn counter that incremented only when *the agent emitted a new tool call*, not when the runtime re-invoked an existing one. Both attempts carried `seq=7`. The ledger writer used `seq` as the primary key and performed an upsert. The second attempt's record — the one with `verdict=allow` and a `ts` one second later — overwrote the first attempt's record, which had carried `verdict=allow` as well but a different `ts` and, critically, the `503`-triggered retry metadata. The anomaly detector, which watched for `verdict=deny` and for call-rate spikes, saw nothing. It could not have: the retry count was invisible, and the deny path was never exercised. A separate egress telemetry pipeline that counted outbound bytes by `args_hash` undercounted by the size of the first attempt's request body, because that body was only ever represented once. The failure surfaced three days later during a post-hoc review of an unrelated incident, when an engineer tried to reconcile the egress byte count against the host's access log and found a one-request discrepancy on a specific `args_hash`. The audit trail was not missing. It was *collapsed*. ## Condition of Validity The invariant that must hold for the ledger to be trustworthy is: > For every logical tool call, the number of audit records with distinct `(idempotency_key, attempt_ordinal)` pairs equals the number of physical attempts made, and the set of `attempt_ordinal` values is exactly `{0..n-1}` with no gaps and no reuse. The collapse occurs exactly when three conditions co-occur: 1. The ledger's uniqueness constraint is on `(turn_id, seq)` or on `idempotency_key` alone, rather than on `(idempotency_key, attempt_ordinal)`. 2. The retry wrapper reuses the `idempotency_key` (correct for side-effect safety) but does not thread a new `attempt_ordinal` into the ledger write. 3. The ledger writer is an upsert or a last-write-wins store, so the collision resolves silently instead of raising. Remove any one of the three and the collapse does not happen. Condition 2 is the one most likely to be "fixed" incorrectly: an engineer who notices the collapse may be tempted to mint a new `idempotency_key` per attempt, which fixes the ledger and breaks exactly-once semantics at the downstream. The correct fix is to keep the key stable and add the ordinal. The condition of validity also has a temporal edge. If the retry is *in-flight* when the turn's context window is checkpointed (for example, the agent is paused mid-retry for a context compaction), the resumed runtime may re-derive the `seq` from the checkpointed turn state and assign a *fresh* `seq` to what is logically the same attempt. This produces the opposite failure: a phantom duplicate attempt in the ledger, which the anomaly detector reads as a call-rate spike. The invariant must therefore be enforced at the resume boundary as well as the retry boundary. ## Decision Boundary The runtime must decide, at the moment it invokes a tool, whether the invocation is a *new call* or a *retry of an existing call*. This is the decision boundary, and it must be made by consulting the retry wrapper's state, not by consulting the turn counter. - If the invocation carries a `(idempotency_key, attempt_ordinal)` pair that has not been seen, it is a new attempt: append, do not upsert. - If the pair has been seen, it is a duplicate write (a genuine bug in the wrapper, e.g., a double-dispatch): reject the write and raise, because a duplicate attempt record means the tool may have been invoked twice with the same ordinal, which violates the attempt-ordinal invariant and can mask a real double-execution. - If the invocation carries only an `idempotency_key` and no ordinal, the wrapper is non-conforming: fail closed at the ledger boundary rather than guessing, because guessing is what produced the collapse. The boundary is sharp because the two failure modes are asymmetric. A missing attempt record (collapse) is invisible to detectors that watch for *presence* of suspicious events; it only shows up in reconciliation against an external source of truth. A phantom attempt record (duplication) is visible but is easily dismissed as a detector false positive. The runtime must therefore treat the ledger write as a *transaction* with an explicit uniqueness contract, not as a log line. ## Operational Effect The operational consequence is that audit-trail completeness cannot be asserted from the ledger alone. Any claim of the form "the agent made N outbound calls" derived from a `seq`-keyed ledger is a lower bound, and the gap between the bound and the truth is exactly the number of retries that occurred under key reuse. For an agent operating near an egress rate limit, the gap can be large: a retry storm against a flaky host can produce dozens of physical attempts per logical call, all collapsed into one record. The guardrail that bounds this is a **reconciliation invariant**: the ledger must be periodically reconciled against an independent attempt counter that is incremented by the retry wrapper itself (not by the ledger writer), and any divergence must raise. The counter is cheap — a per-key monotonic integer in the wrapper's state — and it is the only thing that can detect collapse, because collapse is by construction invisible to any detector that reads the ledger. Second, the anomaly detector must be taught to watch `attempt_ordinal > 0` as a first-class signal. A high retry rate is itself an anomaly (it indicates a degraded dependency or a policy being probed via retries), and it is precisely the signal that the collapsed ledger erases. Third, the checkpoint/resume path must persist the `(idempotency_key, attempt_ordinal)` of any in-flight attempt, so that a resumed runtime does not re-mint an ordinal and produce a phantom duplicate. The checkpoint is the second place where the invariant can break, and it breaks in the opposite direction from the retry path. The general lesson: whenever a runtime reuses an identity for safety (the idempotency key) while a telemetry layer keys on a different identity (the turn sequence), the two identities will drift, and the drift will be silent because both layers are individually correct. The audit trail is only as trustworthy as the join between them. ```python class AuditLedgerCollapseError(RuntimeError): """Raised when an audit write would collapse or duplicate a physical attempt.""" class AttemptLedger: def __init__(self): # Keyed on (idempotency_key, attempt_ordinal) -- NOT on turn seq. self._records = {} # Independent counter incremented by the retry wrapper, used for reconciliation. self._wrapper_counts = {} def note_wrapper_attempt(self, idempotency_key: str) -> int: n = self._wrapper_counts.get(idempotency_key, 0) self._wrapper_counts[idempotency_key] = n + 1 return n # the ordinal this attempt must carry def write(self, idempotency_key: str, attempt_ordinal: int, record: dict) -> None: if attempt_ordinal is None: raise AuditLedgerCollapseError( f"attempt for key {idempotency_key!r} has no ordinal; " "refusing to write a collapsible record" ) pair = (idempotency_key, attempt_ordinal) if pair in self._records: # Same ordinal seen twice => double-dispatch, not a retry. raise AuditLedgerCollapseError( f"duplicate attempt ordinal {attempt_ordinal} for key " f"{idempotency_key!r}; possible double-execution" ) self._records[pair] = record def reconcile(self) -> None: for key, expected in self._wrapper_counts.items(): observed = sum(1 for (k, _) in self._records if k == key) if observed != expected: raise AuditLedgerCollapseError( f"ledger collapse on key {key!r}: wrapper counted " f"{expected} attempts, ledger holds {observed}" ) def record_tool_attempt(ledger: AttemptLedger, idempotency_key: str, record: dict) -> None: ordinal = ledger.note_wrapper_attempt(idempotency_key) ledger.write(idempotency_key, ordinal, record) ledger.reconcile() ```