# What happens when an instance's semantic-convention token counter diverges from the model's actual billing meter mid-run **Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that emits GenAI semantic-convention telemetry (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.usage.total_tokens`) as a proxy for budget enforcement, context-window management, or cost reconciliation. Does not apply to runtimes that read authoritative usage directly from the provider response object on every call and never cache a derived counter. ## Core Distinction The GenAI semantic conventions define token *attributes* as observability signals — point-in-time facts attached to a span. They do not define a *ledger*. The moment an agent runtime promotes `gen_ai.usage.total_tokens` from a per-span attribute into a running accumulator that gates behavior (context compaction, budget cutoffs, handoff decisions), it silently converts an observation into an invariant. That invariant is false, because the semantic-convention counter is a *reconstruction* of provider-side accounting, not the accounting itself. The non-obvious part: the divergence is not a bug in the counter. It is structural. Semantic-convention token counts are almost always derived from one of three lossy sources — a local tokenizer approximating the provider's, a cache-aware formula that the provider does not expose symmetrically, or a sum of per-message estimates that ignores the provider's per-request overhead (system prompt framing, tool-schema tokens, image/audio normalization, hidden reasoning tokens). Each source drifts in a *different direction* depending on payload shape, so the accumulator can be simultaneously over-counting visible turns and under-counting the true bill. ## What Was Observed A long-running agent (a code-repair loop) enforced a 128k context ceiling by accumulating `gen_ai.usage.total_tokens` across turns and compacting at 90% of the ceiling. The runtime also enforced a per-task cost cap by summing the same attribute. After ~40 turns of tool use, two failures appeared *together but in opposite directions*: 1. **Context compaction fired late.** The local tokenizer under-counted tool-result payloads (large JSON blobs with repeated keys tokenize more efficiently under the provider's BPE than the local approximation predicted). The accumulator read ~112k when the provider's actual prompt was ~134k. The next call returned a context-length error, not a compaction. The span still carried `gen_ai.usage.total_tokens = 112k` — the telemetry *agreed with the wrong number*. 2. **The cost cap tripped early.** The same accumulator summed *cached* input tokens at full price because the semantic-convention attribute does not distinguish cache-read from cache-write tokens in older convention versions. The derived spend crossed the cap while the provider's authoritative meter was ~30% below it. The agent aborted a task it could have finished. The trace showed a clean, monotonic accumulator that was wrong in both directions at once — because the errors were payload-shape-dependent, not random. This is the signature of a *reconstruction* masquerading as a *measurement*. ## Condition of Validity The accumulator-as-ledger is valid only when all three hold: - **Source identity:** every counted token originates from a provider response field (`usage.prompt_tokens`, `usage.completion_tokens`, and their cache/reasoning sub-fields), never from a local tokenizer or an estimate. - **Shape stability:** the payload's tokenization behavior is stable across turns — no mid-run switch in tool-schema size, no image/audio attachments, no reasoning-token-emitting model swap. - **Symmetry:** the counter's notion of "billable" matches the provider's, including cache reads, cache writes, and hidden reasoning tokens. Violating *any* one breaks the invariant. In practice, long agent runs violate all three: they cache the counter, they mutate payload shape via tool results, and they rarely model cache asymmetry. ## Decision Boundary The correct boundary is not "trust the counter" or "don't." It is: **the semantic-convention counter may gate *soft* decisions (when to summarize, when to warn) but must never gate *hard* decisions (hard context cutoff, hard budget abort, handoff commit).** Hard decisions must read the authoritative per-response `usage` object at the moment of the call, or re-derive from a provider-reported total on each request. Concretely: - **Soft gate (allowed):** trigger a *pre-emptive* compaction when the counter crosses 80% of the ceiling — leaving headroom for the known under-count. - **Hard gate (forbidden on the counter):** refuse a call or abort a task based solely on the accumulator. The hard gate must consult the last authoritative response's `usage` and, if unavailable, fail *open* with a logged discrepancy rather than fail *closed* on a reconstructed number. The asymmetry of consequences drives this: a late compaction costs a retry; an early abort costs a task. The reconstructed counter's error direction is unpredictable per payload, so hard gates must not depend on it. ## Operational Effect Runtimes that promote the semantic-convention counter to a ledger exhibit a characteristic failure signature: **bidirectional drift with monotonic confidence** — the accumulator never decreases, never self-corrects, and the telemetry looks healthy while behavior is wrong in both directions. The fix is architectural, not a tokenizer patch: 1. Treat `gen_ai.usage.*` as observability only; never as the source of truth for gating. 2. On every provider response, overwrite (not add to) a per-call authoritative total; reconcile the accumulator against it and log the delta as a first-class metric (`token_counter_drift`). 3. Hard context and budget gates read the authoritative total from the *most recent* response plus a conservative headroom margin sized to the observed p99 drift. 4. Emit the drift metric with the payload shape (tool-schema bytes, attachment count, model id) so drift is attributable rather than mysterious. The invariant to enforce: **no hard decision may be taken on a number that was reconstructed rather than reported.** Everything else is headroom sizing. ```python class SemanticCounterDivergence(RuntimeError): """Raised when a reconstructed token accumulator is used to gate a hard decision.""" # Conservative headroom as a fraction of the ceiling, sized to observed p99 drift. DRIFT_HEADROOM = 0.15 def enforce_hard_context_gate( accumulated_semconv_tokens: int, authoritative_last_response_tokens: int | None, ceiling: int, ) -> None: """ Hard gate: may only fire on an authoritative number. Falls open (logs + allows) when authority is missing, because a late compaction costs a retry while an early abort costs the whole task. """ if authoritative_last_response_tokens is None: # No authority this turn: do NOT abort on the reconstructed counter. return effective = authoritative_last_response_tokens + int(ceiling * DRIFT_HEADROOM) if effective >= ceiling: raise SemanticCounterDivergence( f"authoritative={authoritative_last_response_tokens} " f"accumulated_semconv={accumulated_semconv_tokens} " f"ceiling={ceiling}: hard context gate tripped on reported usage" ) def reconcile_accumulator( accumulated_semconv_tokens: int, authoritative_last_response_tokens: int, ) -> int: """Overwrite, never add. Returns drift for the token_counter_drift metric.""" drift = authoritative_last_response_tokens - accumulated_semconv_tokens return drift ```