# Where must an instance reconcile OpenTelemetry GenAI span attribute cardinality before token accounting can be trusted across a multi-turn agent run **Date of Record:** 2026 December 3 **Scope:** Applies to agents emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where a single logical turn fans out into nested tool-call spans and the parent span's `gen_ai.usage.*` attributes are aggregated from child spans. Does not apply to single-shot inference calls with no tool fan-out, nor to spans emitted after the run has been sealed by an exporter with immutable attributes. ## Core Distinction The failure is not "missing telemetry." It is *attribute cardinality divergence between the parent turn span and its child tool-call spans* when the same logical token is counted at two layers. The GenAI conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of the span that represents the model invocation. In a multi-turn agent loop, engineers commonly do one of two things, and both are wrong in different ways: 1. **Aggregate upward.** The parent turn span sets `gen_ai.usage.*` to the sum of all child invocation spans. This double-counts, because each child already carries its own `gen_ai.usage.*`, so any downstream rollup (a collector `sum` aggregation, a billing pipeline) counts the tokens once per child plus once at the parent. 2. **Aggregate downward only.** Children carry usage; the parent carries none. This is correct per the spec but breaks any consumer that reads the parent span as the unit of cost, because `gen_ai.usage.*` is absent on the span that the trace UI and most dashboards key on. The non-obvious boundary: the convention does **not** define a `gen_ai.agent.turn` span kind or a canonical "this span's usage is authoritative, children are informational" flag. There is no `gen_ai.usage.aggregate` attribute in the spec. So the invariant that must hold — *exactly one span per logical token carries the count, and every other span that references the count is marked as a reference, not a source* — is unenforced by the schema and must be enforced by the emitting agent. ## What Was Observed A research agent running a 9-turn task emitted the following span tree on turn 6 (tool-heavy turn): - `invoke_agent` (parent, turn 6): `gen_ai.usage.input_tokens=4120`, `gen_ai.usage.output_tokens=610` - `execute_tool search` (child): `gen_ai.usage.input_tokens=0`, `gen_ai.usage.output_tokens=0` (correct — tools don't consume model tokens, but the emitter wrote zeros rather than omitting) - `chat` (child, the actual model call that decided to call the tool): `gen_ai.usage.input_tokens=3980`, `gen_ai.usage.output_tokens=140` - `chat` (child, the model call after tool result returned): `gen_ai.usage.input_tokens=4110`, `gen_ai.usage.output_tokens=470` The parent's `4120/610` was computed by the emitter as `max(child.input) + overhead` rather than `sum`, because the second `chat` call's input already includes the first call's output plus the tool result — the context is cumulative. The emitter's author had reasoned "the parent input is the largest context window seen," which is defensible as a *context-size* metric but is **not** what `gen_ai.usage.input_tokens` means. The convention's usage attributes are per-invocation consumption, and billing pipelines sum them. Result: the collector's `sum(gen_ai.usage.input_tokens)` over the trace returned `3980 + 4110 + 4120 = 12210` for a turn whose true billable input was `3980 + 4110 = 8090` (the two `chat` calls; the parent's number is a duplicate). A 51% overcount, silently, with no error surface. The overcount was discovered only when the daily cost dashboard diverged from the provider invoice by a factor that correlated with tool-call density. A second, subtler observation: the `execute_tool` span carried explicit zeros. Downstream `avg()` aggregations that filter `gen_ai.usage.input_tokens > 0` behaved correctly, but a `count()` of spans with the attribute present inflated the denominator, dragging per-call averages down. Omission and zero are not the same thing to an aggregator, and the spec does not say which to emit. ## Condition of Validity The invariant — *token counts are trustworthy iff exactly one span per model invocation carries `gen_ai.usage.*`, and no ancestor span re-emits an aggregate of descendants* — holds only under three conditions, all of which must be checked by the emitting agent before it seals the span: 1. **The parent turn span must not set `gen_ai.usage.*` at all** unless it represents a real model invocation. If the agent framework models the turn as a synthetic span wrapping N `chat` spans, the parent must omit usage attributes entirely, not set them to zero, not set them to a max, not set them to a sum. 2. **Non-model spans (tool execution, retrieval, routing) must omit `gen_ai.usage.*`**, not emit zeros. The convention's presence semantics are "this span consumed these tokens"; a zero is a claim of consumption of zero, which is a different and usually false statement for a tool span that triggered a model call elsewhere. 3. **Retry and streaming partials must not each emit usage.** A `chat` span that retried twice due to a 429 must carry usage for the successful attempt only, or carry a `gen_ai.usage.*` for each attempt under distinct child spans with the parent `chat` span omitting usage. The common bug is emitting usage on the retry wrapper *and* the final attempt. If any of these is violated, the trace is still structurally valid OTLP, still passes schema validation, and still renders in Jaeger — but every downstream sum is wrong, and the error is proportional to tool-call and retry density, which means it hides in low-activity traces and explodes under load. ## Decision Boundary The emitter must decide, at span-close time, one of three dispositions per span, and the decision is not recoverable after export because attributes are immutable once the span is sealed: - **Authoritative:** this span is a real model invocation. Set `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` to the provider-reported values for this call. Set `gen_ai.operation.name` to the invocation operation. Do not set usage on any ancestor. - **Structural:** this span organizes other spans (agent turn, tool fan-out, retry wrapper). Omit `gen_ai.usage.*` entirely. If a dashboard needs turn-level cost, it must compute it by summing descendant `chat` spans, not by reading the turn span. - **Reference:** this span cites a count owned elsewhere (e.g., a cached-context hit). Use a distinct, non-convention attribute such as `app.cache.hit_tokens` rather than overloading `gen_ai.usage.input_tokens`, so that a `sum` over the convention namespace does not pick it up. The boundary is crossed the moment an emitter writes a usage attribute on a span whose `gen_ai.operation.name` is not a model invocation, or writes an aggregate onto an ancestor. There is no schema-level guard; the guard must be a pre-seal assertion in the emitter. ## Operational Effect When the boundary is respected, `sum(gen_ai.usage.input_tokens)` over a trace equals the provider bill for that trace, and per-turn cost is recoverable by grouping on the turn correlation attribute and summing only `chat` spans. When it is crossed, the overcount is a multiplicative function of fan-out: an agent with mean 3.2 tool calls per turn overcounts by roughly that factor, and the factor drifts as the agent's tool-use policy changes — so a cost anomaly looks like a model regression, not a telemetry bug, and the investigation goes to the wrong layer for days. The recovery procedure is to re-derive the authoritative set: walk the trace, keep only spans where `gen_ai.operation.name` indicates a model invocation and `gen_ai.usage.*` is present, sum those, and compare against the parent aggregate. If the parent aggregate is present and non-zero, the trace is contaminated and must be re-emitted with the parent stripped — which requires the run to still be replayable, which it usually is not. Hence the guard must be at emit time. ```python import re class GenAIUsageCardinalityError(RuntimeError): """Raised when a span would emit gen_ai.usage.* in a way that double-counts tokens across the parent/child boundary of an agent turn.""" pass MODEL_OPS = {"chat", "text_completion", "generate_content", "embeddings"} def seal_span(span: dict, parent_span: dict | None) -> dict: """Enforce the authoritative/structural/reference invariant before export. span: dict with keys name, gen_ai.operation.name, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, and 'is_retry_wrapper'. parent_span: the enclosing turn span, or None for top-level invocations. """ op = span.get("gen_ai.operation.name") has_usage = ( "gen_ai.usage.input_tokens" in span or "gen_ai.usage.output_tokens" in span ) is_model = op in MODEL_OPS is_wrapper = span.get("is_retry_wrapper", False) or op in {"invoke_agent", "execute_tool"} # Rule 1: structural spans must not carry usage at all. if is_wrapper and has_usage: raise GenAIUsageCardinalityError( f"span {span['name']!r} op={op!r} is structural but carries " f"gen_ai.usage.*; this double-counts against child invocations" ) # Rule 2: model spans must carry usage, and must not be zero-filled placeholders. if is_model: if not has_usage: raise GenAIUsageCardinalityError( f"span {span['name']!r} op={op!r} is a model invocation " f"but omits gen_ai.usage.*; downstream sums will undercount" ) for k in ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens"): v = span.get(k) if v is not None and (not isinstance(v, int) or v < 0): raise GenAIUsageCardinalityError( f"span {span['name']!r} has non-integer or negative {k}={v!r}" ) # Rule 3: a parent turn span must never aggregate descendant usage. if parent_span is not None and parent_span.get("gen_ai.operation.name") not in MODEL_OPS: if "gen_ai.usage.input_tokens" in parent_span: raise GenAIUsageCardinalityError( f"parent span {parent_span['name']!r} carries a usage aggregate; " f"strip it before sealing child {span['name']!r}" ) # Rule 4: retry wrappers must not emit usage alongside the successful attempt. if span.get("is_retry_wrapper") and has_usage: raise GenAIUsageCardinalityError( f"retry wrapper {span['name']!r} must not carry usage; " f"emit usage only on the final attempt span" ) return span def rollup_trace(spans: list[dict]) -> dict: """Recompute authoritative usage by keeping only model-invocation spans.""" total_in = total_out = 0 for s in spans: if s.get("gen_ai.operation.name") not in MODEL_OPS: continue total_in += s.get("gen_ai.usage.input_tokens", 0) or 0 total_out += s.get("gen_ai.usage.output_tokens", 0) or 0 return {"input_tokens": total_in, "output_tokens": total_out} ```