# Which invariants prevent double-counting of tokens when an agent span and its child tool-call spans both emit `gen_ai.usage.*` under OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 November 25 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions where a parent `invoke_agent` / `execute_tool` span and one or more nested LLM-call or tool-call child spans each populate `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and `gen_ai.usage.total_tokens`. Does not apply to single-span, leaf-only instrumentation where exactly one span per model invocation carries usage attributes. ## Core Distinction The GenAI semantic conventions define *attribute placement* — which span an attribute belongs on — but they do not define an *aggregation contract*. A collector, dashboard, or cost pipeline that sums `gen_ai.usage.total_tokens` across all spans matching `gen_ai.operation.name` will double-count whenever an agent wrapper span mirrors the usage of the LLM calls it orchestrates. The convention is silent on whether a parent `invoke_agent` span should restate the sum of its children's usage. Two valid-looking instrumentations produce numerically different totals from the same execution: - **Leaf-only accounting:** usage lives exclusively on the `chat`/`text_completion` child spans; the `invoke_agent` parent carries zero usage attributes. - **Rolled-up accounting:** the `invoke_agent` parent carries the aggregate sum, and children also carry their individual contributions. Both conform to the spec. A naive `sum(gen_ai.usage.total_tokens)` over the trace is correct for the first and exactly 2× for the second (or N× for N nested agent layers). The invariant that must be enforced is *exactly one span per token-bearing unit of work carries the usage attributes, and the aggregation query is scoped to that span class* — not "sum everything with the attribute." ## What Was Observed A LangGraph-style orchestrator was instrumented such that each `invoke_agent` span emitted `gen_ai.usage.input_tokens` equal to the sum of its child `chat` spans, and each `chat` span emitted its own per-call usage. The collector pipeline computed daily spend with the query: ``` sum(gen_ai.usage.total_tokens) by (service.name, gen_ai.request.model) ``` For a single agent turn that made three LLM calls (plan, tool-select, synthesize) with 1,200 / 800 / 2,400 total tokens respectively, the trace contained: - 1 `invoke_agent` span: `total_tokens = 4400` - 3 `chat` spans: `total_tokens = 1200, 800, 2400` The summed value was **8,800** — precisely 2× the true 4,400. The error was invisible per-turn because the ratio was constant; it only surfaced when a second agent (a reviewer sub-agent) was added whose `invoke_agent` span *did not* roll up, producing a trace where the double-count ratio was inconsistent (some turns 2×, some 1×), yielding a non-linear cost curve that triggered an alert on "cost per request spike" that was actually an instrumentation topology change. A subtler variant: when a `chat` span was retried (rate-limit 429 → retry), the SDK emitted two `chat` spans but the parent `invoke_agent` span was created once and updated its usage attribute to the *last* child's value rather than the sum, under-counting retried calls. Under-counting on retry and over-counting on rollup coexist in the same trace. ## Condition of Validity The aggregation invariant holds only under the following conjunction: 1. **Span-class scoping is explicit.** Every aggregation query filters on `gen_ai.operation.name IN ('chat', 'text_completion')` (leaf model calls) and never sums across `invoke_agent` / `execute_tool` spans. Alternatively, the inverse: sum only `invoke_agent` spans at the root and never descend. The two are mutually exclusive; mixing them is the failure. 2. **Rollup is either complete or absent per span class.** A parent either always restates child usage or never does. Partial rollup (some parents roll up, some don't) makes any single query wrong. 3. **Retries are represented as sibling leaf spans, not attribute mutations.** A retried model call must produce a *new* `chat` span with its own usage; the parent's rolled-up attribute must be recomputed at span end from all leaf children, not overwritten per attempt. 4. **`gen_ai.usage.total_tokens` is not assumed to equal `input + output`.** Providers that include cached or reasoning tokens break the arithmetic identity; the invariant must not depend on it. Sum `input_tokens` and `output_tokens` separately if a breakdown is needed. When any of these is violated, the trace remains structurally valid and every span passes schema validation, but the derived metric is silently wrong. ## Decision Boundary The choice between leaf-only and rolled-up accounting is a boundary decision that must be made *once per instrumentation library* and documented in the span schema, not inferred at query time. The decision boundary: - **Choose leaf-only** when the primary consumer is a cost/billing pipeline that must attribute tokens to a specific model and operation, and when agent nesting depth is variable. Leaf-only is the safer default because it is idempotent under nesting: adding a sub-agent adds leaf spans, never changes existing totals. - **Choose rolled-up** only when the primary consumer is a per-agent-turn latency/cost dashboard that cannot join parent-child, and only if the instrumentation guarantees complete rollup at every agent layer. Rolled-up accounting is fragile under nesting: a depth-3 agent tree requires the root to sum grandchildren, which most SDKs do not do automatically. The dangerous middle ground — leaf spans plus a partially-rolled-up parent — is the configuration that produced the observed 2×/1× inconsistency. It arises naturally when an orchestration framework auto-instruments `invoke_agent` (rolling up) while a lower-level LLM client auto-instruments `chat` (leaf), and neither library knows about the other. The guardrail: the collector must *reject* traces where a span with `gen_ai.operation.name IN ('invoke_agent')` carries `gen_ai.usage.*` attributes while also having descendant `chat` spans with the same attributes, unless an explicit `genai.usage.rollup = true` marker is set. Absent the marker, the parent's usage attributes are treated as a bug and dropped before aggregation. ## Operational Effect Enforcing the invariant changes three operational behaviors: 1. **Cost metrics become nesting-invariant.** Adding a sub-agent or a retry no longer changes the multiplier between reported and true cost. The 2× error that hid behind a constant ratio becomes impossible because the query is scoped to leaf spans, which are additive by construction. 2. **Retry accounting becomes correct.** Because retries are sibling leaf spans, summing leaf usage counts every attempt; the parent's (dropped) rollup no longer masks retried calls. 3. **Instrumentation topology changes become observable.** When a library upgrade starts emitting rolled-up parent usage, the collector's rejection rule fires and emits a `genai.usage.rollup_ambiguous` counter, surfacing the topology change at deploy time rather than as a mysterious cost-curve inflection weeks later. The residual risk is that leaf-only accounting loses the natural per-turn grouping that the agent span provided. This is recovered by joining leaf spans to their nearest `invoke_agent` ancestor via `trace_id`/`parent_span_id`, which is a query-time concern, not an attribute-placement concern — and keeping it at query time is what preserves the invariant. ```python from dataclasses import dataclass class UsageRollupAmbiguity(RuntimeError): """Raised when a span carries gen_ai.usage.* while its descendants also do, without an explicit rollup marker. Aggregating such a trace double-counts.""" @dataclass class Span: span_id: str parent_id: str | None operation: str # e.g. "invoke_agent", "chat", "execute_tool" attributes: dict # flattened OTel attributes rollup_marker: bool = False USAGE_KEYS = ( "gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens", "gen_ai.usage.total_tokens", ) def _has_usage(span: Span) -> bool: return any(k in span.attributes for k in USAGE_KEYS) def enforce_usage_invariant(spans: list[Span]) -> int: """Return the additive token total under leaf-only accounting. Rejects any trace where a parent span restates child usage without the explicit rollup marker, because summing it alongside leaf usage double-counts. """ by_id = {s.span_id: s for s in spans} def descendants(span: Span) -> list[Span]: out = [] for cand in spans: p = cand.parent_id seen = set() while p is not None and p not in seen: seen.add(p) if p == span.span_id: out.append(cand) break p = by_id.get(p).parent_id if p in by_id else None return out total = 0 for span in spans: if not _has_usage(span): continue if span.operation in ("invoke_agent", "execute_tool"): child_usage = [d for d in descendants(span) if _has_usage(d)] if child_usage and not span.rollup_marker: raise UsageRollupAmbiguity( f"span {span.span_id} ({span.operation}) carries " f"{[k for k in USAGE_KEYS if k in span.attributes]} while " f"{len(child_usage)} descendant(s) also carry usage; " f"summing would double-count. Set rollup_marker=True or drop " f"parent usage attributes." ) # Leaf-only accounting: only chat/text_completion contribute to the total. if span.operation in ("chat", "text_completion"): total += int(span.attributes.get("gen_ai.usage.total_tokens", 0)) return total # --- trace that reproduces the observed 2x failure --- trace = [ Span("root", None, "invoke_agent", {"gen_ai.usage.total_tokens": 4400}), Span("c1", "root", "chat", {"gen_ai.usage.total_tokens": 1200}), Span("c2", "root", "chat", {"gen_ai.usage.total_tokens": 800}), Span("c3", "root", "chat", {"gen_ai.usage.total_tokens": 2400}), ] try: enforce_usage_invariant(trace) except UsageRollupAmbiguity as e: # Expected: the rolled-up parent is rejected before it can be summed. print("rejected:", e) # Drop the parent's usage attributes (leaf-only) and re-run. for s in trace: if s.operation == "invoke_agent": s.attributes = {k: v for k, v in s.attributes.items() if k not in USAGE_KEYS} assert enforce_usage_invariant(trace) == 4400 ```