# Which invariants prevent OpenTelemetry GenAI span hierarchies from silently double-counting tokens across agent handoffs **Date of Record:** 2026 November 19 **Scope:** Applies to agents instrumented with the OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where a parent agent span emits child spans for LLM invocations and tool calls, and where token usage is aggregated from child spans up to a root. Does not apply to single-span, single-LLM-call instrumentation with no span nesting, nor to billing systems that read provider-side usage directly rather than reconstructing it from traces. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of an *individual model invocation* span. They deliberately do **not** define an aggregation rule for a parent agent span that spans multiple invocations. This leaves a gap: an agent orchestrator span that wraps three LLM calls and two tool calls has no canonical token attribute, so implementers invent one. The failure is not that the numbers are wrong at the leaf — leaves are usually accurate. The failure is that the aggregation identity `parent_tokens = Σ child_tokens` is assumed to hold, and it silently breaks whenever a child span is *also* counted by a sibling path: retried calls, streaming partials that emit a second span on completion, tool spans that embed a nested LLM call (an LLM-as-judge inside a tool), or a handoff where the receiving agent re-emits the upstream usage as its own input. The core distinction: **leaf token attributes are observations; parent token attributes are derivations.** A derivation that is computed by summing descendants is only valid if the descendant set is a partition (no overlap, no duplication, covers exactly the work). The GenAI conventions never assert partitionhood, so the invariant must be enforced by the instrumentation layer. ## What Was Observed A retrieval-augmented agent was instrumented with a root span `agent.run`, child spans `gen_ai.chat` per model call, and `gen_ai.tool` spans for retrieval. A summarization tool internally called a second model to compress retrieved chunks. On a normal trace the root's derived `input_tokens` matched the provider bill. Under load, three anomalies appeared together: 1. A `gen_ai.chat` span that timed out was retried; both the failed and the successful attempt emitted spans with usage attributes. The provider billed once (the failed call returned no completion), but the derived root summed both, inflating input tokens by the full prompt length of the retry. 2. The summarization tool span carried `gen_ai.usage.*` because the inner model call was recorded *on the tool span itself* rather than as a nested `gen_ai.chat` child. The tool span was a descendant of the root, so its tokens were counted — correctly — but the inner call was *also* emitted as a separate child span by a second instrumentation library, so the same tokens were counted twice. 3. On a handoff to a sub-agent, the sub-agent's first `gen_ai.chat` span set `input_tokens` to the full conversation it received, which already included the parent's accumulated context. The parent root summed the sub-agent's input as new work. The trace looked structurally valid — every span had a parent, every usage attribute was a positive integer, no span was orphaned. The derived total was 2.3× the provider invoice. No error was raised anywhere. ## Condition of Validity The aggregation invariant `root.input_tokens = Σ_{leaf gen_ai.chat} input_tokens` holds **if and only if** all of the following are true: - **Partition:** every token-consuming model invocation is represented by exactly one span bearing usage attributes, and no span bearing usage attributes contains another such span as a descendant. This forbids usage attributes on `gen_ai.tool` spans that also emit a nested chat child. - **Attempt isolation:** retries and streaming completions produce at most one *counted* usage span per billed call. A failed attempt span must either carry zero usage or be marked with an attempt/status attribute that the aggregator excludes. - **Handoff non-duplication:** a receiving agent's first input span must not re-attribute context already counted by the sender. The convention's silence here means the receiver must either emit a `gen_ai.usage.input_tokens` of zero for the inherited prefix (counting only new tokens) or the aggregator must subtract a declared `inherited_tokens` attribute. - **Stable span identity:** the aggregator must key on `(trace_id, span_id)` and reject duplicate `span_id` values, because double instrumentation of the same call yields two spans with the same logical identity but different physical IDs. When any of these is violated, the sum is not merely noisy — it is *unbounded* in the direction of over-counting, and the error grows with retry rate and handoff depth, which are exactly the conditions present during incidents. That correlation is the operational hazard: the metric degrades precisely when you need it. ## Decision Boundary The boundary is between **trusting the tree** and **trusting a partition witness**. Below the boundary — shallow agents, single model call per span, no retries, no nested LLM-in-tool — summing descendants is safe because the tree happens to be a partition. Above the boundary, the instrumentation must carry an explicit witness that the descendant set is a partition, and the aggregator must verify it rather than assume it. Concretely, the decision rule for the instrumentation layer: - If a span both *contains* a `gen_ai.chat` descendant and *carries* `gen_ai.usage.*`, treat it as a **derived** span: strip its usage attributes at export, or tag it `gen_ai.usage.derived=true` and exclude from sums. - If two spans in the same trace share `(gen_ai.request.model, gen_ai.operation.name, parent_span_id)` and one has `gen_ai.response.finish_reasons` absent or an error status, treat the pair as an attempt pair and count only the terminal one. - If a handoff span (a `gen_ai.chat` whose `input_tokens` exceeds the parent's cumulative input by more than the delta of new tool results), require an `inherited_tokens` attribute; if absent, the aggregator must raise rather than sum. The boundary is *not* about accuracy tolerance. A 2% over-count from rounding is acceptable; a 130% over-count from double instrumentation is a correctness failure that corrupts capacity planning and cost attribution, and it is invisible without the witness check. ## Operational Effect Without the partition witness, three downstream systems break simultaneously and silently: - **Cost attribution** over-charges the agent that owns the root span, because retries and handoffs inflate its derived total, making per-agent budgets meaningless. - **Capacity autoscaling** keys on tokens-per-second derived from these spans; the inflated rate triggers scale-up during retry storms, which increases contention and retries, a positive feedback loop. - **Audit replay** cannot reconstruct the provider bill from the trace, so incident post-mortems cannot reconcile "what the agent did" against "what it cost." The guardrail is a single invariant enforced at export time: *a span that has a `gen_ai.chat` descendant must not export `gen_ai.usage.*`, and an aggregator must refuse to sum a trace in which any usage-bearing span has a usage-bearing descendant.* This is checkable in O(1) per span with a parent-pointer walk and catches all three observed anomalies. The check must run in the collector or SDK, not in the dashboard, because the dashboard sees post-aggregation numbers and cannot recover the tree. The following reference implementation encodes the invariant as a hard failure so that a violating trace is rejected at the boundary rather than silently summed. ```python from dataclasses import dataclass, field from typing import Optional class TokenAggregationViolation(RuntimeError): """Raised when a span tree cannot be summed under the partition invariant.""" @dataclass class GenAISpan: span_id: str parent_id: Optional[str] operation: str # "chat", "tool", "agent", ... input_tokens: Optional[int] = None output_tokens: Optional[int] = None status: str = "ok" # "ok" | "error" inherited_tokens: Optional[int] = None children: list["GenAISpan"] = field(default_factory=list) @property def carries_usage(self) -> bool: return self.input_tokens is not None or self.output_tokens is not None def _assert_partition(span: GenAISpan, seen_ids: set[str]) -> None: if span.span_id in seen_ids: raise TokenAggregationViolation( f"duplicate span_id {span.span_id!r}: double instrumentation of one call" ) seen_ids.add(span.span_id) usage_children = [c for c in span.children if c.carries_usage] if span.carries_usage and usage_children: raise TokenAggregationViolation( f"span {span.span_id!r} ({span.operation}) carries usage AND has " f"usage-bearing descendants {[c.span_id for c in usage_children]}: " f"tree is not a partition; strip derived usage or nest correctly" ) # Retry attempt pairs: same parent, same op, one errored -> count terminal only. by_parent: dict[Optional[str], list[GenAISpan]] = {} for c in span.children: if c.operation == "chat" and c.carries_usage: by_parent.setdefault(c.parent_id, []).append(c) for parent_id, group in by_parent.items(): if len(group) > 1 and all(g.status == "error" for g in group): raise TokenAggregationViolation( f"all attempts under parent {parent_id!r} errored but carry usage" ) for c in span.children: _assert_partition(c, seen_ids) def aggregate_tokens(root: GenAISpan) -> tuple[int, int]: """Sum leaf usage under the partition invariant; reject non-partitions.""" _assert_partition(root, set()) total_in = total_out = 0 def walk(s: GenAISpan) -> None: nonlocal total_in, total_out if s.carries_usage: # Handoff guard: a receiver must declare inherited context. if s.inherited_tokens is None and s.operation == "chat" and s.parent_id: parent = _find(root, s.parent_id) if parent is not None and parent.carries_usage: raise TokenAggregationViolation( f"handoff span {s.span_id!r} lacks inherited_tokens " f"but parent {parent.span_id!r} carries usage: " f"input would be double-counted" ) total_in += s.input_tokens or 0 total_out += s.output_tokens or 0 for c in s.children: walk(c) walk(root) return total_in, total_out def _find(root: GenAISpan, span_id: str) -> Optional[GenAISpan]: if root.span_id == span_id: return root for c in root.children: hit = _find(c, span_id) if hit is not None: return hit return None ```