# What structural signals indicate span-boundary token accounting drift in OpenTelemetry GenAI multi-turn agent traces **Date of Record:** 2026 December 3 **Scope:** Applies to agents whose multi-turn execution is instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes, `gen_ai.chat`/`gen_ai.tool`/`gen_ai.agent` span kinds) where token usage is aggregated across a parent agent span and reconciled against per-turn child chat spans. Does not cover single-shot inference spans, streaming partial-token accounting, or billing reconciliation against provider invoices. ## Core Distinction The failure is not "missing token counts." It is a *structural* mismatch between where tokens are attributed in the span tree and where they are actually consumed by the model. OpenTelemetry GenAI conventions expect `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` on the span that *terminated* the model call—typically the `gen_ai.chat` child span. Multi-turn agents, however, accumulate context: turn *N*'s input tokens are not turn *N*'s prompt alone, but the entire replayed history plus tool results. When the agent runtime emits a parent `gen_ai.agent` span that sums child `input_tokens`, it double-counts every prior turn, because each child's `input_tokens` already contains the replayed prefix. The parent sum grows quadratically in turn count while the true billed input grows linearly. The invariant that must hold: **for a linear conversation of T turns, `sum(child.gen_ai.usage.input_tokens) - sum(child.replayed_prefix_tokens) == true_billed_input_tokens`.** The convention has no first-class `replayed_prefix_tokens` attribute, so the subtraction is invisible unless the instrumentation explicitly records it. Absent that, the parent span is not a ledger—it is a monotonic overcount. ## What Was Observed A four-turn research agent (plan → search → fetch → synthesize) instrumented per GenAI conventions produced the following parent `gen_ai.agent` span attributes after the run: - `gen_ai.usage.input_tokens = 41,832` - `gen_ai.usage.output_tokens = 2,104` The provider's per-turn usage records for the same run summed to `input = 14,290`, `output = 2,104`. Output reconciled exactly; input was off by a factor of ~2.93. Decomposing the child spans: | Turn | child input_tokens | replayed prefix (est.) | net new | |------|-------------------|------------------------|---------| | 1 (plan) | 1,180 | 0 | 1,180 | | 2 (search) | 3,410 | 1,180 + 214 out | 2,016 | | 3 (fetch) | 9,870 | 3,410 + 640 out | 5,820 | | 4 (synth) | 27,372 | 9,870 + 1,250 out | 16,252 | The parent's 41,832 equals the naive sum of child `input_tokens` (1,180 + 3,410 + 9,870 + 27,372 = 41,832). The true billed input (14,290) equals the sum of *net new* tokens per turn. The gap is the replayed prefix, which no child span declared. Two structural signals made this diagnosable without provider data: 1. **Quadratic growth of parent input vs. linear turn count.** If parent `input_tokens / turn_count` rises monotonically with turn index, replayed prefixes are being folded into the parent. A correctly attributed parent has roughly flat per-turn input. 2. **Child `input_tokens` strictly increasing across a linear conversation.** In a single-threaded agent, each turn's input includes all prior turns. A child span whose `input_tokens` is *less* than the previous sibling's is a signal of context truncation or a branch—not normal accumulation. ## Condition of Validity The overcount is *not* a bug in all cases. It is a correct, if unhelpful, aggregation under three conditions: - The agent runtime treats `gen_ai.usage.*` as "tokens the model saw this call," which is the literal semantic of the attribute. Under that reading, summing is arithmetically correct but operationally useless for cost. - The trace has no `gen_ai.conversation.id` or equivalent to let a consumer reconstruct the linear prefix chain. Without it, the replayed prefix cannot be subtracted. - No child span carries a `replayed_prefix_tokens` (or `cache_read_input_tokens`, which in Anthropic-style APIs *is* the replayed prefix when prompt caching is on) attribute. The overcount *becomes* a defect the moment any downstream consumer—cost dashboards, budget guards, context-window saturation alarms—treats the parent sum as billed input. That is the boundary: the attribute is valid as a per-call descriptor and invalid as an aggregate ledger. The convention does not distinguish these roles. ## Decision Boundary The guardrail is a **span-role declaration**: every `gen_ai.chat` span that replays a prior turn's context MUST emit either `gen_ai.usage.cache_read_input_tokens` (if the provider reports cached prefix) or an explicit `gen_ai.usage.replayed_prefix_tokens` custom attribute, and the parent `gen_ai.agent` span MUST NOT emit `gen_ai.usage.input_tokens` as a sum. Instead it emits `gen_ai.usage.billed_input_tokens` computed as `sum(child.input_tokens - child.replayed_prefix_tokens)`. The decision rule for an auditor reading a trace: - If parent has `input_tokens` and no child has `replayed_prefix_tokens` or `cache_read_input_tokens`, **reject the parent as a cost signal**. Treat it as a token-throughput signal only. - If child `input_tokens` is non-monotonic across a linear `gen_ai.conversation.id` chain, **flag context truncation**—the agent silently dropped history, and both cost and reasoning fidelity are suspect. - If `parent.input_tokens > sum(child.input_tokens)`, the parent is over-attributing (e.g., counting system prompt twice); if `<`, a child span is missing entirely. ## Operational Effect Downstream, the unguarded parent sum inflates budget-guard triggers by ~3x on four-turn runs and worse on longer ones, causing premature agent termination mid-task—a token-budget exhaustion that never actually occurred at the provider. It also corrupts context-window saturation alarms: the parent reports 41k tokens when the model's *actual* context at turn 4 was 27k, so an agent tuned to a 32k window either fires spuriously or, worse, a real saturation at turn 5 is masked because the parent's quadratic inflation has already tripped a higher threshold and been dismissed as "the known overcount." The fix is not arithmetic; it is declaring span role at emission time so the parent span is a ledger, not a sum. ```python class TokenAttributionError(RuntimeError): pass def reconcile_agent_span(agent_span: dict, chat_spans: list[dict]) -> dict: """Reconcile a gen_ai.agent span's token usage against its gen_ai.chat children. Enforces: parent.input_tokens must equal sum(child.input_tokens - replayed_prefix). """ if not chat_spans: raise TokenAttributionError("agent span has no chat children; cannot reconcile") billed_input = 0 for i, child in enumerate(chat_spans): inp = child.get("gen_ai.usage.input_tokens") if inp is None: raise TokenAttributionError(f"child {i} missing input_tokens") prefix = child.get("gen_ai.usage.replayed_prefix_tokens", child.get("gen_ai.usage.cache_read_input_tokens", 0)) if prefix > inp: raise TokenAttributionError( f"child {i}: replayed_prefix {prefix} exceeds input {inp}") billed_input += inp - prefix parent_input = agent_span.get("gen_ai.usage.input_tokens") if parent_input is None: raise TokenAttributionError("agent span missing input_tokens") # Structural signal: parent equals naive sum => replayed prefixes folded in. naive_sum = sum(c["gen_ai.usage.input_tokens"] for c in chat_spans) if parent_input == naive_sum and billed_input != naive_sum: raise TokenAttributionError( f"parent input {parent_input} equals naive child sum but billed is " f"{billed_input}; replayed prefixes not declared") if parent_input != billed_input: raise TokenAttributionError( f"parent input {parent_input} != billed input {billed_input}") return {"billed_input_tokens": billed_input, "billed_output_tokens": sum(c.get("gen_ai.usage.output_tokens", 0) for c in chat_spans)} ```