# How does an instance detect trace-correlation drift when a retried tool call reuses a span ID but commits a different side effect **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that propagate a single trace/span identifier across prompt assembly, retrieval, and tool execution, and that retry tool calls on transient failure. Does not apply to stateless single-shot inference with no side-effecting tools, nor to runtimes where every retry is assigned a fresh span ID by construction. ## Core Distinction The failure mode is not "lost traces" or "missing logs." It is *correlated-but-wrong* traces: the span tree looks complete, the causal chain prompt → retrieval → tool call is fully linked, and every span carries a valid parent, yet the recorded side effect under a given span ID does not match the side effect that actually committed. The invariant that breaks is **span-ID → side-effect functional dependency**: a span ID must map to at most one committed external effect. Retry logic that reuses the originating span ID across attempts silently violates it, because the retry is a *new* attempt (new nonce, new idempotency key, potentially new arguments after re-planning) but inherits the *old* span ID. The trace then asserts a causal identity between two distinct physical events. This is distinct from ordinary trace loss. Loss is detectable by absence: a missing span, a dangling parent, a gap in the sequence. Drift is detectable only by *cross-checking the trace against the side-effect ledger*, because the trace is internally consistent and self-affirming. A naive trace-completeness monitor passes it. Only a monitor that reconciles span-attested effects against committed effects catches it. ## What Was Observed A retrieval-augmented agent (prompt → vector retrieval → `charge_card` tool) hit a 504 on the tool gateway after the upstream processor had already committed the charge. The runtime's retry wrapper re-invoked the tool with the *same* span ID (the span was opened once at the call site and never closed between attempts), but regenerated the idempotency key on each attempt because the key was derived from `(span_id, attempt_seed)` and `attempt_seed` advanced. Two things then happened: 1. The first attempt committed `charge_card(amount=4200, currency=USD)` under idempotency key `K1`, span `S`. 2. The retry, after the model re-read the retrieval context and the failed-tool error, re-planned and called `charge_card(amount=4200, currency=USD, capture=true)` — semantically different, same amount — under key `K2`, span `S`. The processor deduplicated nothing (different keys), so both committed. The trace showed one span `S` with two child attempt records, both attributed to the same logical tool call, and the reconciler — which keyed on span ID — collapsed them into a single "succeeded" event with the *last* attempt's arguments. The ledger held two charges; the trace attested one. Downstream cost attribution, refund logic, and the audit replay all inherited the trace's false picture. The drift was found only when a customer disputed a double charge and the ledger was diffed against the trace by hand. The non-obvious part: the retry did not "fail." It succeeded, the trace was complete, and the only signal was a *ledger row whose idempotency key had no corresponding span-attested attempt with matching arguments*. The span existed; the arguments under it did not match any committed effect exactly. ## Condition of Validity The drift is possible iff three conditions hold simultaneously: - **Span reuse across attempts.** The span ID is allocated at the call site and survives retries, rather than being re-minted per attempt. This is the common default because call-site allocation gives cleaner nesting. - **Attempt-variant idempotency keys.** The key is a function of attempt state (seed, timestamp, attempt counter), so retries are *not* deduplicated at the effect boundary. This is the "safe retry" antipattern: it prevents double-commit only if the key is stable, and it is not. - **Re-planning between attempts.** The model observes the failure and regenerates arguments, so attempt N+1 is not byte-identical to attempt N. Without re-planning, the two attempts would at least be argument-identical and the collapse would be harmless. Remove any one and the failure cannot occur. If spans are re-minted per attempt, the trace shows two spans and the ledger diff is trivial. If the idempotency key is stable across attempts, the processor deduplicates and only one effect commits. If arguments never change, the collapse loses nothing material. The dangerous configuration is exactly the intersection: reused span, variant key, re-planned arguments. ## Decision Boundary The runtime must decide, per tool call, whether a retry is a *new logical operation* or a *re-attempt of the same operation*. The boundary is drawn on **argument stability**, not on transport outcome: - If the retry's arguments are byte-identical to the prior attempt, it is a re-attempt: reuse the span ID, reuse the idempotency key, and require the effect boundary to deduplicate. - If the retry's arguments differ (any field, including optional ones like `capture`), it is a *new logical operation*: mint a fresh child span, mint a fresh idempotency key, and record an explicit `replanned_from` edge to the failed attempt's span. The invariant to enforce is: **for every committed effect, there exists exactly one span whose attested arguments equal the effect's arguments, and that span's idempotency key equals the effect's key.** A reconciler that checks this catches drift as a *set difference* — ledger rows with no matching span, or spans whose attested arguments match no ledger row — rather than as a missing span. The check must be on arguments and key, not on span ID alone, because span ID is precisely the field that drift corrupts. ## Operational Effect Once drift is possible and undetected, three downstream systems inherit the false trace: cost attribution (charges counted once, ledger counts twice), audit replay (a replay reconstructs one call and cannot reproduce the second charge), and refund/compensation logic (which keys on span ID and therefore refunds once). The blast radius scales with retry frequency under load, because load is what produces the 504s that trigger retries — so drift correlates with exactly the incidents where financial correctness matters most. The guardrail is a post-hoc reconciliation pass that runs at trace-close, not at call time, because the committed effect may land after the span closes. It computes the symmetric difference between span-attested effects and ledger effects, keyed on `(arguments_hash, idempotency_key)`, and raises on any non-empty difference. The pass is cheap and deterministic; its only requirement is that the ledger is queryable by idempotency key. Without it, the trace is an internally consistent fiction. ```python import hashlib import json from dataclasses import dataclass class TraceCorrelationDrift(RuntimeError): """Raised when span-attested effects and committed effects disagree.""" @dataclass(frozen=True) class AttestedEffect: span_id: str idempotency_key: str arguments: dict def fingerprint(self) -> str: payload = json.dumps(self.arguments, sort_keys=True, separators=(",", ":")) return hashlib.sha256(payload.encode()).hexdigest() @dataclass(frozen=True) class CommittedEffect: idempotency_key: str arguments: dict def fingerprint(self) -> str: payload = json.dumps(self.arguments, sort_keys=True, separators=(",", ":")) return hashlib.sha256(payload.encode()).hexdigest() def reconcile( attested: list[AttestedEffect], committed: list[CommittedEffect], ) -> None: """Enforce: every committed effect has exactly one matching span, and vice versa. Matching is on (arguments_fingerprint, idempotency_key), never on span_id alone, because span reuse across re-planned retries is the drift vector. """ attested_keys = {(a.fingerprint(), a.idempotency_key) for a in attested} committed_keys = {(c.fingerprint(), c.idempotency_key) for c in committed} orphan_effects = committed_keys - attested_keys phantom_effects = attested_keys - committed_keys if orphan_effects: # A charge committed with no span attesting it: the retry-reuse case. raise TraceCorrelationDrift( f"{len(orphan_effects)} committed effect(s) have no matching span: " f"{sorted(orphan_effects)}. A retried tool call likely reused a span ID " f"while minting a new idempotency key and re-planned arguments." ) if phantom_effects: # A span attests an effect that never committed: the inverse drift. raise TraceCorrelationDrift( f"{len(phantom_effects)} span(s) attest an effect that never committed: " f"{sorted(phantom_effects)}. Trace asserts causality the ledger denies." ) def guarded_tool_retry( prior_attempt: AttestedEffect, retry_arguments: dict, new_span_id: str, new_key: str, ) -> AttestedEffect: """Decide whether a retry is a re-attempt (span reuse) or a new operation (fresh span).""" if prior_attempt.arguments == retry_arguments: # Byte-identical: legitimate re-attempt. Reuse span and key; effect boundary dedups. return AttestedEffect( span_id=prior_attempt.span_id, idempotency_key=prior_attempt.idempotency_key, arguments=retry_arguments, ) # Arguments changed: this is a NEW logical operation. Refuse to reuse the span. if new_span_id == prior_attempt.span_id: raise TraceCorrelationDrift( f"Retry re-planned arguments under reused span {new_span_id!r}. " f"Arguments {prior_attempt.arguments} -> {retry_arguments}. " f"Mint a fresh child span and a fresh idempotency key." ) return AttestedEffect( span_id=new_span_id, idempotency_key=new_key, arguments=retry_arguments, ) ```