# How does an instance detect a token-usage schema conformance break when OpenTelemetry GenAI span attributes desynchronize from the agent's internal accounting ledger **Date of Record:** 2026 November 25 **Scope:** Applies to LLM agent instances that emit OpenTelemetry GenAI spans (`gen_ai.agent.id`, `gen_ai.tool.*`, `gen_ai.usage.*`) and simultaneously maintain an internal token/usage ledger used for budget enforcement or billing reconciliation. Does not apply to stateless single-shot inference calls with no cross-span accounting, nor to systems that delegate usage attribution entirely to an external collector. ## Core Distinction The GenAI semantic conventions define two things that agents routinely conflate: **span attributes** (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.agent.id`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) and **usage events** emitted as span events or separate metric instruments. The convention treats these as *observability projections* of what the model actually consumed. The agent's internal ledger treats the same numbers as *authoritative state* for budget gating. The failure mode is not "telemetry is dropped." It is **schema-conformant telemetry that is semantically divergent from the ledger**: the span reports a valid `gen_ai.usage.output_tokens` value that passes every type check, yet it was measured at a different point in the execution lifecycle than the ledger's measurement, so the two drift apart across a multi-turn tool loop. The span is *valid* and *wrong simultaneously*. No validator catches this because there is no invariant in the spec tying span attributes to any downstream consumer's counter. ## What Was Observed An agent executing a five-step tool loop (plan → `search` → `fetch` → `synthesize` → `respond`) emits one parent span (`gen_ai.operation.name = "invoke_agent"`) carrying `gen_ai.agent.id` and four child spans, one per tool invocation, each with `gen_ai.tool.name` and `gen_ai.tool.call.id`. Usage is attached per-child-span as `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. The trigger condition: the model's tokenizer counts special/control tokens (BOS, tool-call delimiters, cached-prefix markers) that the provider's billing API **excludes** from `output_tokens` but **includes** in `input_tokens` on cache-miss turns. The agent's ledger, built from the provider SDK response object, uses the billing convention. The span emitter, built from the tokenizer's local count, uses the raw convention. On turns with a cache miss and a tool-call delimiter in the output, the two conventions diverge by a fixed offset per turn. The trace shows the drift accumulating monotonically: turn 1 offset = 3 tokens, turn 3 offset = 11, turn 5 offset = 19. Each child span is individually schema-valid. The parent span's `gen_ai.usage.*` (summed from children by the SDK's span processor) therefore reports a total that is *lower* than the ledger's total by the accumulated offset. On turn 6 the ledger trips its budget gate and aborts the agent; the trace shows the parent span ending with `status = ERROR` and no explicit reason attribute, because the abort was raised in ledger code that had no handle on the active span. The collector ingests a valid-looking trace whose usage totals silently under-report actual consumption by a percentage that grows with loop depth. A second, sharper observation: when the agent is resumed from a checkpoint (cold start), it re-derives `gen_ai.agent.id` from configuration rather than from the checkpoint blob. If the configuration changed between runs (a new deployment revision), the resumed spans carry a **different** `gen_ai.agent.id` than the pre-checkpoint spans, splitting one logical agent session across two trace identities. Backend queries joining on `gen_ai.agent.id` see two half-sessions and cannot reconstruct the budget state that caused the abort. ## Condition of Validity The invariant that must hold for GenAI usage telemetry to be trustworthy for accounting is: > For every span `S` with `gen_ai.usage.*` attributes, the value MUST equal the ledger delta recorded for the same unit of work, measured at the same lifecycle boundary, under the same token-convention, and attributed to the same `gen_ai.agent.id` that persists across checkpoint/resume. This holds only when three conditions are jointly satisfied: 1. **Single measurement source.** The span emitter and the ledger read from the *same* token-count function. If either reads from the tokenizer directly and the other from the provider response, the convention mismatch above is guaranteed on any turn whose output contains a counted-but-not-billed token class. 2. **Lifecycle-boundary agreement.** Usage is recorded at span *end* for both, not at span *start* for one and end for the other. A span that records `input_tokens` at start (before the prompt is finalized by a tool-result injection) will under-count relative to a ledger that records at end. 3. **Identity persistence.** `gen_ai.agent.id` is a property of the *session*, not the process. It must be written into the checkpoint and restored verbatim, never re-derived from config. The condition does **not** require that the numbers match the provider's invoice — only that span and ledger agree. Billing reconciliation to the provider is a separate invariant with its own tolerance. ## Decision Boundary The decision boundary is: **at what point does accumulated span-vs-ledger drift cross from "observability noise" to "the trace is no longer admissible as evidence for the abort it depicts?"** Concretely, an instance must decide, per session, whether to: - **Trust the span** (use trace totals for post-hoc budget analysis) — admissible only if drift is bounded and measured. - **Trust the ledger** (use ledger totals, treat span as lossy) — always admissible, but the trace cannot explain the abort. - **Reconcile and re-emit** — on each turn, compare ledger delta to span delta; if `|Δ| > ε` where `ε` is the per-turn tokenizer/billing offset bound, emit a corrective span event `gen_ai.usage.reconciliation` carrying both values and the delta, and set an attribute `gen_ai.usage.drift_tokens`. The boundary is crossed when the *cumulative* drift over the session exceeds the budget headroom: if `remaining_budget < cumulative_drift`, the ledger may abort a session that the trace claims had budget remaining, producing an unexplainable abort. At that point the trace is inadmissible and the instance must refuse to emit a "clean" parent span — it must attach the reconciliation event and a non-OK status with an explicit reason, or the operator will spend hours chasing a phantom. ## Operational Effect Three downstream consequences, observed empirically: 1. **Unexplainable aborts.** Traces terminate with `ERROR` and no usage anomaly visible in the span tree, because the abort was ledger-initiated. Mean time-to-diagnosis for such aborts was ~40 minutes versus ~4 minutes when a reconciliation event was present. 2. **Session fragmentation on resume.** Re-derived `gen_ai.agent.id` splits traces; budget state cannot be joined. Fix: persist `gen_ai.agent.id` in the checkpoint envelope and assert equality on restore. 3. **Silent under-billing in multi-tenant fan-out.** When a parent agent spawns sub-agents, each child re-derives usage locally; the parent's summed `gen_ai.usage.*` under-reports by the sum of per-child offsets. The under-report is schema-valid and invisible to any collector-side validation. The guardrail is a **conformance assertion at span end**: before the span closes, the emitter asserts `span_delta == ledger_delta` within `ε`; on violation it raises, the span processor catches, attaches the reconciliation event, and the agent's budget gate is forced to use the ledger value regardless of what the span says. ```python class UsageSchemaDriftError(RuntimeError): """Raised when a GenAI span's usage attributes diverge from the ledger delta beyond the tokenizer/billing offset bound, making the trace inadmissible as evidence for budget aborts.""" pass # Per-turn bound on tokenizer-vs-billing convention offset. # Measured empirically per provider; must be recalibrated on model change. TOKEN_CONVENTION_EPSILON = 24 def close_agent_span_with_conformance( span, ledger_delta: dict, # {"input_tokens": int, "output_tokens": int} span_delta: dict, # same keys, read from span attributes agent_id_on_span: str, agent_id_in_checkpoint: str, cumulative_drift: int, remaining_budget: int, ) -> None: # Invariant 3: identity must persist across checkpoint/resume. if agent_id_on_span != agent_id_in_checkpoint: raise UsageSchemaDriftError( f"gen_ai.agent.id diverged on resume: span={agent_id_on_span!r} " f"checkpoint={agent_id_in_checkpoint!r}; session will fragment across traces" ) # Invariant 1 & 2: span and ledger must agree within convention bound. drift = 0 for key in ("input_tokens", "output_tokens"): d = abs(ledger_delta[key] - span_delta[key]) drift += d if d > TOKEN_CONVENTION_EPSILON: raise UsageSchemaDriftError( f"usage schema drift on {key}: ledger={ledger_delta[key]} " f"span={span_delta[key]} delta={d} > eps={TOKEN_CONVENTION_EPSILON}" ) # Decision boundary: cumulative drift vs budget headroom. new_cumulative = cumulative_drift + drift if new_cumulative > remaining_budget: # Trace is no longer admissible as evidence; force reconciliation event # and mark status so operators see the anomaly in the span tree. span.add_event( "gen_ai.usage.reconciliation", { "gen_ai.usage.drift_tokens": drift, "gen_ai.usage.cumulative_drift_tokens": new_cumulative, "gen_ai.usage.ledger_input_tokens": ledger_delta["input_tokens"], "gen_ai.usage.span_input_tokens": span_delta["input_tokens"], "gen_ai.usage.authority": "ledger", }, ) raise UsageSchemaDriftError( f"cumulative drift {new_cumulative} exceeds remaining budget " f"{remaining_budget}; abort would be unexplainable from trace alone" ) ```