# Why does an instance emit a GenAI span with `gen_ai.usage.input_tokens` that disagrees with the tool-call children it spawned, and what invariant does this break? **Date of Record:** 2026 November 30 **Scope:** Applies to instrumented LLM agents emitting OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where a single agent span wraps one or more tool-call child spans and reports aggregated token usage. Does not apply to single-shot, tool-free inference spans where no child spans exist and usage is reported exactly once by the provider adapter. ## Core Distinction The failure is not "wrong token count." It is a **conservation violation across the span tree**: the parent agent span's `gen_ai.usage.input_tokens` is set to the *last* provider response's usage rather than the *sum* over all provider round-trips the agent performed, while the child tool-call spans remain correctly attributed. The invariant being broken is the **token accounting conservation law**: for any agent span `A` with provider round-trips `R1..Rn`, `A.usage.input_tokens = Σ Ri.input_tokens`, and this sum must be reconcilable against the union of tool-call child spans' `gen_ai.tool.call.*` attributes plus the final synthesis turn. When an SDK auto-instruments the LLM client and a separate agent framework opens the parent span, the two instrumentation layers each believe they own the usage attribute. The last writer wins, and "last" is the final synthesis turn—the smallest of the round-trips—so the parent span systematically under-reports by the entire tool-calling phase. The distinction that matters operationally: this is a **double-ownership collision on a non-idempotent attribute**, not a sampling or export bug. The span exists, exports cleanly, passes schema validation, and is internally consistent with the *last* turn only. It is invisible to schema validators and only surfaces under cross-span reconciliation. ## What Was Observed A three-tool agent run (search → fetch → synthesize) produced a parent span with: ``` gen_ai.operation.name = "invoke_agent" gen_ai.usage.input_tokens = 1_412 gen_ai.usage.output_tokens = 388 gen_ai.request.model = "claude-3-5-sonnet" ``` and three child spans. The first two children were tool-call spans (`gen_ai.tool.name = "web_search"`, `"http_fetch"`) with no usage attributes (correct—tools don't consume LLM tokens). But the trace also contained *three* nested `gen_ai.operation.name = "chat"` spans, one per provider round-trip, because the LLM client auto-instrumentation opened a chat span for each `messages.create` call: | Round-trip | input_tokens | output_tokens | |---|---|---| | R1 (plan + tool_use) | 9_204 | 611 | | R2 (post-tool reasoning) | 11_877 | 702 | | R3 (final synthesis) | 1_412 | 388 | The parent agent span reported `1_412`—exactly R3. Sum over chat children: `22_493` input, `1_701` output. The parent under-reported input by **93.7%**. The reconciliation job that compared `parent.usage` to `Σ child_chat.usage` fired a `TokenConservationViolation` alert on every multi-turn agent trace, which was then muted because "it always fires." That muting is the real incident: the invariant was real, the violation was real, and the response was to suppress the detector rather than fix the attribute. The mechanism: the agent framework's span processor set usage on `on_end` of the *agent* span by reading `response.usage` from the object returned by the final `messages.create`. The LLM client instrumentation independently set usage on each *chat* span from the same response objects. Both were "correct" locally. Neither owned the aggregation. ## Condition of Validity The conservation law holds—and the detector is meaningful—only under these conditions: 1. **Single provider adapter.** If multiple adapters (e.g., an Anthropic client and an OpenAI client) both emit chat spans under one agent span, the sum is still valid but the parent must aggregate across adapters, which no single adapter's `on_end` hook can do. 2. **No streaming usage gaps.** With streaming, `usage` may arrive only in the terminal `message_delta` event; if the stream is cancelled mid-flight (token-budget exhaustion, client disconnect), that round-trip contributes tokens that were *consumed* but never *reported*. The conservation law then holds against *billed* usage but not against *observed* usage. The invariant must be stated as `parent.usage ≥ Σ observed_child.usage` with a separate `unreported_round_trips` counter, or it will produce false positives on every cancelled stream. 3. **No retries inside the adapter.** An adapter that retries a 529 and succeeds will emit two chat spans (or one, depending on whether it suppresses the failed attempt). If it suppresses, the failed attempt's prompt tokens are billed but invisible; the parent cannot recover them from children. Retry accounting must be surfaced explicitly via `gen_ai.request.retry_count` on the chat span, not silently dropped. 4. **Caching semantics declared.** Prompt-cache reads (`cache_read_input_tokens`) are billed at a different rate and are *not* additive with `input_tokens` in the same way across providers. The conservation law must be restated per-provider: `input_tokens` excludes cache reads on Anthropic, includes them on some others. A naive sum across providers double-counts. Where these conditions fail, the detector must degrade to a *per-round-trip* check (each chat span's usage matches its own response) rather than a *tree-sum* check. ## Decision Boundary The boundary is **who owns the aggregate attribute**. Three viable architectures, each with a different failure surface: - **Adapter-owns-aggregate (rejected).** The LLM client adapter accumulates usage across calls within an agent context and writes it to the parent on agent-span end. Fails because the adapter has no reliable signal for "agent span boundary"—it sees `messages.create` calls, not agent lifecycle. It will over-aggregate across sibling agents sharing a process. - **Framework-owns-aggregate (the observed failure).** The agent framework writes usage from the final response. Fails as shown: it captures only the last turn. - **Span-processor-owns-aggregate (correct).** A dedicated `SpanProcessor` on the tracer provider intercepts `on_end` for chat spans, maintains a per-`trace_id`+`parent_span_id` accumulator, and on the agent span's `on_end` writes the summed usage. This is the only layer that sees both the children and the parent, and it can enforce the conservation law as a *guard*: if the parent's pre-existing usage attribute disagrees with the accumulator, emit a `gen_ai.usage.reconciliation_mismatch` event and either overwrite (authoritative accumulator) or flag (advisory). The decision boundary for *alerting*: fire `TokenConservationViolation` only when `parent.usage.input_tokens < Σ child_chat.usage.input_tokens` **and** the deficit exceeds the largest single round-trip (which is the signature of "last-turn-only" capture). A small deficit is normal stream-cancellation loss; a deficit equal to "everything except the final turn" is the double-ownership bug. Distinguishing these two requires the deficit *shape*, not just its magnitude. ## Operational Effect Downstream consumers of the parent span's usage attribute—cost dashboards, per-agent budget enforcers, token-budget-exhaustion circuit breakers—all operate on a number that is 10–90% too low for any multi-tool agent. The budget enforcer in particular will *never* trip, because it reads the parent span, so an agent that burns 22k input tokens per task appears to burn 1.4k and runs 15× past its configured ceiling before the provider-side 429 (if any) intervenes. The failure is silent, monotonic in tool-call count, and worst for exactly the agents that most need budget control: long-horizon, many-tool runs. The guardrail is a span-processor-level accumulator with an explicit reconciliation event, plus a detector keyed on deficit *shape* rather than magnitude. The following enforces the invariant at the point where both parent and children are visible: ```python from dataclasses import dataclass, field from typing import Dict, Tuple class TokenConservationViolation(RuntimeError): """Raised when an agent span's reported usage under-reports its chat children.""" @dataclass class UsageAccumulator: # key: (trace_id, parent_span_id) -> [input_tokens, output_tokens, round_trips] _acc: Dict[Tuple[str, str], list] = field(default_factory=dict) def record_chat(self, trace_id: str, parent_span_id: str, input_tokens: int, output_tokens: int) -> None: key = (trace_id, parent_span_id) slot = self._acc.setdefault(key, [0, 0, 0]) slot[0] += input_tokens slot[1] += output_tokens slot[2] += 1 def reconcile_agent(self, trace_id: str, span_id: str, reported_input: int, reported_output: int, max_single_round_trip: int) -> Tuple[int, int]: slot = self._acc.pop((trace_id, span_id), None) if slot is None: # No chat children observed: agent may be tool-free or uninstrumented. return reported_input, reported_output summed_in, summed_out, n = slot deficit_in = summed_in - reported_input deficit_out = summed_out - reported_output # Deficit whose shape matches "last-turn-only capture" is the double-ownership bug. if deficit_in > max_single_round_trip or deficit_out > max_single_round_trip: raise TokenConservationViolation( f"agent span {span_id} under-reports usage: " f"reported=({reported_input},{reported_output}) " f"children_sum=({summed_in},{summed_out}) over {n} round-trips; " f"deficit=({deficit_in},{deficit_out}) exceeds max single round-trip " f"{max_single_round_trip} — likely last-turn-only attribute capture" ) # Otherwise: small deficit is stream-cancellation loss; accumulator is authoritative. return summed_in, summed_out ```