# What structural signals indicate token-accounting drift when OpenTelemetry GenAI span attributes are reconciled against a parent agent span under nested tool-call fan-out **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) with a parent agent span aggregating child tool-call and LLM-invocation spans, and that downstream reconcile `gen_ai.usage.input_tokens`/`output_tokens` from child spans into the parent. Does not apply to single-shot LLM calls with no child span fan-out, nor to runtimes that emit token usage only at the root span. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as **per-invocation** counters on the span that represents a single model call. They say nothing normative about how a *parent* agent span should aggregate children, nor about the fact that a single logical model turn in an agent loop can be split across a retry span, a streaming-resume span, and a tool-result re-invocation span — each carrying its own usage block. The distinction that matters operationally is between **billing-truth token counts** (what the provider charged, attributable to a logical turn) and **span-tree token sums** (what a naive `sum(child.usage)` yields). These diverge the moment the span tree is not a clean 1:1 partition of logical turns. The invariant that must hold — and that the semantic conventions do *not* enforce — is: *for every logical model invocation, the sum of `gen_ai.usage.*` across all spans that represent attempts of that invocation must equal exactly one attempt's worth of billed tokens, with retries and partial streams marked as non-additive.* ## What Was Observed In a production agent loop, a single user turn triggered a model call that returned HTTP 429 mid-stream after emitting 812 output tokens. The SDK retried the call under a new span (`gen_ai.request.attempt=2`), which succeeded with a full 2,041 output tokens. Both spans carried `gen_ai.usage.output_tokens` (812 and 2,041 respectively) and both were children of the same `invoke_agent` parent span. The parent's aggregation code did `sum(child.gen_ai.usage.output_tokens)` and reported 2,853 output tokens for a turn that was billed as 2,041 (the aborted stream was never billed for output beyond what was actually generated, but the retry re-generated the answer from scratch — the 812 aborted tokens were charged as input on the retry, not as output twice). Three structural signals marked the drift, and none of them are surfaced by the semantic conventions as first-class attributes: 1. **Attempt multiplicity without a logical-invocation key.** No `gen_ai.invocation.id` attribute exists in the conventions to tie attempt-1 and attempt-2 to the same billed unit. The only correlation is the parent span id, which conflates *distinct* logical invocations (e.g., a planning call and a synthesis call) with *retries of one* invocation. 2. **Partial-usage spans.** The 429 span reported `output_tokens=812` but had no terminal `finish_reasons` and a span status of `ERROR`. A span with usage attributes but non-OK status is a *partial* attempt whose tokens are not independently billable as output — they are folded into the retry's input. 3. **Missing `gen_ai.usage.cache_read_input_tokens` on the retry.** The retry re-sent the full prompt, but the provider's prompt cache meant only the delta was billed at full input rate. Child-span input tokens summed to 2× the prompt; the parent reported double the true input cost. The reconciliation job that compared span-tree sums to provider invoices flagged a 40% output overcount and a 100% input overcount on this turn class. The drift was silent in the trace UI (spans looked correct individually) and only appeared when summed. ## Condition of Validity The naive aggregation invariant (`parent.usage = Σ child.usage`) is valid **only if** all of the following hold: - Every child LLM-invocation span represents exactly one billed attempt with a terminal `finish_reasons` and OK status. - No logical invocation is represented by more than one span (no retries, no streaming-resume, no speculative-decoding partial spans). - Prompt-cache accounting is disabled or `cache_read_input_tokens` is subtracted from `input_tokens` consistently across all children. - Tool-call spans carry no `gen_ai.usage.*` attributes (they are not model calls) and are excluded from the sum. In an agent loop with tool fan-out and retry, at least one of these fails on essentially every non-trivial turn. The condition of validity is therefore *rarely met in production*, which is why the drift is systematic rather than incidental. ## Decision Boundary The boundary is whether the parent span's usage attributes are treated as **authoritative billing truth** or as **observability estimates**. If the runtime uses parent-span sums for cost attribution, quota enforcement, or budget cutoffs (a token-budget-exhaustion guard), the drift becomes a correctness bug: the agent will believe it has spent 2,853 output tokens when it spent 2,041, tripping budget guards early and — worse — the *input* overcount can trip a context-budget guard that aborts a turn that would have fit. Conversely, if parent usage is explicitly labeled `gen_ai.usage.estimated=true` and billing reads from provider-side ledgers, the drift is cosmetic. The decision boundary is crossed the moment any control loop (retry budget, context-window guard, cost ceiling) reads the parent aggregate. The guardrail: emit a `gen_ai.invocation.id` custom attribute (or reuse `gen_ai.request.attempt` plus a stable `gen_ai.conversation.id` + turn index) on every LLM-invocation span, mark partial attempts with `gen_ai.usage.partial=true`, and require the parent aggregator to sum **only** the final attempt per `invocation.id`, subtracting `cache_read_input_tokens` from input. Reject any parent aggregate where a child has `partial=true` and no sibling with the same `invocation.id` and OK status — that is an un-reconciled partial. ## Operational Effect Without the guardrail, three failure modes compound: 1. **Budget-guard premature abort.** Input overcount from retried prompts (cache not subtracted) inflates the parent's input-token total, causing the context-budget guard to abort turns that fit within the real window. Observed as "random" mid-conversation truncation on turns that follow a tool-heavy step. 2. **Cost-attribution skew.** Output overcount from retried streams attributes 40%+ phantom cost to specific agent roles, corrupting per-role cost dashboards and misdirecting optimization effort toward the wrong tool. 3. **Silent invoice mismatch.** The trace looks internally consistent (children sum to parent), so reconciliation against provider invoices is the only detector — and it lags by a billing cycle, long after the bad turns have been replayed. The structural signals that flag drift before invoice reconciliation: (a) a parent span whose child count exceeds its logical-invocation count, (b) any child with usage attributes and non-OK status, (c) any parent whose input-token sum exceeds the sum of distinct prompt lengths, (d) absence of `cache_read_input_tokens` on retry children. Emit a validation span or metric on these signals at aggregation time. ```python from dataclasses import dataclass, field class TokenAggregationDriftError(RuntimeError): """Raised when a parent agent span's aggregated gen_ai.usage attributes cannot be reconciled to a clean 1:1 partition of logical model invocations.""" @dataclass class LLMSpan: span_id: str parent_id: str invocation_id: str | None # None => conventions gave us no key attempt: int status_ok: bool finish_reasons: list[str] input_tokens: int output_tokens: int cache_read_input_tokens: int | None = None def aggregate_parent_usage(children: list[LLMSpan]) -> dict[str, int]: """Sum child usage into a parent agent span, enforcing the reconciliation invariant.""" by_invocation: dict[str, list[LLMSpan]] = {} unkeyed: list[LLMSpan] = [] for c in children: if c.invocation_id is None: unkeyed.append(c) else: by_invocation.setdefault(c.invocation_id, []).append(c) # Signal 1: attempt multiplicity without a logical-invocation key. if unkeyed and len(unkeyed) > 1: raise TokenAggregationDriftError( f"{len(unkeyed)} LLM spans lack gen_ai.invocation.id; cannot " f"distinguish retries from distinct invocations. Spans: " f"{[s.span_id for s in unkeyed]}" ) total_in = 0 total_out = 0 for inv_id, attempts in by_invocation.items(): # Signal 2: partial-usage span with non-OK status and no terminal finish reason. partials = [a for a in attempts if not a.status_ok or not a.finish_reasons] finals = [a for a in attempts if a.status_ok and a.finish_reasons] if partials and not finals: raise TokenAggregationDriftError( f"invocation {inv_id} has only partial attempts " f"{[p.span_id for p in partials]}; no billable final attempt." ) if len(finals) > 1: raise TokenAggregationDriftError( f"invocation {inv_id} has {len(finals)} terminal attempts; " f"logical invocation was double-billed or mis-keyed." ) final = finals[0] # Signal 3: retry without cache_read accounting inflates input. if final.attempt > 1 and final.cache_read_input_tokens is None: raise TokenAggregationDriftError( f"invocation {inv_id} retried (attempt={final.attempt}) but " f"cache_read_input_tokens is unset; input tokens will be " f"double-counted against the prompt." ) total_in += final.input_tokens - (final.cache_read_input_tokens or 0) total_out += final.output_tokens return {"input_tokens": total_in, "output_tokens": total_out} ```