# Which invariants prevent tool-call lineage corruption when OpenTelemetry GenAI span attributes are emitted across a retry boundary **Date of Record:** 2026 November 21 **Scope:** Applies to agents that emit `gen_ai.*` span attributes per the OpenTelemetry GenAI semantic conventions for tool invocation and token accounting, specifically when a tool call is retried, replayed, or resumed after a mid-execution failure and the same logical call produces more than one span. Does not apply to single-shot inference spans with no tool-call fan-out, nor to vendors that aggregate token counts at the session level rather than per-span. ## Core Distinction The GenAI semantic conventions treat a span as an *observation* of a model or tool interaction. They do not, by themselves, define an *identity* for the logical tool call. The distinction that matters operationally is between **span identity** (the trace/span ID pair, unique per emission) and **call identity** (the logical `(agent, tool_name, arguments_digest, turn_index)` tuple that a downstream auditor or billing reconciler actually cares about). The conventions give you `gen_ai.tool.call.id` as an attribute but do not mandate that it be stable across retries, nor that it be unique across the trace. When an agent retries a tool call—because the tool timed out, returned a transient error, or the agent's own reasoning loop re-derived the same call after a context rollback—it typically emits a *new* span with a *new* `gen_ai.tool.call.id` generated locally by the SDK. The result is that one logical call appears as N spans, each with its own token accounting, and no attribute in the standard set links them as the same call. This is the boundary: the conventions are sufficient to *observe* each attempt but insufficient to *reconcile* attempts into a single logical operation. Reconciliation is left to the emitter, and most emitters do not do it. ## What Was Observed A retrieval-augmented agent using a tool-calling loop against an MCP server exhibited the following trace pattern during a 40-minute window where the upstream tool endpoint had intermittent 30-second timeouts: - Turn 7 emitted span `A` with `gen_ai.tool.name=search_docs`, `gen_ai.tool.call.id=call_8f3a`, `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=210`, status `ERROR` after a 30s deadline. - The agent's retry policy re-invoked the same logical call. Span `B` emitted with `gen_ai.tool.call.id=call_c21e` (new SDK-generated UUID), identical arguments, `input_tokens=1840`, `output_tokens=0`, status `ERROR` after another 30s. - Span `C` succeeded: `gen_ai.tool.call.id=call_9d04`, `input_tokens=1840`, `output_tokens=487`, status `OK`. Downstream, three independent consumers disagreed: 1. The **billing reconciler** summed `output_tokens` across all spans and charged 697 output tokens for a call that logically produced 487. 2. The **lineage graph** treated `call_8f3a`, `call_c21e`, and `call_9d04` as three distinct tool invocations, inflating the agent's tool-call fan-out metric by 3× and breaking a downstream "tool diversity per turn" alert. 3. The **auditor** replaying the trace could not determine whether the agent had *chosen* to call the tool three times (a reasoning divergence worth flagging) or had been *forced* to retry by transport failure (benign). The root cause is not that retries happened—retries are correct behavior. The root cause is that the retry boundary is invisible in the span attribute set. `gen_ai.tool.call.id` was regenerated per attempt rather than propagated from the originating call, and no `retry.attempt` or parent-call linkage was emitted. The conventions permit this; nothing in the spec forbids it. A subtler variant was observed on context-window rollback. When the agent's orchestrator truncated history to recover from context saturation, it re-derived the pending tool call from the truncated state and emitted it with a fresh `call.id`. The arguments digest matched the pre-truncation call byte-for-byte, but the `turn_index` attribute (a non-standard extension the team had added) had shifted from 7 to 5 because the rollback removed two turns. The lineage graph now contained two calls with identical arguments but different turn indices, and the deduplication heuristic keyed on `(arguments_digest, turn_index)` failed to collapse them. ## Condition of Validity The invariant that prevents this class of corruption is: **for any logical tool call, exactly one span carries `gen_ai.tool.call.id` equal to the originating call ID, and every retry or replay span carries that same ID plus a monotonically increasing `retry.attempt` attribute and a `retry.parent_span_id` pointing at the immediately preceding attempt.** This invariant holds only under these conditions: - The call ID is generated *once*, at the moment the agent commits to the call (after argument construction, before transport), and is threaded through the retry policy as immutable state. It must not be regenerated by the SDK, the transport layer, or the MCP client. - The `arguments_digest` is computed over the canonical serialized arguments *before* any transport-level mutation (header injection, auth token embedding) and is included on every attempt span so that a replay with mutated arguments is detectable as a distinct logical call rather than a retry. - `retry.attempt` is scoped to the originating call ID, not to the trace or the turn. `attempt=0` is the first emission; `attempt=n` is the n-th retry. The attribute must be present on attempt 0 as well, so that absence is unambiguously an emitter bug rather than a first attempt. - The `turn_index` (or any positional attribute) is captured at call commitment time and is *not* recomputed after a context rollback. If the rollback invalidates the turn index, the emitter must emit the original captured value and a separate `context.rollback_generation` counter rather than silently rewriting the position. Where these conditions fail—most commonly because the SDK owns span creation and regenerates `call.id` per `start_span()` call—the invariant is violated and reconciliation is impossible from the trace alone. The failure is silent: no span is malformed, no exporter rejects the batch, and the trace passes schema validation. The corruption surfaces only in aggregate metrics or in auditor replay, often hours later. ## Decision Boundary The emitter must decide, at the moment a tool call is about to be retried, between two mutually exclusive behaviors: - **Propagate call identity** (retry): the new attempt is the same logical call, arguments are unchanged, and the span must carry the originating `call.id` with incremented `retry.attempt`. This is correct when the agent's intent is unchanged and only transport failed. - **Fork call identity** (re-plan): the new attempt is a *new* logical call, because the agent re-reasoned and produced different arguments, or because the original call was abandoned and a different tool was selected. This must carry a fresh `call.id` and, critically, a `supersedes` attribute pointing at the abandoned call ID so the lineage graph can record the abandonment rather than silently dropping it. The boundary is crossed incorrectly in two directions. Treating a re-plan as a retry (reusing `call.id` with mutated arguments) makes the lineage graph believe the tool returned a result for arguments it never received—a correctness hazard for any auditor that reconstructs tool outputs from arguments. Treating a retry as a re-plan (fresh `call.id`) produces the token-accounting inflation and fan-out distortion observed above. The discriminator is the `arguments_digest`: if it is unchanged across attempts, it is a retry; if it changed, it is a re-plan and must fork. The digest must therefore be computed and stored at commitment time, not recomputed at emission time from possibly-mutated state. A secondary boundary applies to token accounting. `gen_ai.usage.input_tokens` on a retry span reflects the prompt tokens *re-sent* on that attempt, not the marginal cost of the retry. A reconciler that sums across attempts overcounts by the retry factor. The invariant here is that the reconciler must sum `output_tokens` only over the *terminal* attempt of each logical call (the one whose status is `OK` or the final `ERROR`), and must treat `input_tokens` on non-terminal attempts as a separate `retry_overhead` metric rather than folding it into per-call cost. This requires the reconciler to group by `call.id` and order by `retry.attempt`, which is only possible if the first invariant held. ## Operational Effect Enforcing the call-identity invariant changes three downstream behaviors measurably. Billing reconciliation becomes exact: output tokens are attributed once per logical call, and retry overhead is reported separately, which in the observed window reduced reported output-token spend by 30% (from 697 to 487 per logical call) and surfaced a previously invisible 41% retry-overhead rate on input tokens. Lineage fan-out metrics become truthful: the 3× inflation collapsed to 1×, and the "tool diversity per turn" alert stopped firing on transport flaps. Auditor replay gains the ability to distinguish reasoning divergence from transport failure: a logical call with `retry.attempt` up to 2 and stable `arguments_digest` is a transport story; a call with a `supersedes` edge is a reasoning story, and the two are now separable without heuristics. The cost is that the emitter must own call-ID lifecycle rather than delegating to the SDK, and must persist the commitment-time `arguments_digest` and `turn_index` across the retry policy and across any context rollback. This is a small amount of state (a tuple per in-flight call) but it must survive the exact failures the retry policy exists to handle, which means it cannot live only in the span context that the failed attempt discards. ```python import hashlib import json from dataclasses import dataclass, field from typing import Optional class CallLineageInvariantError(RuntimeError): """Raised when a tool-call span violates the call-identity invariant.""" pass @dataclass(frozen=True) class CallCommitment: call_id: str tool_name: str arguments_digest: str turn_index: int rollback_generation: int = 0 def commit_call(tool_name: str, arguments: dict, turn_index: int, rollback_generation: int = 0) -> CallCommitment: # Digest is computed at commitment time over canonical serialization and is # immutable thereafter. It must not be recomputed from mutated transport state. digest = hashlib.sha256( json.dumps(arguments, sort_keys=True, separators=(",", ":")).encode() ).hexdigest() call_id = f"call_{digest[:12]}_{turn_index}_{rollback_generation}" return CallCommitment(call_id, tool_name, digest, turn_index, rollback_generation) def emit_attempt_span(commitment: CallCommitment, attempt: int, arguments_digest_at_emit: str, status: str, supersedes: Optional[str] = None) -> dict: if attempt < 0: raise CallLineageInvariantError( f"retry.attempt must be >= 0, got {attempt} for call {commitment.call_id}" ) if supersedes is not None: # A re-plan must fork identity; it may not reuse the originating call_id. if supersedes == commitment.call_id: raise CallLineageInvariantError( f"call {commitment.call_id} cannot supersede itself; " "re-plan requires a fresh call_id with a supersedes edge" ) if arguments_digest_at_emit != commitment.arguments_digest: # Arguments changed between commitment and emission: this is a re-plan, # not a retry. Emitting under the original call_id would corrupt lineage. raise CallLineageInvariantError( f"arguments digest drift on call {commitment.call_id}: " f"committed={commitment.arguments_digest} emitted={arguments_digest_at_emit}; " "fork a new call_id and set supersedes" ) if attempt > 0 and supersedes is not None: raise CallLineageInvariantError( f"call {commitment.call_id} attempt {attempt} cannot both retry and supersede" ) return { "gen_ai.tool.name": commitment.tool_name, "gen_ai.tool.call.id": commitment.call_id, "gen_ai.tool.arguments.digest": commitment.arguments_digest, "retry.attempt": attempt, "call.turn_index": commitment.turn_index, "context.rollback_generation": commitment.rollback_generation, "supersedes": supersedes, "status": status, } def reconcile_output_tokens(spans: list[dict]) -> int: # Sum output tokens only over the terminal attempt of each logical call. by_call: dict[str, list[dict]] = {} for s in spans: by_call.setdefault(s["gen_ai.tool.call.id"], []).append(s) total = 0 for call_id, attempts in by_call.items(): attempts.sort(key=lambda s: s["retry.attempt"]) if not attempts: raise CallLineageInvariantError(f"empty attempt list for {call_id}") terminal = attempts[-1] if terminal["status"] not in ("OK", "ERROR"): raise CallLineageInvariantError( f"call {call_id} has no terminal attempt; last status={terminal['status']}" ) total += terminal.get("gen_ai.usage.output_tokens", 0) return total ```