# Which invariants prevent double-counted token usage when OTel GenAI spans nest across tool-call boundaries **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that emit OpenTelemetry `gen_ai.*` spans for LLM invocations and tool executions, where a parent agent span aggregates child `chat` and `execute_tool` spans and where token accounting is derived from span attributes rather than from provider billing APIs. Does not apply to single-shot inference with no tool loop, nor to runtimes that read usage exclusively from the provider's response object at the top level. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of an *inference* span (`gen_ai.operation.name = chat`). They deliberately do not define an aggregation rule for a parent span that wraps a multi-turn agent loop. The distinction that matters operationally is between **summing child span attributes** and **propagating the provider-reported usage of the enclosing request**. These two numbers diverge the moment a single logical agent task re-enters the model after a tool call, because the second inference's input tokens already contain the first inference's output tokens plus the tool result — the context is cumulative, but the span tree is a forest of sibling `chat` spans, not a chain of deltas. An aggregator that sums `gen_ai.usage.input_tokens` across all child `chat` spans of an `invoke_agent` span therefore reports a figure that is *not* the cost of the task. It is the sum of prefix-inclusive prompt sizes. For an N-step ReAct loop with roughly constant context growth, the reported input tokens scale as O(N²) in the number of turns while the actual billed input tokens scale as O(N). The error is silent, monotonic, and grows with the exact behavior (long tool loops) that operators most want to observe. ## What Was Observed A three-turn agent task — `search`, then `read_file`, then `summarize` — produced the following child `chat` spans under one `invoke_agent` span. Each `chat` span carried the conventions-compliant attributes: - Turn 1: `input_tokens=1840`, `output_tokens=210` (emits tool call `search`) - Turn 2: `input_tokens=2430`, `output_tokens=185` (emits tool call `read_file`); note 2430 ≈ 1840 + 210 + tool result + scaffolding - Turn 3: `input_tokens=3110`, `output_tokens=340` (final answer) The naive parent aggregator computed `input_tokens = 1840 + 2430 + 3110 = 7380` and `output_tokens = 210 + 185 + 340 = 735`. The provider's invoice for the task was **3110 input tokens** (the final, prefix-inclusive prompt is the only one whose prefix was not re-billed in full — earlier turns were billed at their own sizes but their content is a subset of the final prompt) and **735 output tokens**. The parent span overstated input by 137%. Output tokens summed correctly, because output is genuinely additive across turns; input is not. This asymmetry — output additive, input prefix-cumulative — is the trap. A team that validates only output tokens will ship a dashboard that looks correct until someone reconciles against billing. A second observed failure compounded it. The `execute_tool` child spans were emitted with `gen_ai.usage.input_tokens` set to the *token cost of the tool's returned payload* (a reasonable but non-standard use of the attribute, since the conventions reserve usage for model inference). The aggregator, filtering only on `gen_ai.operation.name`, swept these into the model total as well, adding a further 1900 phantom input tokens. The tool spans were structurally indistinguishable from inference spans to the aggregator because the filter keyed on the presence of `gen_ai.usage.*` rather than on `gen_ai.operation.name = chat`. ## Condition of Validity The invariant that makes any aggregation correct is: > **For a span tree rooted at `invoke_agent`, the task's input token cost equals the `gen_ai.usage.input_tokens` of the *last* `chat` span in the causal chain, not the sum, provided every `chat` span in the chain shares a cumulative context and no context truncation or summarization has occurred between turns.** This condition is valid only when: (a) the runtime does not truncate or summarize context mid-loop (which would make the final prompt *not* a superset of earlier prompts, and the last-span heuristic would then undercount the discarded prefix); (b) no parallel tool fan-out issues multiple `chat` spans whose inputs are disjoint rather than cumulative; and (c) tool spans are excluded by operation name, not by attribute presence. When any of these fails, the correct aggregation is a **delta reconstruction**: input cost = first span's input + Σ over subsequent spans of (that span's input − previous span's input − previous span's output), which reconstructs the non-prefix portion actually added at each step. This delta form is the only aggregation that survives truncation, because a truncated turn produces a negative delta, which the runtime must clamp to the truncated span's own input size and flag. ## Decision Boundary The boundary between "sum children" and "take last / reconstruct deltas" is decided by one field the conventions do not currently standardize: whether the prompt is cumulative. Operationally, a runtime must decide this **before** emitting the parent span, and it must record the decision on the parent so downstream consumers cannot re-derive it wrongly. The decision rule: - If the agent loop is single-threaded and context is append-only → emit parent `gen_ai.usage.input_tokens` = last child's input; annotate `agent.context.mode = "cumulative"`. - If any turn truncated or summarized → emit parent input = delta reconstruction; annotate `agent.context.mode = "reconstructed"` and `agent.context.truncations = `. - If parallel fan-out occurred → the parent cannot carry a single scalar; emit per-branch subtotals and mark the parent input attribute as absent rather than emitting a misleading sum. The failure mode this prevents is an aggregator silently choosing the wrong branch because the parent span gave it no signal. Absence of the attribute is a valid, checkable state; a wrong number is not. ## Operational Effect Emitting the context-mode annotation converts a silent 137% overstatement into a queryable dimension, and it lets the reconciliation job assert a hard invariant: `parent.input_tokens == last_child.input_tokens` for cumulative trees, with any deviation raising at collection time rather than surfacing as a budget surprise a week later. The tool-span exclusion must be enforced structurally — the aggregator filters `gen_ai.operation.name == "chat"` and treats usage attributes on `execute_tool` spans as payload-size telemetry under a distinct namespace (`tool.payload.tokens`), never as model usage. Together these two guards — operation-name filtering and context-mode annotation — are the minimum invariant set; without both, the span tree is a lossy encoding of cost and no downstream consumer can recover the truth. ```python from dataclasses import dataclass class TokenAccountingInvariantError(RuntimeError): """Raised when a span tree's usage attributes cannot be reconciled under the declared context mode.""" @dataclass class ChatSpan: operation_name: str input_tokens: int output_tokens: int def aggregate_agent_input_tokens( spans: list[ChatSpan], context_mode: str, truncations: int = 0, ) -> int: chat_spans = [s for s in spans if s.operation_name == "chat"] if not chat_spans: raise TokenAccountingInvariantError( "invoke_agent span has no chat children; cannot attribute input tokens" ) if context_mode == "cumulative": if truncations != 0: raise TokenAccountingInvariantError( f"context_mode=cumulative but truncations={truncations}; " "last-span heuristic would undercount discarded prefix" ) return chat_spans[-1].input_tokens if context_mode == "reconstructed": total = chat_spans[0].input_tokens for prev, cur in zip(chat_spans, chat_spans[1:]): delta = cur.input_tokens - prev.input_tokens - prev.output_tokens if delta < 0: # Truncation or summarization collapsed the context. # Clamp to the span's own input and require an annotation. if truncations == 0: raise TokenAccountingInvariantError( "negative delta observed but truncations=0; " "context mode mislabeled" ) delta = cur.input_tokens total += delta return total if context_mode == "parallel_fanout": raise TokenAccountingInvariantError( "parallel fan-out cannot be reduced to a single scalar; " "emit per-branch subtotals" ) raise TokenAccountingInvariantError(f"unknown context_mode={context_mode!r}") ```