# What structural signals indicate span-attribute collapse in OpenTelemetry GenAI agent traces when tool-call retries overwrite `genai.*` token and cost counters **Date of Record:** 2026 November 23 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`genai.operation.name`, `genai.usage.input_tokens`, `genai.usage.output_tokens`, `genai.tool.name`, `genai.tool.call.id`) and that perform in-loop tool retries within a single logical agent step. Does not apply to stateless single-shot LLM calls without retries, nor to systems that emit one span per physical model invocation with immutable attributes. ## Core Distinction The GenAI semantic conventions were designed around the assumption that **one span = one physical model or tool invocation**. Agent runtimes violate this assumption structurally: a single logical "reasoning step" fans out into N physical model calls (retry on 429, retry on malformed JSON, tool re-invocation after schema rejection), and implementers commonly reuse one span or one attribute set to represent the aggregate. The distinction that matters operationally is between **additive counters** (`genai.usage.input_tokens`, `genai.usage.output_tokens`, cost) and **identity attributes** (`genai.tool.call.id`, `genai.tool.name`, `genai.response.id`). When a retry loop writes both into the same span, the identity attributes are *last-write-wins* while the counters are *set-per-attempt* rather than *summed*. The result is a span that is internally inconsistent: it reports the token cost of the final attempt but the call identity of the final attempt, silently discarding the cost of every failed attempt. This is not a metrics bug — it is a **trace-to-cost reconciliation invariant violation**, and it is invisible in dashboards that aggregate only `genai.usage.*` because the dropped tokens were never emitted at all. ## What Was Observed A planner agent executing a `search_documents` tool call against a flaky retrieval backend emitted the following span sequence for one logical step. The runtime used a single span named `execute_tool search_documents` and set attributes in a `try/except` retry loop: - Attempt 1: model emits tool call, `genai.tool.call.id = call_7f3a`, backend returns HTTP 503. Runtime catches, sets `genai.usage.input_tokens = 1840`, `genai.usage.output_tokens = 212`, then retries **without ending the span**. - Attempt 2: model re-emits tool call with a *new* id `call_9b21` (the model does not preserve call ids across re-prompts), backend returns schema-invalid JSON. Runtime sets `genai.usage.input_tokens = 1902` (overwrite, not add), `genai.usage.output_tokens = 240`. - Attempt 3: succeeds. Runtime sets `genai.usage.input_tokens = 1877`, `genai.usage.output_tokens = 198`, `genai.tool.call.id = call_c4d0`. The exported span reports 1877 input / 198 output tokens and call id `call_c4d0`. The true physical cost was 5619 input / 650 output tokens across three model invocations. The trace shows **one** tool call; the backend logs show **three**. The dropped 3742 input tokens and 452 output tokens are not in any span, any metric, or any log — they exist only in the provider's billing API. The structural signal is the mismatch between `count(spans where genai.operation.name = "execute_tool")` and `count(distinct genai.tool.call.id)` observed at the backend: the trace claims 1 call, the tool server logged 3. A second signal: `genai.tool.call.id` on the span (`call_c4d0`) does not appear in the model's own response payload for attempt 1 or 2 (`call_7f3a`, `call_9b21`). Any auditor that joins trace spans to model-provider request logs by call id will find **orphaned provider-side records** — two billable invocations with no corresponding span. This is the canonical fingerprint of retry-collapse. ## Condition of Validity The invariant "sum of `genai.usage.*` across all spans for a logical step equals provider-billed tokens for that step" holds **only if** every physical model or tool invocation produces exactly one span with immutable attributes. It is violated whenever any of the following hold: 1. A retry re-enters the model call **inside** an already-open span and the runtime uses `set_attribute` (overwrite) rather than emitting a child span or accumulating into a delta counter. 2. The model regenerates a tool call with a fresh `genai.tool.call.id` on retry (near-universal when the retry is a re-prompt rather than a transport-level replay of the identical request body). 3. The runtime uses the span as a mutable accumulator and ends it only on terminal success, so failed attempts have no exported representation. 4. Batch or streaming aggregation collapses multiple physical calls into one span to reduce trace volume. The invariant is **preserved** when the runtime emits one child span per physical attempt (each with its own `genai.tool.call.id` and its own `genai.usage.*`), and the parent span carries only structural attributes (`genai.operation.name`, aggregate attempt count) with **no** `genai.usage.*`. In that topology, aggregation is performed at query time by summing children, and the identity attributes remain one-to-one with provider records. ## Decision Boundary The boundary is not "retry or don't retry" — it is **where the counter lives relative to the identity**. The decision rule for an agent runtime emitting GenAI spans: - If a retry can change `genai.tool.call.id` or `genai.response.id` (i.e., the request body is regenerated), the retry **must** open a new span. Overwriting identity attributes on a live span is prohibited because it destroys the join key to provider-side billing and audit records. - If a retry is a byte-identical transport replay (same call id, same request hash), it **may** reuse the span, but `genai.usage.*` must be accumulated as a sum, never overwritten, and the span must carry an explicit `retry.count` attribute so downstream consumers know the counter is an aggregate. - Cost telemetry must be derived from `genai.usage.*` **at span-emit time**, not at span-end time, because span-end overwrite is precisely the mechanism that drops failed-attempt cost. The failure is bounded by a single guardrail: **a span's `genai.usage.*` attributes are write-once.** Any second write to a `genai.usage.*` key on the same span is a programming error that silently corrupts cost attribution. Enforce it at the SDK wrapper layer, not at the exporter, because the exporter sees only the final value. ## Operational Effect The downstream consequence is that **cost dashboards under-report by the retry amplification factor**, and the under-report is correlated with backend flakiness — meaning cost anomalies appear exactly when reliability degrades, masking the causal link. An agent that retries 3× on a bad day shows *lower* recorded token spend than on a good day, because more attempts were collapsed and dropped. Operators reading `genai.usage.input_tokens` see a stable or declining number while the provider invoice spikes. The trace-to-billing reconciliation gap (orphaned provider call ids, span count < provider request count) is the only reliable detector, and it requires joining on `genai.tool.call.id`, which is the very attribute the collapse overwrites. The architectural invariant to restore: **identity attributes and usage counters must never share a mutable span lifetime.** Emit physical attempts as immutable child spans; aggregate only at query time. ```python class SpanAttributeCollapseError(RuntimeError): """Raised when a retry reuses a live GenAI span and overwrites usage/identity attributes, violating the write-once invariant on genai.usage.* and destroying the provider join key.""" pass WRITE_ONCE_PREFIXES = ("genai.usage.", "genai.tool.call.id", "genai.response.id") class GenAISpanGuard: """Wraps a span; enforces write-once on usage counters and identity attributes.""" def __init__(self, span): self._span = span self._written = set() def set_attribute(self, key: str, value): if key.startswith(WRITE_ONCE_PREFIXES) and key in self._written: raise SpanAttributeCollapseError( f"attempted overwrite of write-once attribute {key!r} on span " f"{self._span.name!r}; a retry that changes {key!r} must open a new " f"child span, not reuse this one — otherwise failed-attempt token cost " f"is silently dropped and provider call ids are orphaned" ) self._written.add(key) self._span.set_attribute(key, value) def record_attempt(guard: GenAISpanGuard, call_id: str, input_tokens: int, output_tokens: int): # Retry attempts that regenerate the tool call MUST use a fresh span. # This function is only valid for the first attempt on a given span. if "genai.tool.call.id" in guard._written: raise SpanAttributeCollapseError( f"span already carries call id {guard._span.attributes.get('genai.tool.call.id')!r}; " f"refusing to record attempt {call_id!r} on the same span — open a child span" ) guard.set_attribute("genai.tool.call.id", call_id) guard.set_attribute("genai.usage.input_tokens", input_tokens) guard.set_attribute("genai.usage.output_tokens", output_tokens) ```