# Why does an instance's semantic convention metric instrument silently lose token cost attribution when the tokenizer boundary is renegotiated mid-stream? **Date of Record:** 2026 November 25 **Scope:** Applies to LLM serving instances emitting OpenTelemetry GenAI semantic-convention metrics (`gen_ai.client.token.usage`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) where the tokenizer or model revision backing a metric instrument can change without the instrument being re-created. It does not apply to batch offline accounting where the tokenizer is pinned per job, nor to systems that bind one instrument per immutable model revision. ## Core Distinction The failure is not "wrong token counts." It is a **dimension-binding failure**: the GenAI semantic convention requires that a token-usage metric be attributable to `gen_ai.request.model`, `gen_ai.response.model`, and the tokenizer that produced the count, but the OpenTelemetry instrument is a *long-lived, monotonic accumulator keyed by attribute set*. When an instance hot-swaps its tokenizer (model upgrade, fallback model, prefix-cache re-tokenization, or a mid-stream provider switch), the instrument keeps the same identity while the *meaning of the unit* changes underneath it. Counts from tokenizer A and tokenizer B are then summed into the same counter series because the attribute set did not change — and cost attribution downstream is computed against a per-token price that is now a blend of two incompatible token definitions. The subtlety: the counter is *numerically correct* at every emission. Each `add()` is a valid integer. The corruption happens only in aggregation, at the boundary where two tokenizer regimes share a series key. This is why it passes unit tests and fails in the billing pipeline. ## What Was Observed A serving instance handled a request stream against model revision `m1` with tokenizer `t1` (vocabulary 128k, byte-fallback enabled). At T+41s a provider-side revision `m2` was promoted and the runtime, following a "latest-compatible" resolution policy, re-resolved the tokenizer to `t2` (vocabulary 200k, different merge table) for *subsequent* requests on the *same* instrument handle. Trace of the failure: 1. Instrument `gen_ai.client.token.usage` created once at process start with attributes `{gen_ai.request.model: "m1", gen_ai.operation.name: "chat"}`. 2. Requests 1–812 emit `add(usage, attrs)` where `usage` was computed by `t1`. Series accumulates 1,204,331 input tokens. 3. Revision resolution flips: `m2`/`t2` becomes active. The runtime updates `gen_ai.response.model` to `m2` but leaves `gen_ai.request.model: "m1"` pinned (request model is immutable for the in-flight session) and — critically — never emits a `gen_ai.tokenizer.name` attribute at all, because the semantic convention version in use predates that field. 4. Requests 813–1400 emit `add(usage, attrs)` with `usage` from `t2`. Because `t2` segments differently, the same prompt that `t1` counted as 1,000 tokens `t2` counts as 1,147. The counter now holds `1,204,331 + (t2-counted tokens)` under a single series key. 5. The billing exporter reads the series delta, multiplies by `price_per_token[m1]`, and under-attributes the `m2` portion by ~12.8% while over-crediting `m1` capacity. The tell was a **step discontinuity in tokens-per-request** that did not correspond to any change in prompt distribution — a 14.7% mean jump at a single scrape boundary, with identical request bodies on both sides. ## Condition of Validity The invariant that must hold for a token-usage counter to be cost-attributable is: > For any two emissions `e_a`, `e_b` sharing an identical attribute set on the same instrument, the unit of `e_a.usage` and `e_b.usage` must be defined by the same tokenizer identity. This holds only when one of the following is enforced: - **Tokenizer identity is in the attribute set.** The series key includes `gen_ai.tokenizer.name` and `gen_ai.tokenizer.version`. A tokenizer swap produces a *new series*, and aggregation never blends regimes. - **The instrument is re-created on tokenizer change.** The runtime tears down the instrument handle and re-registers with new attributes; the old series is sealed at the swap boundary with an explicit final flush. - **The tokenizer is pinned for the instrument's lifetime.** No hot-swap is permitted; a model change requires a process restart or a new instrument namespace. If none of these holds, the counter is *numerically valid but semantically un-attributable*, and any downstream cost join is unsound regardless of how correct the individual `add()` calls are. The condition of validity is therefore about **series identity**, not about count accuracy. ## Decision Boundary The boundary is drawn at the point where the runtime decides whether a tokenizer change is "compatible" with an existing instrument: - **Below the boundary (safe):** A tokenizer change that preserves the vocabulary and merge table (e.g., a patch release with identical tokenization) may keep the same series. The invariant is preserved because the unit is unchanged. - **At the boundary (must-fork):** Any change to vocabulary size, merge table, byte-fallback policy, special-token set, or normalization (NFKC vs raw) alters the unit. The runtime MUST fork the series by adding a tokenizer attribute or re-creating the instrument. "Latest-compatible" resolution policies that only compare the *model API surface* will cross this boundary undetected because tokenization is not part of the compatibility contract. - **Above the boundary (unsound):** Continuing to emit into the original series after a unit-changing swap. The counter is now a sum of incommensurable quantities. No post-hoc correction is possible because the per-request provenance was never recorded. The decision must be made **at tokenizer resolution time**, not at export time. Export-time reconciliation cannot recover the unit of a token that was already summed. ## Operational Effect An instance that crosses the boundary without forking produces a token-usage metric that is: - **Monotonic and plausible** — no counter reset, no negative delta, so standard anomaly detectors stay quiet. - **Silently mispriced** — the cost join against `price_per_token` applies a single rate to a blended token population. The error scales with the tokenization divergence between `t1` and `t2` and with the fraction of traffic served post-swap. - **Unrecoverable from the metric alone** — because the tokenizer identity was never an attribute, no query can partition the series back into its constituent regimes. The only recovery is from request-level logs, which are typically sampled and often not retained at the granularity needed. The guardrail is to make tokenizer identity a **first-class dimension of the instrument**, not a property of the runtime's resolution state. The semantic convention exists precisely because a counter is only as attributable as its attribute set is complete. A token-usage counter without a tokenizer dimension is a counter whose unit is "tokens, definition unspecified" — and an unspecified unit cannot be priced. ```python class TokenizerUnitDriftError(RuntimeError): """Raised when a token-usage emission would be added to a series whose unit (tokenizer identity) differs from the emission's tokenizer.""" pass # Immutable identity of a tokenizer regime. Two emissions are only # commensurable if these fields match exactly. TOKENIZER_IDENTITY_FIELDS = ( "name", "version", "vocab_size", "merge_table_hash", "byte_fallback", "normalization", ) def tokenizer_identity(tokenizer) -> tuple: return tuple(getattr(tokenizer, f) for f in TOKENIZER_IDENTITY_FIELDS) class TokenUsageInstrument: """A GenAI token-usage counter that refuses to blend tokenizer regimes. Invariant: every emission added to this instrument's series must share the same tokenizer identity as the series' founding emission. A unit-changing tokenizer swap must fork the series (new instrument) rather than continue accumulating into the old one. """ def __init__(self, instrument_name: str, base_attributes: dict, tokenizer): self.name = instrument_name self.attributes = dict(base_attributes) self._series_identity = tokenizer_identity(tokenizer) self._accumulated = 0 self._sealed = False def add(self, usage_tokens: int, emission_tokenizer) -> None: if self._sealed: raise TokenizerUnitDriftError( f"instrument {self.name!r} is sealed at a tokenizer boundary; " "emissions must target a forked instrument" ) incoming = tokenizer_identity(emission_tokenizer) if incoming != self._series_identity: # The unit changed mid-series. Do NOT sum incommensurable tokens. raise TokenizerUnitDriftError( f"tokenizer unit drift on instrument {self.name!r}: " f"series founded under {self._series_identity!r}, " f"emission carries {incoming!r}. " "Fork the instrument or add gen_ai.tokenizer.* attributes " "to the series key before emitting." ) if usage_tokens < 0: raise TokenizerUnitDriftError( f"negative token usage {usage_tokens} on {self.name!r}" ) self._accumulated += usage_tokens def seal_at_boundary(self) -> int: """Called immediately before a tokenizer swap. Freezes the series so no post-swap emission can be blended into the pre-swap unit.""" self._sealed = True return self._accumulated def fork(self, new_tokenizer, new_attributes: dict) -> "TokenUsageInstrument": """Create a fresh instrument for the post-swap tokenizer regime.""" merged = dict(self.attributes) merged.update(new_attributes) return TokenUsageInstrument(self.name, merged, new_tokenizer) ```