# When must an instance reconcile OpenTelemetry GenAI span token counts against the provider's billed usage, and why the naive sum of per-event `gen_ai.usage.*` attributes is not an invariant **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) for LLM invocations and tool calls, where token accounting is derived by summing per-span or per-event `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. Does not apply to systems that record only a single aggregated usage record per session from the provider's billing API, nor to non-streaming single-shot completions with no tool loops. ## Core Distinction There are two distinct quantities that both get labeled "token usage" in a GenAI trace: 1. **Attributable span usage** — the `gen_ai.usage.*` attributes stamped onto a *single* `gen_ai.chat` (or `gen_ai.text_completion`) span, describing the tokens consumed by that one model call. 2. **Billed session usage** — the provider's authoritative count for the whole interaction, which for a multi-turn tool-calling agent is *not* the arithmetic sum of (1). The boundary failure is treating (1) as additive. In a tool-using agent loop, each model turn re-sends the accumulated conversation (system prompt + prior assistant turns + every prior tool result). The provider bills the *input* tokens of turn *N* as the full re-serialized context, not the delta. So the sum of per-span `input_tokens` across *N* turns is a triangular number of the context size — it grows as O(N²) relative to the context, while the billed total is the same O(N²) quantity *only if* the provider does not deduplicate via prompt caching. When prompt caching is active, the billed input is `cached_tokens * cache_read_rate + uncached_tokens`, and the naive sum over-reports by the entire cached prefix re-sent on every turn. The invariant that actually holds is: **billed_input = Σ over turns of (uncached_input_turn) + cache_write_premiums + cache_read_discounts**, and this cannot be reconstructed from `gen_ai.usage.input_tokens` alone because the semantic conventions do not mandate a `gen_ai.usage.cached_input_tokens` attribute uniformly across providers, and several SDKs emit the *total* input (cached + uncached) in `input_tokens` while billing only the uncached portion. ## What Was Observed A three-tool agent (search → fetch → summarize) over a 12-turn loop. The trace emitted one `gen_ai.chat` span per model turn, each with `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. A downstream cost dashboard summed `input_tokens` across all spans and multiplied by the list input price. Observed trace-side sum: **412,880 input tokens**. Provider billing API for the same request window: **61,300 input tokens**, of which 48,000 were cache reads. The 6.7× discrepancy decomposed cleanly: - The agent re-sent a ~4,000-token system+tools preamble on all 12 turns → 48,000 span-attributed input tokens, but the provider served 48,000 of these as cache reads at 10% price and *did not* count them at full rate. The span attribute still reported them as `input_tokens` because the SDK's convention (and the OTel semconv at the time) folded cache reads into the input total. - The remaining span-attributed input (364,880) was genuine uncached context growth — but the provider's billing API *also* did not count the re-sent context as new input on turns where a cache hit occurred, so the billed uncached figure (13,300) was far below the span sum. - Output tokens matched exactly (span sum = billed = 9,140), because output is not cached and is not re-sent. The failure trace, step by step: 1. Turn 1: span `input_tokens=4,120`, billed `input=4,120`. Agreement. 2. Turn 2: span `input_tokens=8,340` (context grew by tool result), billed `input=340` (4,000 cache read, 340 new). **Divergence begins.** The span attribute is *total context sent*, the billed figure is *new uncached tokens*. 3. Turn 3–12: divergence compounds. Each turn's span attribute ≈ previous context + new tool result; each turn's billed input ≈ only the new tool result + new assistant reasoning, because the prior context is a cache read. 4. The dashboard's sum is now a running total of *context sizes*, not *billed tokens*. It diverges monotonically and the error is not a constant factor — it depends on cache hit rate, which depends on prefix stability, which depends on whether the tool result insertion point breaks the cacheable prefix. The non-obvious part: **the divergence is not a bug in the SDK or the provider.** Both are correct under their own definitions. The span attribute answers "how big was the context I sent," the billing API answers "how much did I charge you." The OTel GenAI semconv does not currently enforce a single definition of `gen_ai.usage.input_tokens` across providers, and several providers emit cache-inclusive totals while billing cache-exclusive. An agent that reconciles the two must know which definition its emitter uses. ## Condition of Validity The naive sum `Σ gen_ai.usage.input_tokens` is a valid cost proxy **only** when all of the following hold: - The agent performs a single model call per logical request (no tool loop, no re-send), **or** - The provider does not implement prompt caching (so every re-sent token is billed at full rate and the span attribute equals the billed amount), **or** - The emitter is configured to report `gen_ai.usage.input_tokens` as *cache-exclusive uncached input* and additionally emits `gen_ai.usage.cached_input_tokens`, and the reconciler applies the provider's cache pricing to the latter. If any of these fails, the sum is not a cost estimate — it is a context-size accumulator, and using it for budget enforcement or per-task attribution will systematically over-report and, worse, will *misattribute* cost to turns with large cached prefixes rather than turns with large new reasoning. The condition also breaks the other direction: if the emitter folds cache reads into `input_tokens` but the reconciler treats `input_tokens` as uncached (the common default), the trace *under*-reports cost on cache-heavy turns and the budget guardrail under-fires. ## Decision Boundary The reconciler must branch on a capability probe, not on a hardcoded assumption: - **If** the emitter advertises `gen_ai.usage.cached_input_tokens` (or a provider-specific equivalent such as `gen_ai.usage.cache_read_input_tokens`) **and** the provider's pricing model distinguishes cache reads, **then** compute `billed_input = (input_tokens - cached_input_tokens) + cached_input_tokens * cache_read_rate` and treat `input_tokens` as cache-inclusive. - **If** the emitter does not advertise a cache attribute, **then** do not attempt cache-aware reconciliation from span data alone; fall back to the provider billing API for any window longer than one turn, and mark the span-derived estimate as `unreconciled`. - **If** the span sum and the billing API disagree by more than a configured tolerance (e.g., 15%) on a window where a single model call was expected, **then** raise — this indicates either a cache-attribute misconfiguration or a tool-loop that was not accounted for in the cost model, and silently proceeding will corrupt the budget ledger. The boundary is sharp: a single-turn trace with no cache attribute is reconcilable; a multi-turn trace without a cache attribute is not reconcilable from spans and must be flagged. There is no middle ground where partial reconciliation is safe, because the error is multiplicative in turn count and cache hit rate, not additive. ## Operational Effect An agent that enforces a per-task token budget from the naive span sum will halt tasks that are well under budget (because the accumulator over-counts cached context) and will *fail to halt* tasks that are over budget when the cache is cold and the sum under-counts (because `input_tokens` was cache-exclusive but the reconciler priced it as uncached — the opposite misconfiguration). The two failure modes are symmetric and both silent: the budget check passes or fails on a number that has no fixed relationship to the bill. The correct operational posture is to treat `gen_ai.usage.*` span attributes as *diagnostic* (context growth, output length, per-turn latency correlation) and to treat the provider billing API as *authoritative* for cost, with a reconciliation job that joins the two on request ID and raises on divergence beyond tolerance. The span data remains essential for attribution *within* a task (which turn consumed which new tokens) but is not a substitute for the billed total. The guardrail is a reconciliation assertion, not a sum. The following module encodes it: it refuses to emit a cost figure from span data when the cache attribute is absent on a multi-turn trace, and raises a typed error when span-derived and billed figures diverge beyond tolerance. ```python from __future__ import annotations from dataclasses import dataclass from typing import Optional class TokenReconciliationError(RuntimeError): """Raised when span-derived token accounting cannot be reconciled to billed usage.""" @dataclass(frozen=True) class TurnUsage: turn_index: int input_tokens: int # as emitted on gen_ai.usage.input_tokens output_tokens: int cached_input_tokens: Optional[int] = None # gen_ai.usage.cached_input_tokens, if emitted @dataclass(frozen=True) class BilledUsage: input_tokens: int # authoritative, cache-exclusive uncached + cache reads at rate output_tokens: int def reconcile( turns: list[TurnUsage], billed: BilledUsage, cache_read_rate: float = 0.10, tolerance: float = 0.15, ) -> dict: """ Reconcile per-span GenAI usage against the provider's billed usage. Invariant enforced: billed_input is NOT the naive sum of per-turn input_tokens when prompt caching is active or when the agent re-sends context across turns. """ if not turns: raise TokenReconciliationError("no turns to reconcile") multi_turn = len(turns) > 1 has_cache_attr = all(t.cached_input_tokens is not None for t in turns) # Boundary: a multi-turn trace without cache attributes is not reconcilable # from span data alone -- the error is multiplicative, not additive. if multi_turn and not has_cache_attr: raise TokenReconciliationError( f"multi-turn trace ({len(turns)} turns) lacks gen_ai.usage.cached_input_tokens; " "span-derived cost would over-report cached-prefix re-sends. " "Use provider billing API as authoritative and mark estimate unreconciled." ) span_input = 0.0 for t in turns: if has_cache_attr: cached = t.cached_input_tokens or 0 uncached = t.input_tokens - cached if uncached < 0: raise TokenReconciliationError( f"turn {t.turn_index}: cached_input_tokens ({cached}) exceeds " f"input_tokens ({t.input_tokens}); emitter definition mismatch" ) span_input += uncached + cached * cache_read_rate else: # single-turn, no cache: span attribute is the billed amount span_input += t.input_tokens span_output = sum(t.output_tokens for t in turns) if span_output != billed.output_tokens: raise TokenReconciliationError( f"output mismatch: span={span_output} billed={billed.output_tokens}; " "output is never cached or re-sent, so this indicates a dropped span" ) denom = max(billed.input_tokens, 1) input_drift = abs(span_input - billed.input_tokens) / denom if input_drift > tolerance: raise TokenReconciliationError( f"input drift {input_drift:.1%} exceeds tolerance {tolerance:.0%}: " f"span_reconciled={span_input:.0f} billed={billed.input_tokens}; " "check cache_read_rate, cache-attribute presence, and tool-loop accounting" ) return { "span_reconciled_input": span_input, "billed_input": billed.input_tokens, "input_drift": input_drift, "output_tokens": span_output, "reconciled": True, } ```