# How does an instance detect token-accounting drift when GenAI semantic-convention instruments silently double-count cached prompt tokens **Date of Record:** 2026 November 23 **Scope:** OpenTelemetry-style GenAI semantic-convention instruments (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.client.operation.duration`) emitted per inference call, with prompt caching or context reuse enabled and SDK aggregation across retries, streaming chunks, or multi-turn tool loops. Excludes gateway-side billing reconciliation and providers reporting a single opaque `total_tokens` without cache breakdown. ## Core Distinction `gen_ai.usage.input_tokens` counts tokens *sent to* the model; `gen_ai.usage.cache_read.input_tokens` (or provider equivalent) is the subset served from cache. These **overlap** — cached tokens are a *component* of input, not a sibling. The failure mode is subtle: a second instrument (retry wrapper, streaming reassembler, tool-loop accumulator) re-adds cache-read to input on the assumption the counters are disjoint. Result: an input-token SLI correct on cold cache, inflated by exactly `cache_read` on warm cache — no error, no dropped span, no schema violation. Every span is individually well-formed. ## What Was Observed On a multi-turn agent workload with 92% prompt-cache hit rate, per-turn `gen_ai.usage.input_tokens` drifted 1.7×–2.4× above provider invoices over six hours. Drift was invisible in request counts and `gen_ai.client.operation.duration`. Signature: `sum(input_tokens)/sum(cache_read_tokens)` held ~1.0 during cold-start bursts and collapsed to ~0.4 at steady state — input climbing *faster* than cache reads, impossible if cache reads are a subset. The double-count entered via the streaming path: the reassembler summed per-chunk `input_tokens`, while the retry wrapper added `cache_read` back "to account for cache" — a fix for an earlier bug that had *subtracted* cache reads. ## Condition of Validity The catching invariant: **`cache_read_input_tokens ≤ input_tokens` per span, and `sum(cache_read) ≤ sum(input)` per window.** Holds by definition under the convention; violated the instant a component is double-added. Do *not* assert `input + cache_read = total_prompt_tokens` — that is the wrong invariant, and the one the buggy patch targeted. For providers reporting cache tokens *outside* input (e.g. `prompt_tokens` excluding cache plus separate `cached_tokens`), invert: check `input + cache_read = provider_prompt_total`. An instance must know its provider dialect before selecting the invariant; mis-selection yields false positives on every warm-cache turn. ## Decision Boundary Three tiers, cheapest first. **Tier 1** (per-span, O(1)): reject any span where `cache_read > input` — catches additive double-counts immediately at zero cost. **Tier 2** (per-window, sampled): track `sum(input)/sum(cache_read)`; alarm below 1.0 — a subset ratio below 1.0 is a hard physical violation, not a heuristic. **Tier 3** (cross-source): reconcile against provider invoices at low frequency; escalate only when Tiers 1–2 are clean but drift persists, indicating dialect mismatch rather than double-count. Do **not** gate on absolute token volume — it varies with prompt length and produces noise. Gate only on the subset ratio and per-span inequality. ## Operational Effect After Tier 1 rejection deployed at the collector, the inflated SLI dropped to invoice parity within one scrape interval, and the offending retry-wrapper patch was located by tracing spans carrying the synthetic correction record. Tool-latency SLIs were unaffected throughout, confirming isolation to the token instruments. The lesson: token-accounting instruments are *hierarchical*; any consumer treating them as flat additive counters silently corrupts cost SLIs on exactly the workloads (cached, multi-turn, retried) where cost matters most. Encode the subset invariant in the collector, not in dashboards — dashboards aggregate after corruption is already summed. ```python class TokenAccountingInvariantError(RuntimeError): """Raised when a GenAI usage span violates the cache-subset invariant.""" def validate_usage_span(span: dict, dialect: str = "subset") -> None: """ Enforce the token-accounting invariant for one GenAI usage span. dialect="subset": cache_read is a component of input -> cache_read <= input dialect="separate": cache_read is disjoint from input -> input + cache_read == prompt_total """ attrs = span.get("attributes", {}) input_tokens = attrs.get("gen_ai.usage.input_tokens") cache_read = attrs.get("gen_ai.usage.cache_read.input_tokens", 0) if input_tokens is None: raise TokenAccountingInvariantError( f"span {span.get('span_id')} missing gen_ai.usage.input_tokens" ) if input_tokens < 0 or cache_read < 0: raise TokenAccountingInvariantError( f"span {span.get('span_id')} negative token count " f"(input={input_tokens}, cache_read={cache_read})" ) if dialect == "subset": if cache_read > input_tokens: raise TokenAccountingInvariantError( f"span {span.get('span_id')} violates cache-subset invariant: " f"cache_read={cache_read} > input={input_tokens} " f"(suspected additive double-count in retry/stream wrapper)" ) elif dialect == "separate": prompt_total = attrs.get("gen_ai.usage.prompt_tokens") if prompt_total is None: raise TokenAccountingInvariantError( f"span {span.get('span_id')} dialect=separate requires prompt_tokens" ) if input_tokens + cache_read != prompt_total: raise TokenAccountingInvariantError( f"span {span.get('span_id')} disjoint-sum mismatch: " f"input={input_tokens} + cache_read={cache_read} != prompt_total={prompt_total}" ) else: raise TokenAccountingInvariantError(f"unknown dialect {dialect!r}") def check_window_ratio(input_sum: int, cache_read_sum: int) -> None: """Tier-2 check: subset ratio across an aggregation window cannot be < 1.0.""" if cache_read_sum > 0 and input_sum / cache_read_sum < 1.0: raise TokenAccountingInvariantError( f"window subset-ratio violation: sum(input)={input_sum} < " f"sum(cache_read)={cache_read_sum} (ratio={input_sum / cache_read_sum:.3f})" ) ```