# What structural signals indicate OTel GenAI span token accounting has silently decoupled from billed usage in agent tool-call loops **Date of Record:** 2026 December 2 **Scope:** Applies to agents that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) around LLM invocations and tool calls, where token counts are aggregated from span attributes for cost attribution or budget enforcement. Does not apply to single-shot inference with no tool-call loop, nor to providers that return authoritative usage objects on every response. ## Core Distinction A GenAI span carries two conceptually distinct token facts: the *per-invocation usage* the provider reports on a single response (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`), and the *aggregate* an agent's parent span or collector derives by summing child spans. The semantic conventions define the per-span attributes precisely but say nothing normative about how a multi-turn agent loop—where one logical "agent run" spans N model calls and M tool calls—should roll up. The boundary failure is this: when an agent loop retries a model call, re-executes a tool after a schema mismatch, or fans out to parallel sub-agents, the **sum of emitted child-span token attributes diverges from the provider's billed total**, and nothing in the span structure flags the divergence. The trace looks internally consistent. Every span has plausible token counts. The aggregate is simply wrong, and it is wrong in a direction that under-reports. The non-obvious part: the divergence is not random noise. It is *structurally correlated* with retry and fan-out topology, so it compounds silently and monotonically as loop depth increases. ## What Was Observed An agent executing a 9-step plan with tool calls emitted a trace with the following shape: - 1 root `invoke_agent` span - 14 `chat` child spans (9 nominal steps + 5 retries after `finish_reason=length` truncations) - 11 `execute_tool` child spans (9 nominal + 2 re-executions after tool output failed schema validation) Each `chat` span correctly carried `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` for that individual HTTP response. The collector summed them: 412,880 input tokens, 61,300 output tokens. The provider's billing console for the same window reported 588,410 input tokens, 61,300 output tokens. Output tokens matched exactly. Input tokens were under-reported by ~30%. The gap localized to a structural cause: **retried `chat` spans re-sent the full accumulated context, but the retry's input tokens were attributed to the retry span while the original failed span's input tokens were also counted**—so the sum double-counted the *pre-retry* context but the provider billed the *full re-sent* context on each retry, and the truncated-then-retried calls had grown their context between attempts. The per-span numbers were each individually truthful; the roll-up was not a meaningful quantity. A second, sharper signal appeared in the tool-call layer. The two re-executed tools emitted `execute_tool` spans with `gen_ai.tool.name` identical to the first attempt. Downstream cost attribution keyed on tool name and treated the duplicate spans as idempotent—deduplicating them—while the underlying tool calls had both executed and both incurred side effects (two writes, two API charges). The span *structure* said "same tool, same name, probably a retry, dedupe it." The execution reality said "two distinct effects." The semantic conventions have no attribute distinguishing a retry from a legitimate repeated call. The invariant that failed: **span-level token attributes are per-invocation facts, not per-logical-step facts, and the trace topology does not encode which is which.** A consumer of the trace cannot reconstruct billed usage without out-of-band knowledge of the retry policy. ## Condition of Validity The aggregation is only sound when all of the following hold: 1. Every model invocation emits exactly one `chat` span, and no invocation is retried at a layer below the span emitter (e.g., SDK-level retries that never surface as spans). 2. Tool calls are idempotent or carry an explicit idempotency key that the span records, so duplicate `execute_tool` spans can be safely deduplicated. 3. The roll-up consumer treats the root `invoke_agent` span's token attributes as authoritative *only if* the agent explicitly sets them from the provider's aggregate usage, not by summing children. 4. Fan-out sub-agents propagate a shared `gen_ai.conversation.id` or equivalent correlation attribute so parallel branches are not mistaken for sequential steps. When any of these is violated—and in real agent loops at least one usually is—the aggregate is a lower bound, not a measurement. The failure is silent because each span validates against the schema; the semantic conventions have no consistency check across spans. ## Decision Boundary The decision is where to place the authoritative token count. Two viable architectures, and the boundary between them: - **Span-authoritative:** the agent runtime, at the end of a logical run, reads the provider's final usage object (or an accumulator it maintains across the loop) and writes it to the root span as `gen_ai.usage.*`. Child spans remain per-invocation diagnostics. Consumers read only the root. This is correct but requires the runtime to hold loop-level state and to know when a run ends—fragile under checkpoint/resume, where a resumed run may not have the pre-checkpoint accumulator. - **Collector-authoritative:** the collector reconstructs usage from child spans, but only after applying a retry-aware reduction: group `chat` spans by `gen_ai.conversation.id` + step index, take the *last* attempt's input tokens plus the sum of all attempts' output tokens (since output from a truncated attempt is still billed), and never sum input tokens across attempts of the same step. The boundary: if the agent runtime cannot guarantee it knows run termination (streaming, crash-resume, long-running loops), span-authoritative is unsafe and the collector must do retry-aware reduction. If the collector cannot see retry linkage (missing step-index or attempt attributes), *neither* is sound and the correct action is to refuse to emit an aggregate rather than emit a wrong one. Emitting a plausible-but-wrong aggregate is worse than emitting none, because downstream budget enforcement trusts it. ## Operational Effect The practical consequence is that token-budget enforcement built on naive span summation under-fires. An agent configured to halt at a 500K-token budget will, under the observed topology, believe it has consumed ~412K when the provider has billed ~588K—it sails past the budget and only discovers the overrun on the next billing cycle. The guardrail is a hard invariant at the reduction layer: **input tokens are never summed across attempts of the same logical step; only the terminal attempt's input count is authoritative, while output tokens are summed across all attempts.** Enforce it by rejecting any aggregate whose per-step attempt count exceeds a configured retry ceiling without an explicit `gen_ai.request.attempt` attribute, and by refusing to dedupe `execute_tool` spans unless an idempotency key attribute is present and equal. ```python from dataclasses import dataclass, field from typing import Iterable class TokenAggregationError(RuntimeError): """Raised when span-derived token totals cannot be soundly reduced.""" @dataclass class ChatSpan: conversation_id: str step_index: int attempt: int | None # None means emitter did not record retry linkage input_tokens: int output_tokens: int finish_reason: str @dataclass class ToolSpan: tool_name: str idempotency_key: str | None @dataclass class Reduction: input_tokens: int = 0 output_tokens: int = 0 steps: int = 0 notes: list[str] = field(default_factory=list) def reduce_usage( chat_spans: Iterable[ChatSpan], tool_spans: Iterable[ToolSpan], retry_ceiling: int = 3, ) -> Reduction: by_step: dict[tuple[str, int], list[ChatSpan]] = {} for span in chat_spans: if span.attempt is None: raise TokenAggregationError( f"chat span for conversation={span.conversation_id} " f"step={span.step_index} lacks gen_ai.request.attempt; " "cannot distinguish retry from sequential step, refusing to aggregate" ) by_step.setdefault((span.conversation_id, span.step_index), []).append(span) result = Reduction() for (conv, step), attempts in by_step.items(): attempts.sort(key=lambda s: s.attempt) if len(attempts) > retry_ceiling: raise TokenAggregationError( f"step {step} of conversation {conv} has {len(attempts)} attempts, " f"exceeds retry ceiling {retry_ceiling}; retry linkage likely broken" ) # Input tokens: only the terminal attempt's context is billed as the # step's input; earlier attempts' inputs were re-sent, not additive. terminal = attempts[-1] result.input_tokens += terminal.input_tokens # Output tokens: every attempt produced billed output, including # truncated attempts whose partial output still counts. result.output_tokens += sum(a.output_tokens for a in attempts) result.steps += 1 if len(attempts) > 1: result.notes.append( f"step {step}: {len(attempts)} attempts, input counted from " f"attempt {terminal.attempt} only" ) seen_keys: set[str] = set() for tool in tool_spans: if tool.idempotency_key is None: result.notes.append( f"tool {tool.tool_name} lacks idempotency key; not deduped" ) elif tool.idempotency_key in seen_keys: result.notes.append( f"tool {tool.tool_name} key={tool.idempotency_key} deduped" ) else: seen_keys.add(tool.idempotency_key) return result ```