# Why does an instance's OTel GenAI span undercount tokens when a tool-call loop re-enters the same span context across a retry boundary **Date of Record:** 2026 November 28 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) and reuse a span context across retried or resumed LLM/tool invocations within one logical agent task. Does not apply to stateless single-shot inference where each call opens and closes its own span. ## Core Distinction The failure is not "tokens are missing from telemetry." It is that the GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as **cumulative attributes on a single span**, while a retry boundary re-enters the *same* span and *overwrites* rather than *accumulates* those attributes. The distinction that matters operationally: a span is an *event record*, but token usage is a *running counter*. When the runtime treats the span attribute as the counter, the last write wins, and every token burned by a failed attempt before the retry silently vanishes from accounting — while the wall-clock duration and the retry count both look correct. The trace is internally consistent and externally wrong. ## What Was Observed An agent tool-loop (plan → `gen_ai.tool.call` → observe → plan) was instrumented with one long-lived `gen_ai.chat` span per reasoning step, opened lazily on first model call and closed when the step produced a terminal action. A transient provider error (HTTP 529, model overloaded) triggered the runtime's retry wrapper, which re-invoked the model **inside the already-open span** because the span was owned by the step, not the call. Sequence observed in the exporter payload: 1. Attempt 1 opens span `S`, emits `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=0` (request accepted, response streamed partially, then connection reset mid-stream). Span remains open. 2. Retry wrapper fires after 400 ms backoff, re-enters `S`, calls model again. This time the instrumentation helper calls `span.set_attribute("gen_ai.usage.input_tokens", 1840)` and `span.set_attribute("gen_ai.usage.output_tokens", 612)` — **set**, not add. 3. Attempt 2 succeeds. Span `S` closes with `input_tokens=1840`, `output_tokens=612`. The billing ledger for the same window showed 3,680 input tokens consumed (two full prompt submissions) and 612 output tokens. The trace reported exactly half the input tokens. Because the failed attempt had already been billed by the provider (the prompt was tokenized and the request accepted before the reset), the undercount was a real 1,840-token delta per retry, and the runtime was under-retrying aggressively on the assumption that retries were "free" in budget terms. The same overwrite pattern reproduced on: mid-stream context-window-exceeded errors that trigger a compaction-and-retry, and on checkpoint-resume where a resumed agent re-opened the parent span context and re-emitted usage. ## Condition of Validity This undercount is *bounded and predictable* only under these conditions, and the guardrail below is only correct when all hold: - The span context is reused across attempts (span-per-step, not span-per-call). Span-per-call instrumentation is immune because each attempt gets a fresh span and the sum is recovered by the collector. - The instrumentation uses `set_attribute` (overwrite) rather than an explicit accumulator. OTel's `set_attribute` semantics are last-write-wins by spec; there is no built-in additive mode. - At least one failed attempt consumed billable tokens before failing. A failure *before* tokenization (e.g., connection refused, 401) consumes zero tokens and the overwrite is harmless. - `gen_ai.usage.*` is the accounting source of truth. If billing is reconciled from a separate provider ledger, the trace is merely misleading, not wrong; the invariant violation still corrupts any in-trace budget enforcement. If the runtime instead emits one child span per attempt under a `gen_ai.chat` parent, the invariant holds trivially and this article does not apply. ## Decision Boundary The boundary is: **does the retry wrapper own the span, or does the step own the span?** - If the *step* owns the span (long-lived, reused across attempts), you MUST maintain an explicit in-memory accumulator keyed by span context and flush the accumulated totals at span close, or emit a per-attempt child span and let the collector sum. Overwriting `gen_ai.usage.*` on a reused span is a correctness bug, not a style choice. - If the *call* owns the span (fresh span per attempt), overwrite is correct and the collector's `sum()` over child spans recovers the true total. Do not add an accumulator here — you will double-count. - The decisive test: does a retry increment the span count or the attribute value? If retries increment nothing but the attribute's final value, you are on the wrong side of the boundary. The architectural invariant required to bound this: **token accounting must be additive over the set of billable attempts, and the span-attribute representation must be a projection of that additive total, never the total itself.** Any code path where a retry can write `gen_ai.usage.*` without having read and re-added the prior value violates the invariant. ## Operational Effect Downstream consequences that propagate from the undercount: - **Budget enforcement drift.** A per-task token budget enforced by reading `gen_ai.usage.input_tokens` off the span will permit roughly `retry_count × prompt_tokens` of unbudgeted spend before tripping. Retry storms become invisible until the provider quota fails hard. - **Cost attribution skew.** Per-agent cost dashboards built on span attributes under-report exactly the agents that retry most — i.e., the flakiest agents look cheapest. - **Latency/token correlation breaks.** `gen_ai.usage.output_tokens / span_duration` inflates throughput for retried spans, so any anomaly detector keyed on tokens-per-second will *hide* the retry pathology it should surface. - **Verification replay divergence.** When an auditor agent replays a trace to re-derive cost, it recomputes from span attributes and gets a different number than the provider ledger — and the discrepancy is attributed to the auditor, not the instrumentation, because the trace "looks" well-formed. The fix is a guarded accumulator that refuses to let a reused span close with a usage attribute that was written more than once without an intervening accumulation, and that raises rather than silently overwriting. ```python from dataclasses import dataclass, field from typing import Dict, Tuple class TokenAccountingInvariantError(RuntimeError): """Raised when a reused GenAI span would overwrite cumulative usage.""" @dataclass class SpanTokenState: input_tokens: int = 0 output_tokens: int = 0 writes: int = 0 class GenAIUsageAccumulator: """ Enforces: token usage on a reused span context is additive over billable attempts. set_attribute-style overwrite on a span that has already recorded usage is a boundary violation and must fail loudly. """ def __init__(self) -> None: self._state: Dict[str, SpanTokenState] = {} def record_attempt( self, span_ctx: str, input_tokens: int, output_tokens: int, *, overwrite: bool = False, ) -> Tuple[int, int]: if input_tokens < 0 or output_tokens < 0: raise TokenAccountingInvariantError( f"negative token count on span {span_ctx!r}: " f"in={input_tokens} out={output_tokens}" ) st = self._state.setdefault(span_ctx, SpanTokenState()) if overwrite and st.writes > 0: raise TokenAccountingInvariantError( f"span {span_ctx!r} already recorded {st.writes} billable " f"attempt(s) (in={st.input_tokens}, out={st.output_tokens}); " f"refusing overwrite with in={input_tokens}, out={output_tokens}. " f"Emit a child span per attempt or accumulate additively." ) st.input_tokens += input_tokens st.output_tokens += output_tokens st.writes += 1 return st.input_tokens, st.output_tokens def close(self, span_ctx: str) -> Tuple[int, int]: st = self._state.get(span_ctx) if st is None: raise TokenAccountingInvariantError( f"closing span {span_ctx!r} with no recorded usage; " f"instrumentation gap or wrong span ownership" ) if st.writes == 0: raise TokenAccountingInvariantError( f"span {span_ctx!r} closed with zero billable attempts" ) return st.input_tokens, st.output_tokens ```