# How does an instance detect silent token-accounting drift when OTel GenAI spans decouple from the model's own usage ledger **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) per LLM call and tool call, and that also maintains a separate authoritative usage ledger (provider billing counters, local tokenizer re-counts, or per-turn budget accounting). Does not cover tracing-only deployments where no independent ledger exists to reconcile against, nor streaming partial-usage cases where the provider emits usage only at stream close. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes on the span describing a model invocation. They are *observational*: they describe what the instrumentation layer *believes* happened. They are not a settlement mechanism. The failure mode that matters operationally is not "the span is missing" — missing spans are loud. It is **drift**: the span reports a token count that is internally plausible, well-formed, non-negative, and monotonic across the trace, yet diverges from the model's actual consumption by a margin that compounds across a multi-step agent loop. A span that says `input_tokens=4096` when the true prompt was 6,120 tokens passes every schema check, every dashboard threshold, and every attribute-presence assertion. The instance has no signal unless it explicitly cross-checks the span against a second, independent count. This is a boundary condition, not a bug class. It lives exactly at the seam between *what the instrumentation recorded* and *what the model actually billed*. ## What Was Observed A tool-using agent loop (planner → tool call → synthesizer, repeated up to N steps) emitted one `gen_ai.chat` span per model call and one `gen_ai.execute_tool` span per tool invocation, all parented to an agent-level span carrying `gen_ai.agent.name` and `gen_ai.operation.name=agent`. The instrumentation computed `input_tokens` by counting the *serialized message array* it handed to the client. The provider, however, re-tokenized the same array after applying its own chat template (role markers, tool-schema injection, special tokens), which added a template-dependent overhead of roughly 300–1,400 tokens per call that grew with the number of tool definitions in the request. The observed trace was clean. Per-span token counts were positive, integer, and summable. The agent-level span aggregated child usage by summation and reported a total. Nothing in the attribute set was absent or malformed. Yet over a 7-step run, the summed span total under-reported true consumption by ~18%, and the divergence was *not constant* — it was largest on steps where the tool schema was widest, i.e., the steps most likely to hit context limits. The error was structured, correlated with the very variable (context pressure) that the metric was supposed to guard. A second, orthogonal observation: when a tool call failed and the agent retried, the retry emitted a fresh `gen_ai.execute_tool` span but the *model call* that produced the retry decision was sometimes instrumented with the pre-retry prompt (cached message array) rather than the post-failure prompt that actually included the error text. The span's `input_tokens` reflected the stale serialization. Two spans, same `gen_ai.operation.name`, honest-looking counts, one of them describing a prompt that was never sent. ## Condition of Validity The invariant that must hold for span-based accounting to be trustworthy is: > For every model invocation `i`, `span_i.gen_ai.usage.input_tokens + span_i.gen_ai.usage.output_tokens` equals the provider's reported usage for that invocation within a fixed tolerance `ε`, and the *per-step* residual `r_i = actual_i − reported_i` is bounded, not merely the aggregate. Aggregate equality is insufficient and is the trap. A loop that over-reports on early steps and under-reports on late steps can sum to zero while every individual span is wrong. The condition of validity is therefore **per-span residual bounding with a stable sign**, checked at emission time, not at trace-close time. If `|r_i| > ε` for any span, the span is a lie regardless of the trace total. This holds only when: (a) a second independent count exists (provider usage payload, or a re-tokenization using the *post-template* serialization), and (b) the instrumentation captures the exact bytes sent, not a cached or reconstructed message array. When either is absent — e.g., a provider that omits usage on some responses — the invariant is undecidable and the instance must mark the span `gen_ai.usage` as *estimated*, a distinct state from *measured*. ## Decision Boundary The instance crosses from "trusted telemetry" to "drifted telemetry" at the first span where the residual exceeds `ε` **and** the sign of the residual is consistent with a known template-overhead or stale-serialization signature. The decision the runtime must make at that boundary: - If residual is positive (actual > reported) and correlates with tool-schema width → template-overhead drift. The span under-reports; any budget guard driven by span totals is running blind and will let the context window saturate before the guard fires. Action: switch budget enforcement to the independent ledger, and downgrade span usage to advisory. - If residual is negative or sign-flips across steps → stale-serialization drift. The instrumentation is describing a prompt that was not sent. Action: halt, because the trace is now actively misleading an auditor replaying the run. - If residual is within `ε` but the span carries no `gen_ai.usage` at all → undecidable, not zero. Action: mark estimated, never coalesce into a measured total. The boundary is not "error rate exceeded." It is "the residual acquired a *signature*," which is what makes it detectable at all. ## Operational Effect Without per-span residual bounding, the failure is silent and self-concealing: the under-reporting is worst exactly when the agent is closest to context exhaustion, so the budget guard that should trip first is the one being lied to. The agent runs until the provider hard-rejects an over-length prompt mid-loop, losing the in-flight tool state and forcing a cold restart — which then re-emits the same drifted instrumentation and repeats. With the invariant enforced at emission, the instance gains a cheap detector: it does not need to trust the span, only to reconcile it. The reconciliation cost is one tokenizer pass per call (or one provider-usage field read), and the payoff is that the sign of the residual becomes an operational signal — template drift vs. stale serialization vs. undecidable — each with a distinct remediation. The guardrail is not "emit accurate tokens" (the instrumentation cannot always know the template overhead); it is "never let a span's usage attribute be consumed as authoritative without a signed residual check against the ledger." The following reference implementation encodes the invariant as a hard boundary: it raises when a span's reported usage cannot be reconciled with the independent ledger within tolerance, and it distinguishes the three drift signatures in the exception payload so the caller can route remediation. ```python from dataclasses import dataclass from enum import Enum from typing import Optional class DriftSignature(Enum): TEMPLATE_OVERHEAD = "template_overhead" # actual > reported, correlates with schema width STALE_SERIALIZATION = "stale_serialization" # sign flips or actual < reported UNDECIDABLE = "undecidable" # no independent count available class TokenAccountingDriftError(RuntimeError): """Raised when a GenAI span's usage attributes cannot be reconciled with the independent usage ledger within tolerance.""" def __init__(self, span_id: str, reported: int, actual: int, signature: DriftSignature, epsilon: int): self.span_id = span_id self.reported = reported self.actual = actual self.residual = actual - reported self.signature = signature self.epsilon = epsilon super().__init__( f"span {span_id}: reported={reported} actual={actual} " f"residual={self.residual} signature={signature.value} eps={epsilon}" ) @dataclass class SpanUsage: span_id: str input_tokens: int output_tokens: int estimated: bool = False @property def total(self) -> int: return self.input_tokens + self.output_tokens def classify_residual(residual: int, schema_width: int, prior_residuals: list[int]) -> DriftSignature: if residual > 0 and schema_width > 0: return DriftSignature.TEMPLATE_OVERHEAD if residual < 0 or (prior_residuals and (residual > 0) != (prior_residuals[-1] > 0)): return DriftSignature.STALE_SERIALIZATION return DriftSignature.UNDECIDABLE def reconcile_span( span: SpanUsage, ledger_actual: Optional[int], schema_width: int, prior_residuals: list[int], epsilon: int = 64, ) -> int: """Enforce per-span residual bounding. Returns the residual if within tolerance; raises TokenAccountingDriftError otherwise. Aggregate-only reconciliation is deliberately NOT performed here: a zero-sum trace with per-span drift is still rejected.""" if span.estimated or ledger_actual is None: # Undecidable is a distinct state from measured-zero; never coalesce. raise TokenAccountingDriftError( span.span_id, span.total, -1, DriftSignature.UNDECIDABLE, epsilon, ) residual = ledger_actual - span.total if abs(residual) > epsilon: signature = classify_residual(residual, schema_width, prior_residuals) raise TokenAccountingDriftError( span.span_id, span.total, ledger_actual, signature, epsilon, ) return residual def enforce_trace(span_usages: list[SpanUsage], ledger_totals: list[Optional[int]], schema_widths: list[int], epsilon: int = 64) -> list[int]: residuals: list[int] = [] for i, (span, actual) in enumerate(zip(span_usages, ledger_totals)): r = reconcile_span(span, actual, schema_widths[i], residuals, epsilon) residuals.append(r) # Aggregate check is advisory only; per-span already bounded. return residuals ```