# Which invariants prevent gen_ai.* span attributes from silently misattributing token usage across retried tool-call turns **Date of Record:** 2026 November 20 **Scope:** Applies to agents that emit OpenTelemetry `gen_ai.*` spans per LLM call and per tool invocation, where retries, streaming, or provider failover can cause a single logical turn to produce multiple spans. Does not cover pure metric-only pipelines or providers that do not emit usage on the final chunk of a stream. ## Core Distinction A `gen_ai.*` span is a *per-attempt* record, but token accounting, cost attribution, and tool-call lineage are *per-logical-turn* concerns. The semantic conventions describe attribute names (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) but do not, on their own, define an aggregation invariant. The boundary failure is that a retried or failed-over attempt emits a span whose usage attributes are individually correct yet collectively double-counted or orphaned, because no invariant binds attempt spans to a single turn identity. The distinction that matters: *correctness of a span* is not *correctness of the sum of spans*. ## What Was Observed An agent loop issued a tool-calling turn against a primary provider. The first attempt streamed 1,842 output tokens before the connection reset mid-tool-call-argument. The retry against a secondary provider succeeded and emitted `gen_ai.usage.output_tokens = 2,010`. Both spans carried the same `gen_ai.tool.name = "search_docs"` and a *newly generated* `gen_ai.tool.call.id` on the retry (the SDK minted a fresh UUID because the original call never completed). The trace showed: - Span A (attempt 1): `gen_ai.request.model = "model-a"`, output 1,842, status `ERROR`, no `gen_ai.tool.call.id` finalized. - Span B (attempt 2): `gen_ai.request.model = "model-b"`, output 2,010, status `OK`, `gen_ai.tool.call.id = "call_9f…"`. The downstream cost aggregator summed `output_tokens` across all spans with a `gen_ai.tool.name` attribute and reported 3,852 tokens for a turn that logically consumed ~2,010 billable output tokens plus 1,842 *discarded* tokens that were still billed by the primary provider but never produced a usable tool call. Two invariants were violated simultaneously: (1) the sum of per-attempt usage did not equal the turn's cost, and (2) the tool-call ID did not survive the retry, so the successful tool result could not be joined back to the attempt that originated the intent. A second, subtler case: during streaming, the provider emitted usage only on the terminal chunk. A mid-stream client-side timeout caused the SDK to close the span *before* the terminal chunk arrived, so `gen_ai.usage.output_tokens` was absent. The aggregator treated absence as zero, undercounting by the full streamed length. The span was `OK`-status because the client cancelled cleanly. ## Condition of Validity The per-attempt span model is only sound for accounting when three conditions hold jointly: 1. **Turn identity is explicit and stable across attempts.** A `gen_ai.conversation.id` (or a custom `turn.id`) must be set by the caller, not the SDK, and must be identical on every attempt span for the same logical turn. SDK-generated IDs are per-attempt and cannot serve this role. 2. **Usage presence is distinguished from usage zero.** `gen_ai.usage.*` absent means *unknown*, not *zero*. Any aggregator that coerces missing to 0 is invalid the moment streaming or cancellation is possible. 3. **Tool-call identity is minted before the attempt, not after success.** `gen_ai.tool.call.id` must be assigned by the orchestrator at intent time so a retry reuses it; otherwise the successful result is an orphan relative to the failed attempt's lineage. When any of these fails, the trace is still *individually* valid but the aggregate is not. The convention does not enforce these; the emitter must. ## Decision Boundary The boundary is whether a given span represents a *billable attempt* or a *logical outcome*. Concretely: - If the provider charges for tokens streamed before a failure (most do), the failed attempt span **must** retain its usage attributes and **must** be tagged with a turn ID — it is a billable attempt, and dropping or zeroing it undercounts cost. - If the provider does not charge for aborted attempts, the attempt span should carry `gen_ai.usage.*` absent (unknown) plus an explicit `attempt.billed = false`, never `0`. - A retry span **must not** be summed with its predecessor under the same turn ID unless the aggregator is explicitly computing *attempt cost*, not *turn cost*. Two aggregations are legitimate and must be kept separate: `sum_by_turn(billed_attempts)` for cost, and `last_ok_by_turn` for outcome attribution. - Tool-call joins must key on the orchestrator-minted ID, and a retry that reuses that ID is the *same* logical call; a retry that mints a new ID is a *new* call and must be linked via `gen_ai.tool.call.parent_id` (or turn ID) or the lineage is broken. ## Operational Effect Without these invariants, three failures propagate silently: cost dashboards over- or under-report by the retry multiplier; tool-result joins drop the successful result because its `call.id` never appeared on the originating attempt; and latency SLOs computed from span durations double-count the failed attempt's wall-clock. The fix is cheap and must live in the emitter: mint turn and tool-call IDs at intent time, never coerce absent usage to zero, and tag every span with `attempt.index` and `attempt.billed` so downstream aggregation can choose turn-cost or attempt-cost semantics explicitly. The convention gives you the attribute names; it does not give you the aggregation contract, and the gap between the two is where the accounting drifts. ```python from dataclasses import dataclass, field from typing import Optional class GenAiUsageInvariantError(RuntimeError): """Raised when gen_ai.* span attributes violate the turn-accounting invariant.""" @dataclass class GenAiSpan: turn_id: Optional[str] attempt_index: int model: str status: str # "OK" | "ERROR" input_tokens: Optional[int] # None == unknown, never coerce to 0 output_tokens: Optional[int] tool_name: Optional[str] = None tool_call_id: Optional[str] = None attempt_billed: Optional[bool] = None def aggregate_turn_cost(spans: list[GenAiSpan]) -> int: if not spans: return 0 turn_ids = {s.turn_id for s in spans} if None in turn_ids or len(turn_ids) != 1: raise GenAiUsageInvariantError( f"turn_id must be set and identical across attempts; got {turn_ids}" ) total = 0 for s in spans: if s.status == "OK" and s.output_tokens is None: raise GenAiUsageInvariantError( f"OK span on turn {s.turn_id} attempt {s.attempt_index} " f"has unknown output_tokens; cannot aggregate cost" ) if s.status == "ERROR" and s.attempt_billed is None: raise GenAiUsageInvariantError( f"failed attempt {s.attempt_index} on turn {s.turn_id} " f"lacks attempt.billed; billed-vs-aborted is undecidable" ) if s.attempt_billed is False: continue # unknown usage on a billed attempt is a hard stop, not a zero if s.output_tokens is None: raise GenAiUsageInvariantError( f"billed attempt {s.attempt_index} on turn {s.turn_id} " f"missing gen_ai.usage.output_tokens" ) total += s.output_tokens return total def join_tool_result(spans: list[GenAiSpan], call_id: str) -> GenAiSpan: matches = [s for s in spans if s.tool_call_id == call_id] if not matches: raise GenAiUsageInvariantError( f"tool result call_id={call_id} has no originating attempt span; " f"retry likely minted a fresh id instead of reusing intent-time id" ) ok = [s for s in matches if s.status == "OK"] if len(ok) != 1: raise GenAiUsageInvariantError( f"expected exactly one OK attempt for call_id={call_id}, got {len(ok)}" ) return ok[0] ```