# Which invariants prevent OpenTelemetry GenAI agent spans from double-counting child tool-call tokens during mid-trace context handoff **Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) across a parent agent span and nested tool-call spans, where a sub-agent or tool invocation performs its own LLM call whose token usage is attributed back to the trace. Does not cover single-span, single-model-call instrumentation, nor non-OTel tracing backends that flatten spans. ## Core Distinction The GenAI semantic conventions define token usage attributes as *per-LLM-call* measurements, not per-span-tree aggregates. The convention places `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` on the span that *wraps the model invocation*. When an agent delegates to a sub-agent that itself makes model calls, two structurally valid instrumentations exist and they are **not** interchangeable: 1. **Leaf attribution** — the sub-agent's model call gets its own span carrying its own `gen_ai.usage.*`; the parent agent span carries only the tokens from *its own* model calls. 2. **Rollup attribution** — the parent span carries the sum of all descendant model calls, and descendants carry none (or carry them but are marked so aggregators exclude them). The failure mode is a *mixed* trace: some spans emit leaf usage, some emit rolled-up usage, and the span processor / backend aggregator has no way to distinguish them. The result is silent multiplication of token counts, which then corrupts cost accounting, budget circuit-breakers, and any downstream rate limiter keyed on `gen_ai.usage.input_tokens`. Unlike a latency double-count (which is bounded and obvious), token double-counting is unbounded across nesting depth and invisible in the trace topology. ## What Was Observed During a mid-task handoff, an orchestrator agent (span `agent.orchestrator`, `gen_ai.operation.name=invoke_agent`) invoked a retrieval sub-agent (span `agent.retriever`) which made two model calls, then returned control. The orchestrator then made one final synthesis model call. The sub-agent instrumentation used a "rollup" pattern: it summed its two model calls and wrote the total onto `agent.retriever` as `gen_ai.usage.input_tokens=4200, output_tokens=610`. It did *not* emit child `gen_ai.operation.name=chat` spans for its two model calls — those were suppressed to reduce span volume. The orchestrator instrumentation used a "leaf" pattern: it emitted a `gen_ai.operation.name=chat` child span for its own synthesis call (`input_tokens=9800`) and, because it received the sub-agent's returned usage metadata in the handoff payload, also wrote the sub-agent's reported tokens onto its own `agent.orchestrator` span as `gen_ai.usage.input_tokens=9800+4200=14000`. The backend aggregator, keyed on `gen_ai.operation.name in {chat, invoke_agent}` and summing `gen_ai.usage.input_tokens` over all spans, computed: ``` agent.orchestrator input_tokens = 14000 (includes sub-agent's 4200) agent.retriever input_tokens = 4200 (its own rollup) chat (synthesis) input_tokens = 9800 ----- reported total = 28000 actual total = 14000 ``` A 2.0× overcount, and the multiplier grows with nesting depth: each level that both rolls up *and* has a child that also rolls up re-adds the same subtree. At depth 3 with uniform rollup-plus-parent-mirror, the observed overcount was 4.1× on a production trace. The trace looked structurally correct. No span was orphaned, no parent-child link was broken, timestamps were monotonic. The only signal was a cost dashboard anomaly flagged three hours later when the per-task token budget tripped a circuit breaker that should not have fired. ## Condition of Validity The invariant that prevents this is a **single-attribution invariant**: > For any trace, each model-call token must appear in `gen_ai.usage.*` on exactly one span, and that span must be identifiable by a stable discriminator. The convention's discriminator is `gen_ai.operation.name`. A span with `gen_ai.operation.name=chat` is a model-call span; a span with `gen_ai.operation.name=invoke_agent` is an agent span. The invariant holds only if: - Every actual model call produces a `chat` span carrying its own usage, **and** agent spans (`invoke_agent`) carry usage only for model calls that have no `chat` child span — or carry none at all. - Aggregators sum over `chat` spans only, and treat `invoke_agent` usage as *advisory* (for display), never as additive. - Handoff payloads that transport usage metadata (e.g., A2A task results, MCP tool results) are treated as *observations*, not as authorization to re-emit `gen_ai.usage.*` on the receiving span. The condition fails whenever a single instrumentation library is allowed to choose its attribution mode per-call rather than per-trace. Mixed-mode traces are the trigger. The overcount is not a bug in any single span; it is a violation of the cross-span invariant, which no individual span can detect because each span only sees its own attributes. A second, subtler validity condition: `gen_ai.usage.input_tokens` must be *cumulative for the model call it wraps*, not incremental per streaming chunk. Instrumentations that emit a `chat` span at stream start and patch usage on each chunk produce a span whose final attribute value depends on span-end ordering — if the span is exported before the final chunk's usage patch lands, the recorded value is a prefix of the true value, undercounting. This is the inverse failure and shares the same root cause: usage is treated as mutable span state rather than as an immutable event payload. ## Decision Boundary The boundary is **where in the span tree the usage is materialized**. Three regimes: - **Materialize-at-leaf (safe).** Usage written on the `chat` span at the moment the model call completes, before span end, immutable thereafter. Agent spans carry no `gen_ai.usage.*`. Aggregator sums `chat` spans. Handoff payloads may carry usage for display but the receiver must not write it to `gen_ai.usage.*`. - **Materialize-at-agent (safe only if exclusive).** Usage written on `invoke_agent` spans, and *no* `chat` child spans are emitted for the same calls. Aggregator must sum `invoke_agent` spans only and must not also sum `chat`. This regime is valid but fragile: any library upgrade that starts emitting `chat` spans silently converts it to the double-count regime. - **Mixed (unsafe).** The observed failure. No aggregator query can recover the true total without knowing, per span, which regime produced it — information the trace does not carry. The decision rule: **an instrumentation library must commit to one regime for the entire trace, and must declare it.** The declaration is a resource attribute, e.g. `gen_ai.usage.attribution_mode = "leaf" | "agent_rollup"`, set once at tracer-provider construction and propagated to every span. An aggregator that sees more than one distinct value of this attribute in a trace must refuse to sum and emit a `usage_attribution_conflict` diagnostic rather than a number. ## Operational Effect Without the single-attribution invariant and its declaration, three downstream systems corrupt: 1. **Budget circuit-breakers** fire on phantom tokens. In the observed incident, a 14000-token task tripped a 20000-token per-task ceiling at 2× inflation. The breaker is correct given its input; its input is wrong. Retries then re-run the task, re-emitting the same inflated trace, and the breaker latches open — a self-sustaining outage driven purely by observability. 2. **Cost attribution** to tenants/features is inflated by a depth-dependent multiplier, so the most deeply nested (and usually most valuable) agent workflows appear the most expensive, inverting prioritization. 3. **Rate limiters** keyed on `gen_ai.usage.input_tokens` throttle healthy agents. Because the inflation multiplier is a function of nesting depth, not of load, throttling is uncorrelated with actual provider pressure — the limiter sheds the wrong traffic. The guardrail is a validation pass at span-processor exit: for each completed trace, group spans by `gen_ai.usage.attribution_mode`; if cardinality > 1, drop all `gen_ai.usage.*` attributes from `invoke_agent` spans, retain only `chat` span usage, and emit a single `usage_attribution_conflict` event with the trace ID. This degrades to the safe leaf regime and makes the conflict visible instead of silent. ```python from dataclasses import dataclass, field from typing import Iterable class UsageAttributionConflict(RuntimeError): """Raised when a trace mixes leaf and agent-rollup token attribution.""" @dataclass class Span: name: str operation: str # gen_ai.operation.name attributes: dict = field(default_factory=dict) def usage(self) -> tuple[int, int]: return ( int(self.attributes.get("gen_ai.usage.input_tokens", 0)), int(self.attributes.get("gen_ai.usage.output_tokens", 0)), ) def reconcile_trace_usage(spans: Iterable[Span]) -> tuple[int, int]: spans = list(spans) modes = { s.attributes.get("gen_ai.usage.attribution_mode") for s in spans if "gen_ai.usage.attribution_mode" in s.attributes } if len(modes) > 1: raise UsageAttributionConflict( f"trace mixes attribution modes {sorted(modes)}; " f"refusing to sum gen_ai.usage.*" ) mode = next(iter(modes), "leaf") if mode == "leaf": contributing = [s for s in spans if s.operation == "chat"] elif mode == "agent_rollup": contributing = [s for s in spans if s.operation == "invoke_agent"] else: raise UsageAttributionConflict(f"unknown attribution mode {mode!r}") if not contributing: raise UsageAttributionConflict( f"mode={mode!r} but no contributing spans found in trace" ) tin = sum(s.usage()[0] for s in contributing) tout = sum(s.usage()[1] for s in contributing) return tin, tout # Reproduces the observed incident: orchestrator mirrors sub-agent usage. trace = [ Span("agent.orchestrator", "invoke_agent", {"gen_ai.usage.input_tokens": 14000, "gen_ai.usage.attribution_mode": "leaf"}), Span("agent.retriever", "invoke_agent", {"gen_ai.usage.input_tokens": 4200, "gen_ai.usage.attribution_mode": "agent_rollup"}), Span("chat.synthesis", "chat", {"gen_ai.usage.input_tokens": 9800, "gen_ai.usage.attribution_mode": "leaf"}), ] try: reconcile_trace_usage(trace) except UsageAttributionConflict as e: # Correct behavior: refuse to emit a number, surface the conflict. print(f"usage_attribution_conflict: {e}") ```