# What structural signals indicate token-accounting drift when OpenTelemetry GenAI spans merge child tool-call usage into a parent agent span **Date of Record:** 2026 December 2 **Scope:** Applies to agents emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where a parent agent/invoke span aggregates token usage from child chat and tool-execution spans. Does not apply to single-shot LLM calls with no child spans, nor to billing systems that read provider-side invoices directly. ## Core Distinction The GenAI semantic conventions define token attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and the newer `gen_ai.usage.input_tokens.cached`) as *per-operation* measurements attached to the span that performed the inference. They are **not** defined as additive counters to be rolled up by an agent orchestration layer. The distinction that matters operationally: a span's usage attributes describe one model invocation; an agent's total cost is a *derived aggregation* that the collector or backend must compute by summing leaf spans. The failure mode arises when an agent framework, wanting a single "total tokens" number on the root agent span, writes the sum of all descendant usage into the root span's own `gen_ai.usage.*` attributes. This looks correct in a trace viewer and is catastrophically wrong in any pipeline that also sums leaf spans, because the leaf usage is now double-counted. Worse, the conventions provide no marker distinguishing "this span performed inference and here is its usage" from "this span is a rollup container carrying aggregated usage." Both look identical: a span with `gen_ai.usage.input_tokens` set. ## What Was Observed A multi-step agent (planner → 4 tool-calling ReAct iterations → synthesizer) emitted a trace where the root `invoke_agent` span carried `gen_ai.usage.input_tokens = 41820` and `output_tokens = 3110`, while the six child `chat` spans each carried their own usage summing to exactly the same 41820/3110. The collector's OTLP-to-metrics processor, configured per the conventions' guidance to emit `gen_ai.client.token.usage` histograms from spans bearing usage attributes, emitted seven data points per request — one from the root, six from children. Three structural signals flagged the drift, none of which is a schema violation: 1. **Usage-attribute cardinality exceeded span-kind cardinality.** The root span had `gen_ai.operation.name = invoke_agent` but carried `gen_ai.usage.*`. Per the conventions, `invoke_agent` is an orchestration operation; usage attributes on it are only meaningful if the agent itself is a thin wrapper over a single model call. When a span with `invoke_agent` has child spans that *also* carry usage, the parent's usage is either its own (and children are separate) or an aggregate (and children are double-counted). The trace cannot tell you which. 2. **Sum-of-leaf ≠ root, but only sometimes.** In traces where the agent made exactly one model call (no tools), root usage equaled the single child's usage — indistinguishable from correct. The double-count only manifested on multi-call traces, so a smoke test on a single-turn agent passes while production multi-turn agents silently double their reported token spend by a factor equal to the number of inference calls. 3. **`gen_ai.usage.input_tokens.cached` broke the sum invariant.** Cached tokens are a *subset* of input tokens, not additive. Agents that summed `input_tokens + cached` or that copied cached counts to the root while children reported zero cached produced a root whose `cached` exceeded its `input_tokens` — a physically impossible state that the schema does not forbid. ## Condition of Validity The rollup is only sound when **exactly one** of the following holds and is enforced structurally: - The root span carries usage **and** has no descendant spans carrying usage attributes (single-inference agent), or - The root span carries **no** usage attributes and aggregation is done exclusively by the backend summing leaf spans, or - The root span carries usage but is explicitly tagged with a non-standard marker (e.g., `gen_ai.usage.aggregate = true`) and the collector is configured to exclude marked spans from metric emission. Absent one of these, any pipeline that both reads span-level usage and sums across spans is undefined. The invariant to enforce: **for any trace, the sum of `gen_ai.usage.input_tokens` over spans where usage is a leaf measurement must equal the true provider-reported total, and no span may contribute to that sum twice.** Cached tokens must satisfy `cached ⊆ input` per span and must never be summed into `input`. ## Decision Boundary The boundary is whether the emitting agent framework knows, at span-close time, whether it is a leaf or a container. If it cannot distinguish — because the framework writes usage in a `finally` block regardless of child count — it must **not** write usage on the orchestration span. The safe default is: write usage only on spans with `gen_ai.operation.name ∈ {chat, text_completion, embeddings}`, never on `invoke_agent` or `execute_tool`. Tool spans in particular must not carry `gen_ai.usage.*` at all; their cost is the model call that requested them, already counted on the `chat` span. A `execute_tool` span bearing usage attributes is itself a drift signal, because tool execution does not consume model tokens. When the framework *does* want a root total for dashboards, it must emit it under a distinct, non-convention attribute namespace (e.g., `agent.rollup.input_tokens`) so that convention-compliant collectors ignore it and only custom dashboards read it — keeping the two accounting paths disjoint. ## Operational Effect The observable effect is a token-cost metric that inflates by a factor of (inference calls per trace) while latency and error-rate metrics remain correct — a signature that misleads capacity planning toward "our agents are expensive" when the true cost is 1/N of reported. Budget alerts fire on summed leaf spans while the root-span dashboard shows a different number, and reconciliation against the provider invoice fails by exactly the double-counted amount. The fix is a collector-side dedup rule keyed on `trace_id`: prefer leaf spans, drop container spans, and reject any span where `cached > input` or where `operation.name == execute_tool` carries usage. ```python from dataclasses import dataclass class TokenAccountingDriftError(RuntimeError): """Raised when a GenAI span violates the leaf-vs-rollup usage invariant.""" pass @dataclass class GenAISpan: span_id: str trace_id: str operation_name: str # e.g. "chat", "invoke_agent", "execute_tool" input_tokens: int = 0 output_tokens: int = 0 cached_tokens: int = 0 is_aggregate_marked: bool = False LEAF_OPS = {"chat", "text_completion", "embeddings"} CONTAINER_OPS = {"invoke_agent", "execute_tool"} def validate_trace(spans: list[GenAISpan]) -> int: """Return the deduplicated true input-token total for a trace. Enforces: leaf-only usage, cached subset of input, no usage on tool spans, and no unmarked container span carrying usage when leaves also carry usage. """ leaves = [s for s in spans if s.operation_name in LEAF_OPS] containers_with_usage = [ s for s in spans if s.operation_name in CONTAINER_OPS and (s.input_tokens or s.output_tokens or s.cached_tokens) and not s.is_aggregate_marked ] for s in spans: if s.cached_tokens > s.input_tokens: raise TokenAccountingDriftError( f"span {s.span_id}: cached_tokens={s.cached_tokens} exceeds " f"input_tokens={s.input_tokens} (cached must be a subset)" ) if s.operation_name == "execute_tool" and (s.input_tokens or s.output_tokens): raise TokenAccountingDriftError( f"span {s.span_id}: execute_tool span carries gen_ai.usage.*; " f"tool execution consumes no model tokens" ) if leaves and containers_with_usage: offending = ", ".join(s.span_id for s in containers_with_usage) raise TokenAccountingDriftError( f"trace {spans[0].trace_id}: container span(s) {offending} carry " f"unmarked usage alongside {len(leaves)} leaf spans; summing both " f"double-counts tokens. Mark with gen_ai.usage.aggregate=true or " f"strip usage from container spans." ) return sum(s.input_tokens for s in leaves) ```