# Which invariants prevent token-usage double-counting across nested agent and tool-call spans in OpenTelemetry GenAI traces **Date of Record:** 2026 November 22 **Scope:** Applies to agents that emit OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.*` attributes) where an LLM invocation span (`gen_ai.operation.name = "chat"`) and its child tool-execution spans (`gen_ai.operation.name = "execute_tool"`) both carry token-usage attributes and are aggregated by a downstream collector into cost/throughput metrics. Does not apply to single-span, flat traces where no parent-child token attribution occurs, nor to metrics derived from a single authoritative source (e.g., provider-side billing exports). ## Core Distinction The GenAI semantic conventions define token usage as attributes on the LLM invocation span: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. They do **not** specify that these attributes are mutually exclusive with respect to span nesting. The distinction that matters operationally is between *usage-bearing spans* (spans that actually consumed model tokens) and *usage-propagating spans* (spans that aggregate or re-expose child usage for convenience). The convention leaves this distinction implicit, and the instrumentation default — "copy child usage onto the parent so the parent is self-describing" — silently converts a tree of disjoint usage into a set of overlapping usage. A collector that sums `gen_ai.usage.*` across *all* spans in a trace then counts the same tokens once per ancestor level. The invariant that must hold for correct aggregation is: **for any trace, the set of spans carrying `gen_ai.usage.*` attributes must be pairwise non-nested** (no usage-bearing span may be an ancestor of another usage-bearing span). Equivalently, token usage must be attributed at exactly one level of the span tree — the leaf that actually issued the model call — and any aggregate must be reconstructed by the collector via tree traversal, never by flat summation. ## What Was Observed A multi-step tool-using agent emits the following span tree for a single user turn: ``` invoke_agent (root) ├── chat (step 1: plan) input=1200, output=180 │ └── execute_tool (search) input=0, output=0 ├── chat (step 2: synthesize) input=2400, output=310 │ └── execute_tool (fetch) input=0, output=0 └── (agent-level aggregate emitted by SDK convenience wrapper) gen_ai.usage.input_tokens = 3600 ← copied from children gen_ai.usage.output_tokens = 490 ``` The agent framework's tracing helper, aiming to make the root span "self-describing," sums the two `chat` spans and writes the totals onto `invoke_agent`. The two `chat` spans remain on the trace unchanged. A collector computing per-turn cost with the natural query — `sum(gen_ai.usage.input_tokens) by trace_id` — now returns **7200**, exactly double the true 3600. The failure is silent: every individual span is correct; only the aggregation over the tree is wrong. Dashboards show a 2× cost regression the day the SDK convenience wrapper is upgraded, with no change to model calls, prompts, or provider billing. A second, subtler variant appears with streaming and retries: a `chat` span that is retried mid-stream emits a *second* `chat` span under the same parent with partial `output_tokens`, and the parent aggregate is recomputed from only the successful attempt, dropping the partial tokens from the failed one. Here the invariant that breaks is different — not nesting overlap but *attempt coverage* — and it produces under-counting rather than double-counting. ## Condition of Validity The non-nesting invariant is only enforceable when three conditions hold simultaneously: 1. **Usage is attributed at the leaf.** The instrumentation contract must state that `gen_ai.usage.*` is set only on spans where `gen_ai.operation.name` is `chat` (or `embeddings`/`text_completion`) and the span actually terminates a model request. Framework wrappers that "helpfully" aggregate must instead emit a *distinct* attribute namespace (e.g., `agent.usage.aggregate.input_tokens`) or a span event, not reuse `gen_ai.usage.*`. 2. **The collector aggregates by tree, not by flat scan.** Because the convention does not forbid nested usage, the collector cannot assume non-nesting; it must either (a) filter to `gen_ai.operation.name = "chat"` before summing, or (b) traverse parent-child links and sum only spans with no usage-bearing descendant. Option (a) is fragile if a future operation name is introduced; option (b) is the robust invariant enforcement. 3. **Retries are represented as sibling attempts, not nested spans.** A retried `chat` must produce sibling spans (or span events with their own token attributes) so that summing leaves captures all attempts. If a retry nests under the original, the non-nesting invariant is violated by a different mechanism and the leaf-sum under-counts. When any of these fails, the invariant is unenforceable at the collector and must be enforced at the instrumentation boundary — which is exactly where the convention is silent. ## Decision Boundary The decision boundary is whether to treat `gen_ai.usage.*` as **authoritative leaf-level fact** or as **denormalized convenience aggregate**. The convention's wording supports the former (attributes live on the invocation span), but human ergonomics favor the latter (a root span that answers "what did this turn cost?" without a join). These two readings are incompatible in a single trace. The boundary resolves as follows: **if any span in a trace carries `gen_ai.usage.*` and has a descendant that also carries `gen_ai.usage.*`, the trace is in a malformed state for aggregation and the collector must reject or re-derive rather than sum.** A well-behaved collector detects this by walking the span tree and asserting the non-nesting property before emitting token metrics. If the assertion fails, it should fall back to leaf-only summation (filtering by operation name) and emit a `gen_ai.usage.nesting_conflict` counter so the instrumentation regression is visible. The alternative — summing everything and hoping no wrapper aggregates — is the failure mode observed above. For the retry sub-case, the decision boundary is whether a failed attempt's partial `output_tokens` are *billable* (they are, for most providers) and therefore must be counted. The invariant is that every attempt span that reached the model must carry its own usage, and leaf summation must include failed attempts, not just successful ones. ## Operational Effect Enforcing the non-nesting invariant plus leaf-only aggregation changes three operational behaviors: - **Cost dashboards stop doubling on SDK upgrades.** The 2× regression described above is caught at the collector by the nesting assertion, and the `nesting_conflict` counter fires the moment a framework wrapper starts copying usage upward. The regression is attributed to instrumentation, not to a model change. - **Retry accounting becomes correct.** Failed-attempt output tokens are counted, closing the under-count that otherwise makes retry-heavy agents look cheaper than they are. - **The convention's silence becomes an explicit contract.** Teams must document in their instrumentation guide that `gen_ai.usage.*` is leaf-only and that aggregates use a separate namespace. This is the guardrail the convention does not supply. The cost is that root-span self-description is lost; consumers must join or traverse. That is the correct trade: a self-describing root that is numerically wrong is worse than a leaf that is numerically right and requires a join. ```python from dataclasses import dataclass, field from typing import Optional class UsageNestingConflict(RuntimeError): """Raised when a usage-bearing span has a usage-bearing descendant.""" pass @dataclass class Span: span_id: str parent_id: Optional[str] operation_name: str input_tokens: Optional[int] = None output_tokens: Optional[int] = None children: list = field(default_factory=list) @property def carries_usage(self) -> bool: return self.input_tokens is not None or self.output_tokens is not None def assert_non_nesting(root: Span) -> None: """Enforce: no usage-bearing span may be an ancestor of another usage-bearing span.""" def walk(span: Span, usage_ancestor: Optional[str]) -> None: if span.carries_usage and usage_ancestor is not None: raise UsageNestingConflict( f"span {span.span_id} ({span.operation_name}) carries gen_ai.usage.* " f"but has usage-bearing ancestor {usage_ancestor}; " f"flat summation would double-count tokens" ) next_ancestor = span.span_id if span.carries_usage else usage_ancestor for child in span.children: walk(child, next_ancestor) walk(root, None) def sum_leaf_usage(root: Span) -> tuple[int, int]: """Aggregate tokens by leaf-only summation; reject malformed trees first.""" assert_non_nesting(root) total_in = total_out = 0 stack = [root] while stack: span = stack.pop() if span.carries_usage: total_in += span.input_tokens or 0 total_out += span.output_tokens or 0 stack.extend(span.children) return total_in, total_out ```