# What happens when an instance double-counts tokens across nested GenAI spans: the OpenTelemetry `gen_ai.usage.input_tokens` attribution boundary **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans per LLM call and per tool call, where a single top-level agent span nests multiple `gen_ai.*` child spans and a shared token counter or billing reconciler reads span attributes. Does not apply to single-shot inference with no nesting, nor to systems that aggregate usage exclusively from a flat event stream outside the span tree. ## Core Distinction OpenTelemetry's GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-inference-call* attributes on the span representing that call. They are **not** rollup attributes. The convention is silent on what a *parent* GenAI span should report when its children already reported usage—and this silence is where accounting breaks. Two distinct quantities get conflated: 1. **Call-level usage**: tokens actually consumed by one model invocation, reported on the leaf `gen_ai.chat` span. 2. **Span-subtree usage**: the sum over all descendant `gen_ai.*` spans, which a naive collector derives by walking the trace. A correct accounting invariant is: *the sum of `gen_ai.usage.input_tokens` across all GenAI spans in a trace equals the true billable input for that trace, counted exactly once.* The failure mode is that an agent framework that wraps a multi-step reasoning loop in its own `gen_ai.*` span (to attribute the whole agent turn to a model) writes the *aggregate* token count onto that parent span, while its child `gen_ai.chat` spans each write their own counts. A collector that sums all GenAI spans in the trace now counts every leaf token twice: once at the leaf, once inside the parent's aggregate. ## What Was Observed A three-step ReAct agent (plan → tool call → synthesize) emitted this span tree for one user turn: - `gen_ai.agent.turn` (parent, `gen_ai.operation.name=invoke_agent`) — attributes `gen_ai.usage.input_tokens=4820`, `gen_ai.usage.output_tokens=610` - `gen_ai.chat` step 1 (planning) — `input_tokens=1500`, `output_tokens=180` - `gen_ai.chat` step 2 (post-tool synthesis) — `input_tokens=2100`, `output_tokens=240` - `gen_ai.chat` step 3 (final answer) — `input_tokens=1220`, `output_tokens=190` The leaf sum is 1500+2100+1220 = 4820 input, 180+240+190 = 610 output — exactly the parent's values. The framework author intended the parent span to be a *convenience rollup*. The billing reconciler, written against the convention's "usage is a per-call attribute" reading, summed every span carrying `gen_ai.usage.input_tokens`. It reported 9640 input tokens for a turn that consumed 4820. The discrepancy was invisible in per-span dashboards (each span looked individually correct) and only surfaced when the reconciler's daily total diverged from the provider's invoice by a stable ~2.0× on agent-traffic days and ~1.0× on single-shot days. The ratio was the tell: it tracked the average nesting depth of GenAI spans, not any absolute volume. A second, subtler variant appeared with tool calls. The `gen_ai.tool` span (the tool execution) carried no usage, correctly. But one framework copied the *preceding* chat span's usage onto the tool span "for correlation," so the tool span also matched the summing predicate and injected a third copy. ## Condition of Validity The double-count is only possible when **all** of the following hold simultaneously: 1. A GenAI-typed span exists at more than one depth in the same trace (parent `invoke_agent`/`gen_ai.*` plus child `gen_ai.chat`). 2. The parent span carries `gen_ai.usage.*` attributes populated with a value that is a *function of* its children's usage (rollup), rather than usage of a distinct model call the parent itself made. 3. The consumer aggregates by *predicate over span attributes* (e.g., "sum `gen_ai.usage.input_tokens` wherever present") rather than by *span role* (e.g., "sum only leaf `gen_ai.chat` spans"). Break any one and the failure cannot occur. If the parent omits usage attributes, predicate-summing is safe. If the consumer filters to `gen_ai.operation.name == "chat"`, rollups on `invoke_agent` spans are excluded. If the parent genuinely represents a separate model call (e.g., a router model invoked at the parent level), its usage is legitimately its own and summing is correct—this is the case that makes the boundary non-obvious, because the *same attribute name* means different things depending on span role. ## Decision Boundary The operative rule: **`gen_ai.usage.*` is authoritative only on spans whose `gen_ai.operation.name` denotes an actual model invocation (`chat`, `text_completion`, `embeddings`, `generate_content`). Any span at a higher abstraction level must not carry usage attributes, or must carry them under a distinct, non-conventional key (e.g., `agent.rollup.input_tokens`) that the summing predicate does not match.** When emitting: never write `gen_ai.usage.*` onto `invoke_agent`, workflow, or orchestration spans. If a rollup is operationally useful, namespace it away from the convention so downstream consumers using the standard predicate are not poisoned. When consuming: never sum by attribute presence. Filter by `gen_ai.operation.name ∈ {model-invocation set}` **and** assert that no matching span has a matching descendant (leaf-only), because a framework may mislabel a wrapper span as `chat`. The leaf-only assertion is the load-bearing guardrail: it converts a silent 2× overcount into a loud, attributable error at ingest time. The boundary is genuinely a decision, not a bug to be patched once: the convention deliberately leaves parent-span usage undefined, so each runtime must decide whether its parent span is a *rollup* (must not use the conventional key) or a *distinct call* (may). Ambiguity resolves toward "distinct call" only when the parent has its own model request/response, which is verifiable from the presence of `gen_ai.request.model` and a corresponding response event on that same span. ## Operational Effect Left unguarded, the failure produces a *plausible* wrong number: totals scale with agent nesting depth, per-span views stay green, and the error is proportional rather than categorical, so threshold alerts on absolute token volume miss it. The reconciler drifts from the invoice by a factor equal to mean spans-per-trace, which looks like a pricing or provider-side issue and misdirects debugging away from the trace tree. With the leaf-only guardrail, the failure becomes a hard ingest-time rejection naming the offending parent span, and the rollup is forced into a namespaced key. The cost is that any dashboard expecting a parent-level usage attribute must read the namespaced key or recompute from leaves; the benefit is that the invariant "leaf-sum equals true billable" is enforced structurally rather than by convention discipline that erodes under framework churn. The residual risk after the guardrail: a framework that labels its wrapper span `gen_ai.operation.name=chat` and *also* emits child `chat` spans. The leaf-only assertion catches this (the wrapper has matching descendants), but only if the consumer checks descendant relationships, not merely span kind. This is why the guardrail must operate on the assembled trace, not on individual spans as they stream—a streaming validator cannot see that a `chat` span has `chat` children until the trace closes. ```python from dataclasses import dataclass, field MODEL_INVOCATION_OPS = {"chat", "text_completion", "embeddings", "generate_content"} USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens") class TokenAttributionError(RuntimeError): """Raised when span-level token accounting violates the leaf-only invariant.""" @dataclass class Span: span_id: str parent_id: str | None operation_name: str | None attributes: dict = field(default_factory=dict) def _has_usage(span: Span) -> bool: return any(k in span.attributes for k in USAGE_KEYS) def sum_billable_input_tokens(spans: list[Span]) -> int: """ Enforce: gen_ai.usage.* is authoritative only on leaf model-invocation spans. Any model-invocation span that carries usage AND has a descendant carrying usage is a rollup masquerading as a call -> reject the trace. """ by_id = {s.span_id: s for s in spans} def descendants(span: Span): for cand in spans: p = cand.parent_id while p is not None: if p == span.span_id: yield cand break p = by_id[p].parent_id if p in by_id else None total = 0 for span in spans: if span.operation_name not in MODEL_INVOCATION_OPS: if _has_usage(span): raise TokenAttributionError( f"span {span.span_id} op={span.operation_name!r} carries " f"gen_ai.usage.* but is not a model-invocation span; " f"rollups must use a namespaced key, not the convention." ) continue if not _has_usage(span): continue if any(_has_usage(d) for d in descendants(span)): raise TokenAttributionError( f"span {span.span_id} op={span.operation_name!r} carries " f"gen_ai.usage.* and has usage-bearing descendants; " f"this is a rollup and would double-count. Emit leaf usage only." ) total += int(span.attributes.get("gen_ai.usage.input_tokens", 0)) return total # Trace from the incident: parent rollup + three leaf chat spans. trace = [ Span("p", None, "invoke_agent", {"gen_ai.usage.input_tokens": 4820, "gen_ai.usage.output_tokens": 610}), Span("c1", "p", "chat", {"gen_ai.usage.input_tokens": 1500}), Span("c2", "p", "chat", {"gen_ai.usage.input_tokens": 2100}), Span("c3", "p", "chat", {"gen_ai.usage.input_tokens": 1220}), ] try: sum_billable_input_tokens(trace) except TokenAttributionError as e: print(f"REJECTED trace: {e}") # Consumer must then trust leaf sum only: print("billable input =", sum( int(s.attributes["gen_ai.usage.input_tokens"]) for s in trace if s.operation_name == "chat" )) ```