# What happens when an instance attributes child-span token usage to the wrong GenAI semantic convention generation **Date of Record:** 2026 November 30 **Scope:** Applies to agents emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where a parent agent span fans out to child tool-call and chat spans, and where the collector or backend aggregates `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` for cost and budget enforcement. Does not apply to single-span, non-nested instrumentation, nor to backends that only consume raw span payloads without cross-span aggregation. ## Core Distinction There are two incompatible ways an agent span tree can describe token usage, and they are not distinguishable from the attribute values alone: 1. **Inclusive accounting** — the parent agent span carries the *sum* of all descendant chat spans' token usage, and children carry their own usage. This is the model implied by naive "wrap the whole run in a span and record the total" instrumentation. 2. **Exclusive accounting** — only the leaf chat spans carry `gen_ai.usage.*`, and intermediate agent/tool spans carry none, on the assumption that aggregation happens at query time by summing leaves. The GenAI semantic conventions define the attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.system`, `gen_ai.request.model`) but do **not** pin down whether a non-chat span may legally carry usage attributes. The convention is silent on double-counting. A backend that sums `gen_ai.usage.input_tokens` across *all* spans in a trace therefore produces a token total that is correct under exclusive accounting and inflated by the fan-out factor under inclusive accounting. The boundary failure is not in any single span — every span is individually well-formed — but in the *aggregation invariant* that the convention leaves unstated. ## What Was Observed A tool-using agent was instrumented with a run-level span `agent.run` (`gen_ai.operation.name = "invoke_agent"`) that, at completion, set `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` to the run total reported by the orchestrator's own counter. Three child `chat` spans (`gen_ai.operation.name = "chat"`) each set their own per-call usage, and two nested `execute_tool` spans set none. The trace was valid. The per-span attributes were valid. The failure surfaced at the cost dashboard: - The leaf-sum aggregation reported 8,140 input tokens for the run. - The run-span value reported 8,140 input tokens for the run. - A backend configured to sum *every* span carrying `gen_ai.usage.input_tokens` reported **16,280** — exactly 2×. The 2× factor was not constant across runs. It equaled `1 + (number of usage-bearing non-leaf spans)`, so runs with retried chat calls (an extra nested `chat` span under a retry wrapper span that also stamped usage) inflated by 3× or 4×. The budget-enforcement loop, which halted the agent when cumulative input tokens crossed a threshold, began halting healthy runs at roughly half their intended budget. The agent's *behavior* changed — it truncated reasoning and skipped tool calls to stay under a phantom budget — while every span remained schema-valid. This is the non-obvious part: the semantic-convention violation produced no validation error, only a silent behavioral regression two layers up. A second, subtler observation: when the orchestrator retried a chat call after a timeout, the retry wrapper span copied the *failed* attempt's usage attributes as well as the successful attempt's. Because the failed attempt had consumed tokens (the request was sent; the response was lost), the "correct" total genuinely includes both — but the leaf-sum backend counted them too, while the run-span backend counted them once. The two aggregations disagreed on retry-heavy traces even after the double-count was fixed, because they disagreed about whether retries are inclusive of prior attempts. ## Condition of Validity The exclusive-accounting invariant holds only when: - Every span carrying `gen_ai.usage.*` is a leaf chat/embedding span, **or** - Every non-leaf span carrying `gen_ai.usage.*` is explicitly marked with a disambiguating attribute (e.g. `gen_ai.usage.aggregate = true` or a custom `agent.usage.rollup = "inclusive"`) that the backend is configured to exclude from summation. Absent one of these, the convention is under-determined and any aggregation is a guess. The invariant also requires that retry attempts be represented as *sibling* chat spans under a wrapper that carries no usage, so that "sum of leaves" equals "true billed tokens" including retries. If the retry wrapper itself stamps usage, the leaf-sum and rollup models diverge on retry paths specifically — the failure is masked on clean runs and only appears under retry load, which is exactly when budget enforcement matters most. ## Decision Boundary The decision the instrumenting agent must make at span-emit time: - **If the backend aggregates by leaf-sum** (the common default for GenAI cost tooling), then non-leaf spans MUST NOT emit `gen_ai.usage.*`. The run total is a derived query, never a stamped attribute. Cost dashboards read it from the leaf sum. - **If the backend aggregates by span-max or by explicit rollup attribute**, then non-leaf spans MAY emit usage, but every such span MUST carry the disambiguator, and the backend MUST be configured to honor it. Mixing the two within one service is the failure mode — a single misconfigured emitter poisons every trace it touches. The boundary is crossed the moment an instance emits usage on a non-leaf span without a disambiguator while the backend sums all usage-bearing spans. There is no runtime signal that this has happened; the only detector is a cross-check between leaf-sum and rollup totals on the same trace, which must be run as a continuous invariant, not a one-time audit. ## Operational Effect Downstream, the inflated total propagates into budget-enforcement state, and because the agent's halting logic reads that state, the corruption feeds back into agent behavior: the agent under-spends, truncates, and skips tool calls it would otherwise make. The trace remains green; the agent silently degrades. Recovery requires (a) identifying every non-leaf span that stamps usage, (b) either stripping the attribute or adding the disambiguator and reconfiguring the backend, and (c) replaying the budget state for in-flight runs, because the phantom spend is already latched in the enforcement counter. The invariant to enforce going forward: *for every completed trace, `sum(leaf gen_ai.usage.input_tokens) == rollup gen_ai.usage.input_tokens`, and any span carrying usage that has children must carry a disambiguator.* Violation of that equality is the only reliable detector, and it must be checked on retry-heavy traces specifically, where the two models diverge even under correct exclusive accounting. ```python from dataclasses import dataclass, field class TokenAccountingInvariantError(RuntimeError): """Raised when a trace's GenAI usage attributes violate the leaf-sum == rollup invariant under the exclusive-accounting model.""" @dataclass class Span: name: str operation: str # "invoke_agent" | "chat" | "execute_tool" input_tokens: int = 0 output_tokens: int = 0 children: list["Span"] = field(default_factory=list) disambiguator: bool = False # gen_ai.usage.aggregate == true def _walk(span: Span): yield span for child in span.children: yield from _walk(child) def verify_token_accounting(root: Span) -> None: """Enforce: sum of leaf chat usage == any rollup usage on non-leaf spans, and every non-leaf span carrying usage must carry a disambiguator.""" leaf_input = leaf_output = 0 rollup_input = rollup_output = 0 for span in _walk(root): has_usage = span.input_tokens or span.output_tokens if not has_usage: continue is_leaf = not span.children if is_leaf: leaf_input += span.input_tokens leaf_output += span.output_tokens else: if not span.disambiguator: raise TokenAccountingInvariantError( f"non-leaf span {span.name!r} ({span.operation}) carries " f"gen_ai.usage.* without a disambiguator; backend leaf-sum " f"aggregation will double-count it" ) rollup_input += span.input_tokens rollup_output += span.output_tokens if rollup_input and rollup_input != leaf_input: raise TokenAccountingInvariantError( f"input token mismatch: leaf-sum={leaf_input} rollup={rollup_input} " f"(delta {rollup_input - leaf_input}); retry attempts may be " f"stamped on a wrapper span instead of as sibling chat spans" ) if rollup_output and rollup_output != leaf_output: raise TokenAccountingInvariantError( f"output token mismatch: leaf-sum={leaf_output} rollup={rollup_output}" ) def enforce_or_halt(root: Span, budget_input: int) -> None: try: verify_token_accounting(root) except TokenAccountingInvariantError: # Do not feed a corrupt total into budget enforcement; halt the run # rather than let the agent silently under-spend against phantom usage. raise total = sum(s.input_tokens for s in _walk(root) if not s.children) if total > budget_input: raise TokenAccountingInvariantError( f"budget exceeded on verified total: {total} > {budget_input}" ) ```