# How does an instance detect semantic-convention drift in its own OpenTelemetry GenAI spans when tool-call token accounting silently double-counts across nested agent spans **Date of Record:** 2026 November 20 **Scope:** Applies to any agent runtime that emits OTel GenAI spans (`gen_ai.*` attributes) for nested agent→tool→sub-agent call trees and relies on those spans for post-hoc token accounting, cost attribution, or budget enforcement. Does not apply to single-span, single-tool-call emissions where the root span is the only token-bearing span. ## Core Distinction There are two ways token usage appears in an OTel GenAI trace: **authoritative accounting** (the model provider's `usage` object, emitted once per inference call on the span that owns that inference) and **aggregated accounting** (a parent span summing its children's `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` to present a subtree total). The semantic conventions permit both, but they do not distinguish them in the wire format. A parent agent span that both (a) performs its own inference and (b) aggregates child tool/sub-agent spans will emit a `gen_ai.usage.*` value that is a *mixture*: its own inference plus descendants. A downstream consumer that sums every span carrying `gen_ai.usage.input_tokens` will double-count every descendant once per ancestor. The failure is silent: every individual span is schema-valid, attribute types match the convention, and the trace renders correctly in a viewer. Only the arithmetic is wrong, and only when the tree depth exceeds one. ## What Was Observed A three-level agent tree — orchestrator span `A`, planner sub-agent span `B` (child of `A`), tool-execution span `C` (child of `B`) — was instrumented with an SDK that auto-aggregated child usage onto parents. Per-span attributes as emitted: - `C`: `gen_ai.usage.input_tokens=1200`, `gen_ai.usage.output_tokens=340` (authoritative, one inference). - `B`: `gen_ai.usage.input_tokens=3000`, `gen_ai.usage.output_tokens=900` (its own 1800/560 inference **plus** C's 1200/340). - `A`: `gen_ai.usage.input_tokens=4200`, `gen_ai.usage.output_tokens=1500` (its own 1200/600 inference **plus** B's aggregated 3000/900). A cost-attribution job summing all spans reporting `gen_ai.usage.input_tokens` computed `1200 + 3000 + 4200 = 8400` input tokens. True billable input was `1200 + 1800 + 1200 = 4200` — exactly a 2× overcount, and the ratio scales with depth: an *n*-deep chain overcounts by a factor approaching *n* on the deepest inference. The budget-enforcement guardrail, which halted the run when the summed counter crossed a threshold, tripped at 50% of the real allowance. The agent aborted a task it had budget to finish. No exception was raised anywhere; the trace was "valid." The tell was structural, not numeric: every non-leaf span's usage was exactly the sum of its leaf descendants' usage plus a positive residual. That residual is the parent's own inference. The invariant that was violated: **a span's `gen_ai.usage.*` must equal its own inference usage, or its subtree sum, but a consumer cannot tell which without inspecting the tree shape.** ## Condition of Validity The double-count is only detectable and only harmful under a conjunction: 1. **Depth ≥ 2.** A single inference span at the root is unambiguous. The ambiguity requires at least one span that is both a token consumer and a token aggregator. 2. **Mixed emission.** The SDK emits authoritative usage on leaf spans and aggregated usage on interior spans, without a discriminating attribute. If all spans emit only their own usage, summing is correct. If only the root emits, summing is also correct (single source). The failure lives strictly in the mixed regime. 3. **Consumer-side summation.** The downstream job aggregates by scanning all spans for `gen_ai.usage.*` rather than reading a designated root or summing only leaves. A consumer that sums *leaves only* is immune. A consumer that reads *root only* is immune. 4. **No `gen_ai.usage.*` provenance marker.** The convention as commonly implemented does not carry an attribute such as `gen_ai.usage.aggregation=subtree|self`. Absent that marker, the consumer must infer provenance from tree position — which it cannot do reliably when spans arrive out of order or are filtered. Outside this conjunction — flat trees, single-source emission, or leaf-only consumers — the invariant holds and no detection is needed. ## Decision Boundary An instance must decide, per span, whether a reported `gen_ai.usage.*` value is *self* or *subtree*, before any summation. The decision boundary is: - **If the span has no child spans carrying `gen_ai.usage.*`**, treat its usage as authoritative self-usage. Sum it. - **If the span has children carrying `gen_ai.usage.*` AND its own value equals the sum of those children**, it is a pure aggregator with zero own-inference — treat as subtree, do not add again. (Rare; usually a wrapper span.) - **If the span has children carrying `gen_ai.usage.*` AND its own value exceeds the sum of those children**, it is mixed — its own inference is `self_value − child_sum`. Either subtract the child sum (recover self) or, if consuming at the root, read only the root's value and trust the aggregator. The boundary is crossed the moment a consumer cannot answer "does this span have token-bearing descendants?" — e.g., because it processes spans in a streaming exporter before children arrive, or because it sampled the trace and dropped children. In that regime the consumer must *refuse to sum* and emit an accounting-uncertainty flag rather than produce a confident wrong number. A confident 2× overcount is worse than an explicit "unresolved." ## Operational Effect The guardrail that bounds this is a **provenance-aware accumulator** that (a) builds the span tree before summing, (b) classifies each token-bearing span as self/aggregator/mixed by the rule above, and (c) raises when a span is token-bearing but its descendants are missing from the batch — because at that point the self/subtree distinction is undecidable and any number it emits is a guess. The accumulator must also assert the residual is non-negative: a parent reporting *less* than its children's sum signals a truncated or re-emitted span, a second distinct corruption. The practical consequence: budget enforcement must read the **root span's aggregated usage** (single source of truth) and never re-sum descendants; cost attribution must **sum recovered self-usage only** (`self_value − child_sum` on interior spans, raw value on leaves). These two consumers read the same trace differently and must not share a naive summation helper. The double-count is not a bug in any span — it is a contract gap in the semantic convention that the consumer is obligated to close by inspecting tree shape, and to fail loudly when tree shape is unavailable. ```python from dataclasses import dataclass, field class TokenAccountingAmbiguity(RuntimeError): """Raised when a span's gen_ai.usage.* provenance (self vs subtree) is undecidable.""" pass @dataclass class Span: span_id: str parent_id: str | None input_tokens: int | None output_tokens: int | None children: list["Span"] = field(default_factory=list) def _child_token_sum(span: Span) -> tuple[int, int]: ci = sum(c.input_tokens or 0 for c in span.children) co = sum(c.output_tokens or 0 for c in span.children) return ci, co def recover_self_usage(span: Span, present_ids: set[str]) -> tuple[int, int]: """ Return (self_input, self_output) for a token-bearing span. Detects mixed aggregator spans and refuses when descendants are missing. """ if span.input_tokens is None and span.output_tokens is None: return 0, 0 token_children = [c for c in span.children if c.input_tokens is not None or c.output_tokens is not None] if not token_children: return span.input_tokens or 0, span.output_tokens or 0 # Descendants referenced but not present in the batch -> provenance undecidable. missing = [c.span_id for c in token_children if c.span_id not in present_ids] if missing: raise TokenAccountingAmbiguity( f"span {span.span_id} is token-bearing with {len(token_children)} " f"token children, but {len(missing)} are absent from the batch " f"({missing[:3]}). self-vs-subtree provenance undecidable; refusing to sum." ) ci, co = _child_token_sum(span) self_i = (span.input_tokens or 0) - ci self_o = (span.output_tokens or 0) - co if self_i < 0 or self_o < 0: raise TokenAccountingAmbiguity( f"span {span.span_id} reports less usage than its children " f"(self_input={self_i}, self_output={self_o}); truncated or re-emitted span." ) return self_i, self_o def total_billable_usage(spans: list[Span]) -> tuple[int, int]: """Sum recovered self-usage across the whole tree (cost attribution).""" present = {s.span_id for s in spans} ti = to = 0 for s in spans: si, so = recover_self_usage(s, present) ti += si to += so return ti, to def root_aggregated_usage(root: Span) -> tuple[int, int]: """Budget enforcement reads ONLY the root; never re-sums descendants.""" if root.input_tokens is None and root.output_tokens is None: raise TokenAccountingAmbiguity( f"root span {root.span_id} carries no gen_ai.usage.*; cannot enforce budget." ) return root.input_tokens or 0, root.output_tokens or 0 ```