# What structural signals indicate token-accounting drift when OpenTelemetry GenAI spans model multi-turn agent tool-call trees **Date of Record:** 2026 November 24 **Scope:** Applies to agents that emit OTel GenAI semantic-convention spans (`gen_ai.*`) across multi-turn, nested tool-call trees where a single logical turn fans out into child `execute_tool` and nested `chat` spans. Does not apply to single-shot inference calls with flat span hierarchies, nor to providers that report usage at the request level only without per-turn attribution. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of a *single* model invocation span. They deliberately do **not** define an aggregation rule across a span tree. This is the load-bearing gap: the convention specifies per-span truth but leaves tree-level token accounting undefined. Operators therefore infer the turn's cost by summing spans, and that inference is wrong in a specific, reproducible way. The distinction that matters is between **span-local usage** (what the provider actually billed for that one HTTP round-trip) and **turn-attributed usage** (the tokens the agent's reasoning loop consumed to produce one user-visible answer). In a multi-turn tool-call tree these diverge because every tool result is re-injected into a *new* `chat` span whose `input_tokens` re-counts the entire accumulated conversation, including all prior tool outputs and the system prompt. Summing child spans double-counts the prefix on every hop. ## What Was Observed A three-hop tool-call turn (plan → search → synthesize) produced the following span tree: ``` chat (turn root) input=812 output=140 ├── execute_tool search (no usage attrs) ├── chat (continuation 1) input=1,684 output=210 │ └── execute_tool fetch (no usage attrs) └── chat (continuation 2) input=2,910 output=390 ``` Naive summation yields `input = 5,406`, `output = 740`. The provider invoice for the turn showed `input = 2,910` (the final, longest context is the only distinct prefix the model was billed for under prefix caching) and `output = 740`. The tree-sum overcounted input by 86%. The structural signal is the **monotonically increasing `input_tokens` across sibling `chat` spans within one trace**, each approximately equal to the prior span's `input + output + tool_result_size`. That growth curve is the fingerprint of context re-injection, and it is the only reliable indicator that summation is invalid. When `input_tokens` is flat across continuations (stateless re-prompting with no history), summation *is* correct — the same code path produces opposite accounting, and the span tree does not announce which regime it is in. A second signal: `execute_tool` spans carry `gen_ai.operation.name = "execute_tool"` but no `gen_ai.usage.*` attributes at all. Any aggregator that joins on `gen_ai.usage.input_tokens` silently drops tool spans, so tool-side token cost (the tool's own LLM sub-calls, if any) vanishes from the turn total. The absence of the attribute is indistinguishable from a zero value in most query languages. ## Condition of Validity Tree-summation of `gen_ai.usage.*` is valid **only** when all three hold: 1. Every `chat` span in the trace has a *disjoint* input prefix — i.e., `input_tokens` does not grow monotonically along the continuation chain. This is the stateless regime. 2. No `chat` span is a continuation of a sibling, detectable by checking that `input_tokens[i] < input_tokens[i-1] + output_tokens[i-1] + tool_result_tokens[i-1]` fails for at least one pair, or that a `gen_ai.request.is_streaming` / cache attribute marks prefix reuse. 3. Tool spans either carry their own usage or are known to make no model calls. When condition 1 fails — the common case for agentic loops — the correct turn-level input accounting is `max(input_tokens)` over the continuation chain *plus* the final `output_tokens`, not the sum. This is the prefix-caching lower bound, and it matches provider billing only when the provider bills distinct prefixes. If the provider bills per-request without caching, the sum *is* the invoice and the max is an underestimate. **The span tree alone cannot distinguish these two billing regimes** — the convention does not carry a `gen_ai.usage.cache_read_tokens` attribute in all SDK versions, so the aggregator must be told which regime it is in out-of-band. ## Decision Boundary The boundary is crossed at the moment an agent emits a *continuation* `chat` span whose `input_tokens` exceeds the parent's `input_tokens + output_tokens` by more than the tool result payload. Below that threshold, the span is a fresh independent call and summation is safe. Above it, the span is a continuation and summation double-counts. Operationally: compute `delta = input_tokens[child] - (input_tokens[parent] + output_tokens[parent])`. If `delta` is within the tool-result token estimate, treat as continuation and switch the aggregator to max-plus-final-output. If `delta` is large and negative or zero, treat as independent and sum. If `delta` is positive but unexplained by tool payload, the span tree is *inconsistent* — a continuation span whose prefix does not match the parent's accumulated context — and this indicates either a dropped span in the export pipeline or a context-truncation event mid-turn. Both are integrity failures that must raise, not silently average. ## Operational Effect An aggregator that sums without this check produces token dashboards that overcount agentic turns by 50–200% while undercounting stateless turns by the tool-span gap. The two errors partially cancel in mixed workloads, which is why the drift survives review: aggregate cost looks plausible while per-turn attribution is wrong in both directions. The fix is to make the aggregator regime-aware, keyed on the continuation delta, and to fail loudly on inconsistent trees rather than emit a plausible number. ```python from dataclasses import dataclass from typing import Optional class SpanTreeAccountingError(RuntimeError): """Raised when a GenAI span tree cannot be reconciled to a single billing regime.""" pass @dataclass class ChatSpan: span_id: str parent_id: Optional[str] input_tokens: int output_tokens: int tool_result_tokens: int = 0 # tokens of tool output injected before this span def attribute_turn(chain: list[ChatSpan], provider_caches_prefix: bool) -> dict: """ chain: continuation chat spans of one turn, ordered root -> leaf. Returns turn-level token accounting under the detected regime. """ if not chain: raise SpanTreeAccountingError("empty continuation chain") root = chain[0] regime = "stateless" for prev, cur in zip(chain, chain[1:]): expected_floor = prev.input_tokens + prev.output_tokens delta = cur.input_tokens - expected_floor # Continuation: child prefix re-counts parent context plus tool output. if delta >= cur.tool_result_tokens and cur.input_tokens > prev.input_tokens: regime = "continuation" elif delta < -prev.output_tokens: raise SpanTreeAccountingError( f"inconsistent tree: span {cur.span_id} input {cur.input_tokens} " f"is smaller than parent floor {expected_floor} by {-delta}; " f"possible dropped span or mid-turn truncation" ) elif delta > cur.tool_result_tokens + 64: # unexplained growth beyond payload raise SpanTreeAccountingError( f"inconsistent tree: span {cur.span_id} grew {delta} tokens " f"but tool payload only accounts for {cur.tool_result_tokens}" ) total_output = sum(s.output_tokens for s in chain) if regime == "stateless": total_input = sum(s.input_tokens for s in chain) else: # Continuation regime: distinct prefix is the largest context. total_input = max(s.input_tokens for s in chain) if not provider_caches_prefix: # Provider bills every request; max undercounts the invoice. total_input = sum(s.input_tokens for s in chain) return { "regime": regime, "input_tokens": total_input, "output_tokens": total_output, "billing_caveat": ( "max-prefix lower bound; reconcile against provider cache_read_tokens" if regime == "continuation" and provider_caches_prefix else None ), } ```