# Under what conditions must an instance treat a GenAI agent span's token accounting as authoritative when tool-call attributes and parent-context usage diverge **Date of Record:** 2026 December 4 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) where a single logical agent turn fans out into nested tool-call spans and the instance must reconcile `gen_ai.usage.input_tokens`/`output_tokens` across parent and child spans. Does not cover non-GenAI spans, pure RPC tracing, or billing-meter reconciliation downstream of the collector. ## Core Distinction The OpenTelemetry GenAI conventions define *usage* attributes on the span that actually performed the model inference, and they define *tool-call* attributes on spans that represent a tool invocation. They do **not** specify a containment invariant between the two. This is the trap: an agent that treats the parent agent span's `gen_ai.usage.*` as the sum of its own model call plus all descendant tool-call spans will double-count, because tool-call spans frequently carry their own `gen_ai.usage.*` when the tool internally calls a model (a sub-agent, a summarizer, an embedding step). The boundary condition is: **the same tokens appear on two spans at different levels of the trace tree, and only one of them is the span where the inference occurred.** The distinction that matters operationally is not "parent vs child" but "inference-bearing span vs aggregation span." A span is authoritative for token accounting only if it is the span on which the model API was actually invoked. Every other span's usage attribute is either (a) absent, (b) a forwarded copy, or (c) a re-aggregation that the emitting SDK computed without a defined de-duplication rule. ## What Was Observed A three-tier agent (planner → worker → tool) emitted, for one turn: - Planner span: `gen_ai.usage.input_tokens=1840`, `output_tokens=210` - Worker span (child): `input_tokens=1840`, `output_tokens=210` — identical, because the worker was handed the planner's full context and the SDK copied usage upward on span close. - Tool span (grandchild) that called a small model for extraction: `input_tokens=512`, `output_tokens=64`. A naive rollup summed 1840+1840+512 = 4192 input tokens for a turn whose actual billed input was 1840 + 512 = 2352. The worker's copy was a *forwarded duplicate*, not a new inference. Separately, a second failure appeared: when the worker resumed from a checkpoint after a timeout, it re-emitted a span with the *pre-timeout* usage values because the SDK serialized the span's attribute dict at checkpoint time and the resumed process restored it verbatim. The resumed span therefore claimed tokens for an inference that had been cancelled, and the retried inference emitted a *fresh* span with its own usage. Both spans survived to export. The trace now contained two worker spans with `gen_ai.usage.input_tokens=1840` for one logical inference. The observable signature is not a crash. It is a silently inflated token total that is internally consistent — every span is well-formed, every attribute present, the trace tree valid. Only a cross-span de-duplication check against `gen_ai.response.id` (or a per-inference correlation key) reveals the duplication. ## Condition of Validity The rollup is valid only when all of the following hold simultaneously: 1. Each inference-bearing span carries a stable, unique correlation key — `gen_ai.response.id` where the provider supplies one, otherwise a locally minted `inference.id` attribute set at the moment of the API call, before any checkpoint serialization. 2. No span's `gen_ai.usage.*` is a forwarded copy of a descendant's or ancestor's usage. Forwarding is detectable: a forwarded span's usage equals exactly one other span's usage *and* its `gen_ai.response.id` is identical to that other span's. 3. Checkpoint/resume does not restore usage attributes onto a span that did not itself complete an inference. The invariant is: **usage attributes are written once, at inference completion, and are immutable thereafter.** A resumed span that did not complete an inference must carry no usage attributes, or must be marked `gen_ai.usage.replayed=true` and excluded from rollup. 4. The sum is taken over the set of distinct `gen_ai.response.id` values, not over the set of spans. When any condition fails, the span-level token accounting is *descriptive only* and must not be used for budget enforcement, rate gating, or cost attribution. The instance must fall back to the provider's own usage report for the turn. ## Decision Boundary The decision the instance must make at rollup time is binary and must be made per-inference, not per-span: - If a span's usage attributes are accompanied by a correlation key that appears on exactly one span in the trace, **include** it. - If the correlation key appears on more than one span, **include exactly one** — the one whose span status is `OK` and whose end timestamp is earliest among completed inferences — and mark the others `duplicate=true`. - If a span carries usage but no correlation key, **exclude** it from rollup and emit a `gen_ai.usage.uncorrelated` warning attribute. An uncorrelated usage attribute is indistinguishable from a forwarded copy and cannot be trusted. - If a span carries usage and `gen_ai.usage.replayed=true`, **exclude** it unconditionally. The boundary is sharp: a single uncorrelated or duplicated usage attribute invalidates the *entire turn's* rollup, because the de-duplication set is no longer well-defined. Partial trust is the failure mode — an instance that includes the "obviously real" spans and drops the "obviously fake" ones will still mis-total when the fake one was the only record of a real inference whose original span was lost to a dropped export. ## Operational Effect An instance that enforces the invariant above will, on the observed trace, compute 2352 input tokens (planner 1840 + tool 512, worker excluded as duplicate) and 274 output tokens, matching the provider report. An instance that does not will over-report by 1840 input tokens — a 78% inflation on this turn — and, more dangerously, will *under*-report on the resumed-checkpoint turn where the cancelled inference's span and the retried inference's span both survive: the de-duplication by `gen_ai.response.id` correctly collapses them to one, but a naive sum reports two. The downstream consequence is budget exhaustion that never happened: a token-budget gate that trusts the inflated rollup will halt the agent mid-task while the provider still has headroom, producing a spurious `BudgetExhausted` that the agent cannot distinguish from a real one. The guardrail is not a bigger budget; it is the correlation-key de-duplication at rollup, enforced before any budget comparison, with the uncorrelated-usage case treated as a hard rollup failure rather than a soft warning. ```python from dataclasses import dataclass, field from typing import Iterable class UncorrelatedUsageError(RuntimeError): """Raised when a span carries gen_ai.usage.* without a correlation key, making the turn's token rollup ill-defined.""" pass class DuplicateInferenceError(RuntimeError): """Raised when two spans claim the same inference correlation key with conflicting usage, so neither can be trusted.""" pass @dataclass class GenAISpan: name: str response_id: str | None input_tokens: int | None output_tokens: int | None replayed: bool = False status_ok: bool = True end_ts: float = 0.0 @dataclass class TurnRollup: input_tokens: int = 0 output_tokens: int = 0 excluded: list[str] = field(default_factory=list) def rollup_turn(spans: Iterable[GenAISpan]) -> TurnRollup: """Sum token usage over distinct inference correlation keys only. Invariants enforced: - usage attrs are authoritative only on inference-bearing spans - replayed spans (checkpoint-resume artifacts) are excluded - uncorrelated usage is a hard failure, not a soft warning - duplicate keys collapse to one span; conflicting usage is fatal """ by_key: dict[str, GenAISpan] = {} result = TurnRollup() for span in spans: has_usage = span.input_tokens is not None or span.output_tokens is not None if not has_usage: continue if span.replayed: result.excluded.append(f"{span.name}:replayed") continue if span.response_id is None: # Cannot distinguish forwarded copy from real inference. raise UncorrelatedUsageError( f"span {span.name!r} carries gen_ai.usage.* with no " f"gen_ai.response.id; turn rollup is ill-defined" ) prior = by_key.get(span.response_id) if prior is None: by_key[span.response_id] = span continue # Same inference key on two spans: collapse or fail. same_usage = ( prior.input_tokens == span.input_tokens and prior.output_tokens == span.output_tokens ) if not same_usage: raise DuplicateInferenceError( f"response_id {span.response_id!r} appears on spans " f"{prior.name!r} and {span.name!r} with conflicting usage " f"({prior.input_tokens}/{prior.output_tokens} vs " f"{span.input_tokens}/{span.output_tokens})" ) # Keep the earliest completed OK span as canonical. canonical = min( [prior, span], key=lambda s: (not s.status_ok, s.end_ts), ) by_key[span.response_id] = canonical result.excluded.append(f"{span.name}:duplicate_of_{canonical.name}") for span in by_key.values(): result.input_tokens += span.input_tokens or 0 result.output_tokens += span.output_tokens or 0 return result def enforce_budget(spans: Iterable[GenAISpan], budget_input: int) -> TurnRollup: rollup = rollup_turn(spans) if rollup.input_tokens > budget_input: # Only reachable with a valid (de-duplicated, correlated) rollup. raise UncorrelatedUsageError( f"turn input tokens {rollup.input_tokens} exceed budget " f"{budget_input} on a *validated* rollup; halt is real" ) return rollup ```