# Which invariants prevent OpenTelemetry GenAI agent spans from double-counting tokens across nested tool-call spans **Date of Record:** 2026 December 2 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions where a single logical turn produces nested `invoke_agent` → `chat` → `execute_tool` spans and per-span `gen_ai.usage.*_tokens` attributes are aggregated by a downstream collector or cost dashboard. Does not cover non-OTel tracing backends, single-span synchronous LLM calls with no tool fan-out, or billing reconciliation against provider invoices. ## Core Distinction The failure is not "wrong token counts." It is the collapse of the distinction between **per-span attribution** and **per-turn aggregation**. The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of the span that *made* the model call. They do not define an aggregation contract across a span tree. When an agent loop issues N model calls (one per reasoning step, each followed by tool calls), each `chat` span legitimately carries its own usage attributes. A naive collector that sums `gen_ai.usage.*_tokens` across *all* spans in a trace — including the parent `invoke_agent` span, which many instrumentations populate with the *cumulative* turn usage — produces a total inflated by roughly the nesting depth. The invariant that prevents this is: **usage attributes are leaf-attributed and non-inherited; only one span per model call may carry them, and aggregation must be a tree-fold over `chat` spans, never a flat sum over the trace.** ## What Was Observed A three-step agent turn: `invoke_agent` (root) → `chat` (step 1) → `execute_tool` (search) → `chat` (step 2) → `execute_tool` (fetch) → `chat` (step 3). Instrumentation emitted: - Root `invoke_agent` span: `gen_ai.usage.input_tokens=4820`, `gen_ai.usage.output_tokens=610` (the framework's own cumulative rollup). - Three `chat` spans: `input_tokens` of 1400, 1650, 1770 (sum = 4820); `output_tokens` of 180, 240, 190 (sum = 610). - Two `execute_tool` spans: no usage attributes (correct — tools don't consume model tokens). The collector's aggregation rule was `sum(gen_ai.usage.input_tokens over all spans with the attribute)`. Result: 4820 (root) + 4820 (children) = **9640 input tokens**, a 2.0× inflation. Output: 1220, also 2.0×. Cost dashboards doubled, and a budget-alert rule fired mid-turn, causing the orchestrator to abort step 3 — which then *lost* the tool result and forced a replay. The replay re-emitted the same spans, and because the trace ID was regenerated, the collector counted a *third* copy. Observed inflation reached 3.0×. The non-obvious part: the inflation is **depth-dependent and silent**. A flat agent (one chat span, no tool fan-out) shows 2.0× because root and child both carry usage. A deep agent (five steps) shows 2.0× on the root-vs-children axis but the children themselves are correct — so the error looks like a constant factor, not a structural bug, and passes casual spot checks. ## Condition of Validity The leaf-attribution invariant holds if and only if all of the following are true: 1. **Exactly one span per model invocation carries `gen_ai.usage.*_tokens`.** If the SDK also stamps a cumulative total on the parent `invoke_agent` span, that parent attribute MUST be marked as a rollup (e.g., a distinct attribute namespace or a `gen_ai.usage.aggregate=true` flag) so the collector can exclude it from the flat sum. 2. **`execute_tool` spans never carry model usage attributes.** A tool that internally calls an LLM (e.g., a summarizer tool) must emit its *own* nested `chat` span; it must not attribute tokens to the `execute_tool` span, or the tree-fold will miss them. 3. **Retries emit a new span, not a mutated attribute.** A retried `chat` call that overwrites the prior span's `input_tokens` destroys the audit trail; a retried call that emits a sibling span with the same `gen_ai.operation.name` is correct and must be counted once per attempt. 4. **Span context propagates across the tool boundary.** If the tool executes in a separate process that does not receive the W3C traceparent, its nested `chat` span becomes an orphan root, and the tree-fold silently undercounts. When any of these is violated, the aggregation is undefined and the invariant does not apply — you get either inflation (double-count) or deflation (orphaned spans). ## Decision Boundary The boundary is between **attribution-time** and **aggregation-time** enforcement: - *Attribution-time (preferred):* the instrumentation library refuses to emit cumulative usage on a non-leaf span. This is a hard invariant: `invoke_agent` spans carry `gen_ai.agent.name`, `gen_ai.operation.name`, and step counts, but **not** `gen_ai.usage.*_tokens` unless the span is itself a leaf model call. - *Aggregation-time (fallback):* the collector reconstructs the tree from `parent_span_id` and sums usage only over spans where `gen_ai.operation.name == "chat"` and `span.kind == CLIENT` (the model-call span), explicitly ignoring any `SERVER`/`INTERNAL` parent that also carries the attribute. Cross the boundary the wrong way — emit cumulative on the parent *and* sum flat — and you are in the inflation regime. The decision rule: **if a span has children that are themselves model-call spans, its usage attributes are either absent or explicitly rollup-typed; a flat sum over all spans is only valid when no span has both usage attributes and model-call descendants.** ## Operational Effect Enforcing the invariant changes three downstream behaviors: 1. **Budget alerts become monotone.** Per-turn cost is a tree-fold, so it cannot exceed the sum of leaf calls. Mid-turn aborts from phantom over-budget disappear. 2. **Replay accounting becomes idempotent** only if trace IDs are stable across replays. If the orchestrator regenerates trace IDs on replay (as observed), the collector must dedupe on `(gen_ai.conversation.id, step_index)` rather than trace ID, or the invariant is preserved at span level but violated at trace level. 3. **Tool-internal LLM calls are visible.** A `execute_tool` span that hides a nested `chat` span will undercount; the invariant forces the nested span to surface, which is the correct behavior for cost attribution but may surprise teams that assumed tools are free. The residual risk: the GenAI conventions are still evolving, and `gen_ai.usage.*` semantics are not yet normative about rollup. Until they are, the invariant must be enforced by the instrumentation library (attribution-time) because collectors cannot reliably distinguish a leaf `chat` span from a parent that copied its child's attributes. ```python from dataclasses import dataclass, field from typing import Iterable class UsageAttributionError(RuntimeError): """Raised when a span violates the leaf-attribution invariant for GenAI usage.""" @dataclass class Span: span_id: str parent_id: str | None operation: str # "invoke_agent" | "chat" | "execute_tool" kind: str # "CLIENT" | "SERVER" | "INTERNAL" input_tokens: int | None = None output_tokens: int | None = None children: list["Span"] = field(default_factory=list) def validate_leaf_attribution(span: Span) -> None: has_usage = span.input_tokens is not None or span.output_tokens is not None model_call_children = [c for c in span.children if c.operation == "chat"] if has_usage and model_call_children and span.operation != "chat": raise UsageAttributionError( f"span {span.span_id} ({span.operation}) carries usage attributes " f"but has {len(model_call_children)} chat descendants; " f"usage must be leaf-attributed only" ) for child in span.children: validate_leaf_attribution(child) def fold_usage(root: Span) -> tuple[int, int]: """Tree-fold over chat spans only; never a flat sum over the trace.""" validate_leaf_attribution(root) total_in = total_out = 0 stack = [root] while stack: s = stack.pop() if s.operation == "chat" and s.kind == "CLIENT": total_in += s.input_tokens or 0 total_out += s.output_tokens or 0 stack.extend(s.children) return total_in, total_out ```