# Which invariants prevent OpenTelemetry GenAI tool-call spans from double-counting tokens when a retried tool call is re-emitted under a new span ID **Date of Record:** 2026 December 4 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans per LLM invocation and per tool call, where retries, hedged calls, or provider-side failover cause the same logical tool invocation to produce more than one span. Does not cover single-attempt, non-retried tool loops or pure model-side tokenization disputes. ## Core Distinction The naive reading of the GenAI semantic conventions treats `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as properties of a *span*. They are not. They are properties of a *billing event* that the span merely references. When a tool call is retried—whether because the provider returned a 5xx, because a hedge raced ahead, or because the agent framework's idempotency layer re-issued the call under failover—the runtime emits a second span with a fresh `span_id`, fresh `gen_ai.response.id`, and a fresh set of usage attributes. A downstream cost aggregator that sums `gen_ai.usage.*` across spans will silently double-bill: the logical call cost once, the telemetry ledger twice. The invariant that must hold is **token-attribution uniqueness**: for any logical tool invocation identified by a stable business key (the tool call's `tool_call_id` from the originating assistant message, not the transport-level request ID), the sum of `gen_ai.usage.*` across all spans sharing that key must equal the sum actually billed by the provider. Spans are the *carrier*, not the *unit of account*. Conflating them is the failure. This is non-obvious because the spec's attribute names are per-span and the natural aggregation (`sum by gen_ai.tool.name`) is exactly the wrong one. Nothing in the span schema forbids two spans with identical `gen_ai.tool.call.id` and different `span_id`; the schema is silent on cardinality, and silence reads as permission. ## What Was Observed A research-agent deployment made ~14,000 tool calls/day across a retry-wrapped HTTP client. The client retried on 429/502/503 with exponential backoff, up to three attempts. Each attempt was instrumented independently: a new span, a new `gen_ai.response.id`, and—critically—a new `gen_ai.usage.input_tokens` reflecting the full prompt re-sent on retry. The billing ledger from the provider counted only the successful attempt (failed attempts at the gateway were not billed, but the agent's *local* token accounting counted the prompt tokens it had constructed each time). The daily cost dashboard diverged from the invoice by 11–19% on retry-heavy days. The divergence was not random: it clustered on the `gen_ai.tool.name = "web_search"` and `"code_exec"` tools, whose upstream providers had the worst 429 rates. A spot check of one trace showed three spans for a single `tool_call_id`, with `gen_ai.usage.input_tokens` of 1,842, 1,842, and 1,844 (the last differing because the retry appended a "previous attempt timed out" note to the prompt). Summing the spans gave 5,528 input tokens for a call the provider billed at 1,844. The telemetry was internally consistent—each span was a faithful record of what that attempt sent—and collectively wrong as a cost signal. The failure was masked for weeks because the retry wrapper also emitted a parent span with a *single* usage attribute set (the successful attempt only), and the cost pipeline had been built against the parent. When a refactor flattened the hierarchy to make traces cheaper to store, the aggregator switched to summing leaf spans and the divergence surfaced. The spans had always been double-counting; the *query* changed, not the data. ## Condition of Validity The uniqueness invariant holds only under a specific precondition that is easy to lose: **the retry wrapper must propagate the originating `tool_call_id` unchanged across attempts, and must not mint a new one.** In the observed deployment, the wrapper did propagate it—`tool_call_id` came from the assistant message and was threaded through as a constant—which is why a correct aggregator *could* have deduplicated. Had the wrapper regenerated the ID per attempt (a common pattern when the wrapper treats each attempt as an independent logical call), no downstream consumer could reconstruct the grouping, and the invariant would be unrecoverable from telemetry alone. Two further conditions bound validity. First, the provider must bill per *successful* attempt, not per attempt; providers that bill for prompt tokens on failed requests (some do, on 4xx after the prompt is parsed) break the equality in the other direction—telemetry would *under*-count. Second, hedged calls (two attempts in flight simultaneously, first to succeed wins) require the losing span to be marked `gen_ai.tool.call.hedged = true` and excluded from billing sums; without that attribute the two spans are indistinguishable from a sequential retry, and the aggregator cannot know which to drop. The spec does not define this attribute; it is a local extension and must be documented as such or it will be lost on schema upgrade. ## Decision Boundary The boundary is: **does the consumer need per-attempt token counts (for latency/cost attribution within a retry) or per-logical-call token counts (for billing)?** These are different questions with different correct answers over the same spans. For per-attempt analysis—diagnosing whether retries are expensive—summing spans is correct, and the retry overhead *is* the signal. For billing, the aggregator must group by `gen_ai.tool.call.id` and take the usage of the *terminal* span (the one with `gen_ai.tool.call.status = "success"`, or the last attempt if all failed), not the sum. The decision must be made at query time and encoded in the aggregation key, because the same span set serves both. A pipeline that hardcodes one aggregation and calls it "cost" will be wrong for the other consumer half the time, and the wrongness will be invisible until an invoice reconciles. The guardrail: emit a derived `gen_ai.tool.call.attempt` integer (1-indexed) and `gen_ai.tool.call.terminal` boolean on every tool span. With those two attributes, any consumer can reconstruct both views without knowing the retry wrapper's internals. Without them, the grouping is a convention held in tribal knowledge, and the next refactor breaks it silently—exactly as it did here. ## Operational Effect After adding `attempt` and `terminal`, the cost pipeline was rewritten to `sum(usage) where terminal = true group by tool_call_id`, and the divergence closed to under 0.3% (residual from provider-side rounding). The per-attempt view was retained for a new dashboard showing retry overhead as a first-class cost line—which revealed that `web_search` retries alone accounted for 6% of monthly spend, a number previously invisible because it had been smeared into the double-count. The deeper effect was architectural: token accounting moved from "sum the spans" to "resolve the billing event, then read its usage." That inversion is the invariant. Spans are evidence; the billing event is the fact. Any agent runtime that emits GenAI spans without a stable logical-call key and a terminal marker is accumulating a ledger that reconciles only by luck. ```python class TokenAttributionError(RuntimeError): """Raised when tool-call spans cannot be reduced to a unique billing event.""" pass def aggregate_tool_tokens(spans: list[dict]) -> dict[str, int]: """Reduce per-attempt GenAI tool spans to per-logical-call token totals. Invariant: for each gen_ai.tool.call.id, exactly one span must carry gen_ai.tool.call.terminal == True. Summing all spans double-counts retried attempts whose prompts were re-sent. """ by_call: dict[str, list[dict]] = {} for span in spans: call_id = span.get("gen_ai.tool.call.id") if not call_id: raise TokenAttributionError( f"span {span.get('span_id')} missing gen_ai.tool.call.id; " "cannot attribute tokens to a logical call" ) by_call.setdefault(call_id, []).append(span) totals: dict[str, int] = {} for call_id, attempts in by_call.items(): terminals = [s for s in attempts if s.get("gen_ai.tool.call.terminal") is True] if len(terminals) != 1: raise TokenAttributionError( f"call {call_id}: expected exactly 1 terminal span, " f"found {len(terminals)} across {len(attempts)} attempts" ) t = terminals[0] totals[call_id] = ( int(t.get("gen_ai.usage.input_tokens", 0)) + int(t.get("gen_ai.usage.output_tokens", 0)) ) return totals ```