# Which invariants prevent tool-call span attribution from silently double-counting tokens across nested GenAI spans **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for LLM inference and tool execution, where a single logical turn may nest a parent chat span around child tool-call spans that themselves trigger further inference. Does not apply to single-shot, non-nested inference telemetry or to pure transport-level tracing without GenAI attributes. ## Core Distinction The failure is not "missing spans" or "broken export." It is **attribution ambiguity under nesting**: the GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of a chat span, and separately define tool-call spans. When an agent loop executes `model -> tool -> model`, the second model call is a *new* inference whose prompt contains the tool result. If the runtime models this as one parent span with `gen_ai.usage.*` set on the parent *and* on each child chat span, the same tokens are counted at two levels of the span tree. Aggregators that sum `gen_ai.usage.input_tokens` across all spans in a trace — the natural Prometheus/OTLP rollup — then report input tokens roughly equal to the sum of every prompt in the loop, not the tokens billed. The distinction that matters: **a span attribute is a per-operation fact, not a per-subtree aggregate**, and the conventions do not forbid a parent from carrying usage attributes even when children also carry them. ## What Was Observed A three-step agent turn (`plan -> call search tool -> synthesize`) produced a trace with four spans: one root `invoke_agent`, one `chat` for planning, one `execute_tool` for search, one `chat` for synthesis. The root span was populated by a wrapper that copied the *terminal* chat span's `gen_ai.usage.*` onto the root for "convenience." The synthesis chat span also carried its own usage. A dashboard summing `gen_ai.usage.input_tokens` grouped by `service.name` reported 2.4× the provider's billing figure for the same window. The trace-level mechanics: 1. Planning chat span: `input_tokens=1820`, `output_tokens=140`. 2. Tool span: no usage attributes (correct). 3. Synthesis chat span: `input_tokens=2410` (includes tool result), `output_tokens=310`. 4. Root `invoke_agent` span: wrapper copied synthesis usage — `input_tokens=2410`, `output_tokens=310`. Sum across spans = 6640 input tokens. Actual billed input = 4230. The duplication is exactly the synthesis span's usage, mirrored onto the root. Worse, when a retry occurred, the retried chat span was emitted as a sibling rather than a child, so its usage was *also* summed — a second, independent double-count path through retry semantics rather than nesting. A subtler variant surfaced with streaming: the runtime emitted `gen_ai.usage.output_tokens` incrementally as partial counts on span events, then finalized the attribute at span end. Aggregators reading span events mid-flight and the finalized attribute both counted the same output tokens. ## Condition of Validity The invariant that must hold for token sums to be meaningful: > **Exactly one span per logical inference operation carries `gen_ai.usage.*`, and that span is the leaf-most span whose operation is that inference. No ancestor span and no event within the span may carry the same usage.** This is valid only when: - The emitting runtime distinguishes *operation spans* (a chat completion, a tool execution) from *coordination spans* (`invoke_agent`, workflow wrappers) and never copies usage upward. - Retries are modeled as child spans of the operation span (or as span events with distinct `retry.attempt` attributes excluded from default aggregation), never as siblings that both carry usage. - Streaming partial usage is emitted only as span *events* marked non-authoritative, or not at all until finalization; the finalized attribute is the single source of truth. - The aggregator's query is scoped to spans where `gen_ai.operation.name` is a leaf operation (`chat`, `text_completion`, `embeddings`), not to all spans bearing `gen_ai.*`. Outside these conditions — e.g., a vendor SDK that stamps usage on every span it touches — the invariant is unenforceable at the collector and must be enforced at emission. ## Decision Boundary The boundary is **whether a span's usage attribute describes the operation the span *is*, or the subtree the span *contains***. The GenAI conventions are written for the former. Any wrapper that treats a coordination span as a container for usage crosses the boundary and creates an aggregatable duplicate. Concrete decision rules: - If a span has child spans with `gen_ai.operation.name` set, the parent MUST NOT carry `gen_ai.usage.*`. Enforce with a collector-side validation rule that drops or flags the attribute. - If a retry occurs, the retried attempt is a child of the original operation span; only the attempt that produced the returned completion carries authoritative usage, or all attempts carry usage with `gen_ai.request.attempt` set and the aggregator filters to `attempt=0` or sums deliberately. - If usage is unknown at span end (provider omitted it), emit the attribute as absent, not zero — zero is a value and will skew averages downward while absent is excluded. - Streaming partial counts are events, never attributes, until finalization. ## Operational Effect Enforcing the leaf-only invariant changed the reported input-token total from 6640 to 4230 for the sample turn — a 36% overcount eliminated without touching the provider. The retry double-count was eliminated by re-parenting retried attempts, which also fixed a latency-attribution bug (retry latency had been attributed to the parent, inflating p99 for the coordination span). The residual risk is *under*-counting: if a runtime stops copying usage to the root but the root was the only span exported in some sampling configuration (e.g., a tail-sampling policy that keeps root spans and drops children), usage vanishes entirely. The guardrail is to make the leaf operation span the sampling anchor — always-keep spans where `gen_ai.operation.name` is set — so the authoritative usage is never the one dropped. The invariant is therefore two-sided: usage lives on exactly one span, and that span is guaranteed to survive sampling. ```python from dataclasses import dataclass, field from typing import Optional class UsageAttributionError(RuntimeError): """Raised when gen_ai.usage.* attributes violate the leaf-only invariant.""" @dataclass class GenAISpan: span_id: str parent_id: Optional[str] operation_name: Optional[str] # gen_ai.operation.name, None for coordination spans input_tokens: Optional[int] = None output_tokens: Optional[int] = None attempt: int = 0 children: list = field(default_factory=list) def validate_usage_attribution(spans: dict[str, GenAISpan]) -> int: """Return authoritative input-token total; raise on invariant violation. Invariants enforced: 1. A span with gen_ai.operation.name set must not carry usage if any descendant also carries usage (no ancestor/descendant double-count). 2. Usage on a retried attempt (attempt > 0) must not be summed with attempt 0 unless explicitly requested; we reject ambiguous siblings. 3. Absent usage is None, never 0, so averages exclude unknown spans. """ by_id = {s.span_id: s for s in spans.values()} def descendants(span: GenAISpan): for child_id in span.children: child = by_id[child_id] yield child yield from descendants(child) authoritative = 0 for span in by_id.values(): carries_usage = span.input_tokens is not None or span.output_tokens is not None if not carries_usage: continue if span.operation_name is None: raise UsageAttributionError( f"coordination span {span.span_id} carries gen_ai.usage.*; " f"usage must live on the leaf operation span only" ) for desc in descendants(span): if desc.input_tokens is not None or desc.output_tokens is not None: raise UsageAttributionError( f"span {span.span_id} and descendant {desc.span_id} both carry " f"gen_ai.usage.*; aggregation would double-count tokens" ) if span.attempt > 0: raise UsageAttributionError( f"retried attempt span {span.span_id} carries usage as a sibling; " f"re-parent under the original operation span or filter by attempt" ) authoritative += span.input_tokens or 0 return authoritative ```