# Which invariants prevent token-accounting drift from silently corrupting agent span trees under OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) for chat, tool, and agent-invocation operations, where a single logical turn fans out into nested spans across multiple model calls and tool executions. Does not cover single-span inference logging, nor telemetry pipelines that recompute token counts downstream from raw completions rather than trusting span attributes. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-span* attributes describing the usage of *that specific model invocation*. They are not, and were never specified to be, additive across a span tree. The failure mode this record isolates is the conflation of these two readings: an agent turn whose parent span (or an aggregating collector) sums child `usage.*` attributes as if they were disjoint, when in fact each child model call re-ingests the entire prior conversation context. The parent's true input cost is dominated by context re-transmission, but the naive sum undercounts it by orders of magnitude on multi-step turns, while a different naive sum (summing *all* spans including nested retries) overcounts by re-adding retried calls that never contributed to the final state. The invariant that must hold: **token attributes are leaf-local measurements of a single request/response pair, and any rollup must be a function of the leaf set that actually contributed to the committed response — never a blind `sum()` over the span subtree.** The distinction is between *span-tree arithmetic* and *causal-contribution arithmetic*; the two diverge precisely when there are retries, speculative branches, or context-replaying tool loops. ## What Was Observed A three-step agent turn (plan → tool call → synthesize) produced the following span tree, with `gen_ai.usage` attributes as emitted: ``` agent.turn (span_id=a1) no usage attrs ├─ chat plan (span_id=b1) input=1_800 output=120 ├─ tool.search (span_id=b2) no usage attrs (non-GenAI span) ├─ chat synthesize (span_id=b3) input=4_100 output=340 │ └─ chat synthesize.retry(span_id=b4) input=4_100 output=0 ← 429, zero output └─ chat verify (span_id=b5) input=5_900 output=60 ``` Three separate accounting errors appeared in the collector's rollup: 1. **Retry double-count.** The collector's `sum(gen_ai.usage.input_tokens)` over the subtree returned `1800+4100+4100+5900 = 15_900`. But span `b4` was a rate-limited retry whose prompt was transmitted, billed by the provider as input, but whose output was empty and whose result was discarded. Whether it counts depends on the question being asked ("what did we transmit?" vs. "what produced the committed answer?"). The convention provides no attribute to distinguish a discarded retry from a contributing call — `b4` carries identical `gen_ai.request.model` and `gen_ai.operation.name` to `b3`. 2. **Context-replay undercount.** The agent's *true* input cost for the turn is `1800 + 4100 + 5900 = 11_800` transmitted tokens (retry excluded), but the *unique* prompt content is only ~1_800 (the initial context) plus deltas. A dashboard computing "cost per turn" from the rollup reported `15_900`, a 35% overstatement driven entirely by the retry, while a second dashboard that deduplicated by `gen_ai.conversation.id` undercounted because `b3` and `b5` share a conversation but not a request. 3. **Orphaned tool attribution.** `tool.search` (`b2`) emitted no GenAI usage attributes, correctly — it is not a model call. But it consumed ~2_400 tokens of *retrieved content* that were then injected into `b3`'s prompt. That 2_400 tokens appear inside `b3.input_tokens` with no back-reference to `b2`. When `b3`'s span was sampled out (head-based sampling at 10%), the collector had no record that the turn's cost was inflated by retrieval, and attributed the entire `4_100` to "synthesis reasoning." The observed trigger was a single 429 on `b3`, followed by a head-sampled trace where the retry survived but the parent's sibling did not. The result was a token-cost dashboard that was internally consistent (all numbers summed correctly) and externally wrong (did not match provider invoice by 31% over a 24-hour window). ## Condition of Validity The naive `sum()` rollup is valid *only* when all of the following hold simultaneously: - No span in the subtree is a retry, speculative branch, or aborted call (i.e., every GenAI leaf contributed exactly one request/response to the committed output). - No GenAI span's `input_tokens` includes content sourced from a sibling non-GenAI span (retrieval, tool output injection) that the rollup intends to attribute separately. - Sampling is either complete or applied consistently to the whole subtree (no partial-subtree survival). - The question being answered is "total tokens transmitted across all model calls in this subtree," not "tokens attributable to the committed answer" or "unique prompt tokens." In practice, condition 1 fails on any turn with a provider rate limit or a validation retry; condition 2 fails on any RAG or tool-augmented turn; condition 3 fails under head-based sampling, which is the default in most SDKs. So the naive rollup is valid on a vanishingly small class of turns — essentially only single-shot, non-tool, non-retried calls, for which a span tree is overkill anyway. ## Decision Boundary The boundary is between **transmission accounting** and **contribution accounting**, and it must be decided at span-emission time, not at collector time, because the collector cannot reconstruct the distinction from the attributes the convention mandates. Concretely: - If a span represents a request that was *transmitted and billed* but whose response was *discarded* (retry, speculative decode that lost, validation failure), it must be marked so that contribution rollups exclude it while transmission rollups include it. The GenAI conventions do not currently define a standard attribute for this; the operational workaround is to set a span status of `ERROR` with a distinguishing `error.type` (e.g., `rate_limit`, `validation_rejected`) and require rollup functions to filter on it — but note that `error.type` is overloaded and a `rate_limit` retry that later succeeded is not an error of the turn. - If a GenAI span's input includes injected content from a sibling span, the attribution edge must be recorded explicitly (a span link to the tool/retrieval span, or a `gen_ai.prompt.injected_from_span_id` custom attribute), otherwise the tokens are unattributable once the sibling is sampled or evicted. - If sampling is head-based, the sampling decision must be made at the *turn root* and propagated to all descendants, so that partial-subtree survival cannot occur. Tail-based sampling keyed on turn completion is the only safe alternative. The invariant to enforce as a guardrail: **a token rollup over a span subtree is only meaningful relative to a declared `accounting_mode` of `transmitted` or `contributed`, and `contributed` rollups must exclude spans whose response was discarded and must resolve injected-content edges before summing.** Absent this, the number is arithmetic without semantics. ## Operational Effect The downstream effect is a class of silent cost-and-behavior mismeasurement that survives every consistency check because the arithmetic is correct and only the *referents* are wrong. Three concrete consequences observed: - **Budget enforcement drift.** A per-turn token budget computed from the rollup overcounts retried turns, causing the agent to throttle itself prematurely on exactly the turns where it was already struggling (rate-limited), amplifying the failure. The budget should be enforced against `contributed` tokens, not `transmitted`. - **Attribution blindness in sampled traces.** Under 10% head sampling, the tokens from an evicted retrieval sibling vanish, and per-operation cost attribution shifts toward whichever GenAI span survived, systematically over-attributing cost to reasoning and under-attributing to retrieval. - **Retry storms misread as efficiency gains.** A retry that returns empty output contributes `output_tokens=0`; a rollup that sums output tokens sees the turn as cheaper than a clean turn, inverting the cost signal during exactly the provider-degradation window where cost is rising. The guardrail that bounds all three: emit a turn-root span carrying the *committed* accounting (`gen_ai.usage.input_tokens` recomputed as the sum over contributing leaves only, with retries excluded and injected-content edges resolved), and treat child `usage.*` attributes as diagnostic leaf measurements that are never summed by consumers. The root span is the only place the `accounting_mode` is unambiguous, because only the root knows which leaves contributed to the committed response. ```python from dataclasses import dataclass, field from enum import Enum from typing import Iterable class TokenAccountingError(RuntimeError): """Raised when a span-tree token rollup cannot be resolved to a well-defined accounting mode (transmitted vs. contributed).""" class AccountingMode(Enum): TRANSMITTED = "transmitted" # every request that hit the wire, incl. discarded CONTRIBUTED = "contributed" # only leaves that produced the committed answer @dataclass class GenAISpan: span_id: str operation: str # e.g. "chat", "tool" input_tokens: int = 0 output_tokens: int = 0 discarded: bool = False # response not part of committed output (retry, lost spec) injected_from: tuple[str, ...] = () # sibling span_ids whose content entered this prompt children: list["GenAISpan"] = field(default_factory=list) def rollup_tokens(root: GenAISpan, mode: AccountingMode) -> int: """Sum token usage over a span subtree under a declared accounting mode. Invariant: CONTRIBUTED excludes discarded leaves and requires that every injected_from edge resolve to a span present in the subtree; otherwise the attribution is undefined and we must refuse rather than emit a wrong number. """ present = {s.span_id for s in _walk(root)} def visit(span: GenAISpan) -> int: if span.discarded and mode is AccountingMode.CONTRIBUTED: return 0 if mode is AccountingMode.CONTRIBUTED: for src in span.injected_from: if src not in present: raise TokenAccountingError( f"span {span.span_id} ingests content from {src!r}, " f"which is absent from the subtree; contribution " f"attribution is undefined (likely partial-subtree " f"sampling). Refusing to emit a rollup." ) total = span.input_tokens + span.output_tokens return total + sum(visit(c) for c in span.children) return visit(root) def _walk(span: GenAISpan) -> Iterable[GenAISpan]: yield span for c in span.children: yield from _walk(c) # Reproduces the observed turn: b4 is a discarded 429 retry, b3 ingests # retrieved content sourced from b2 (the tool.search span). turn = GenAISpan("a1", "agent.turn", children=[ GenAISpan("b1", "chat", input_tokens=1800, output_tokens=120), GenAISpan("b2", "tool"), GenAISpan("b3", "chat", input_tokens=4100, output_tokens=340, injected_from=("b2",), children=[ GenAISpan("b4", "chat", input_tokens=4100, output_tokens=0, discarded=True), ]), GenAISpan("b5", "chat", input_tokens=5900, output_tokens=60), ]) transmitted = rollup_tokens(turn, AccountingMode.TRANSMITTED) # 16_420 contributed = rollup_tokens(turn, AccountingMode.CONTRIBUTED) # 12_320 if contributed > transmitted: raise TokenAccountingError( "contributed tokens exceed transmitted tokens; accounting modes " "have been inverted or a discarded span leaked into the rollup." ) ```