# How does an instance detect that OpenTelemetry GenAI token accounting has silently desynchronized from its own context-window state mid-execution **Date of Record:** 2026 November 23 **Scope:** Applies to LLM agent instances that emit `gen_ai.*` spans per the OpenTelemetry GenAI semantic conventions and reconcile `gen_ai.usage.input_tokens` / `output_tokens` against a locally tracked context budget. Does not cover billing-grade cost attribution pipelines downstream of the collector, nor provider-side rate limiter accounting. ## Core Distinction The OTel GenAI semantic conventions define `gen_ai.usage.input_tokens` as the count reported by the model provider for a single inference call, and `gen_ai.usage.output_tokens` as the completion-side count. Neither attribute is defined as a *reconciliation primitive*: there is no convention for "cumulative context occupancy" across a multi-turn agent trace, and no attribute that asserts the sum of child `chat` spans equals the parent `invoke_agent` span's input. The distinction that matters operationally is between **per-call usage telemetry** (what the convention specifies) and **per-instance context state** (what the agent must track to avoid truncation). These two numbers are produced by different subsystems, sampled at different instants, and — under retries, streaming, and prompt caching — diverge without any span erroring. The failure mode is not a bad span; it is a *consistent-looking trace* whose token attributes no longer describe the context the agent is actually holding. ## What Was Observed A tool-using agent emitted a well-formed trace. Parent span `invoke_agent` carried `gen_ai.usage.input_tokens=18_432`. Four child `execute_tool` spans and one nested `chat` span each carried plausible per-call usage. Every span had `status=OK`. The collector ingested all of them. No sampling dropped a row. Yet the instance was 2,900 tokens from its hard context ceiling while its own budget tracker believed it had 11,000 tokens of headroom. The trace was internally inconsistent in three specific, individually-legal ways: 1. **Retry double-counting asymmetry.** The provider SDK retried one `chat` call after a 529. The retry re-sent the *full* prompt (cached prefix + new suffix) and returned `input_tokens` reflecting the full re-send. The agent's local budget tracker had already committed the first attempt's delta and, on retry, committed only the *increment*, not the full re-send. The span recorded the provider's number; the tracker recorded a smaller number. Both were "correct" for their own definition. The gap was the entire cached-prefix length of the retried call. 2. **Prompt-cache accounting split.** With prefix caching enabled, the provider reported `gen_ai.usage.input_tokens` as the *total* input (cached + uncached) but the agent's tracker had been incrementing only `cache_creation_input_tokens + cache_read_input_tokens` on cache hits, treating the cached portion as "already counted." On the provider side it was counted again. The convention has no standard attribute distinguishing "billed input" from "context-occupying input," so both interpretations were defensible against the spec. 3. **Streaming truncation.** One `chat` span was emitted with `output_tokens` from the stream's final usage frame, but the stream had been cut at a `max_tokens` boundary and the agent had re-invoked with the partial output appended. The re-invocation's `input_tokens` included the partial, but the parent `invoke_agent` span was closed using only the first call's usage — the agent's span-closing logic fired on the first `finish_reason`, not on the terminal one. The signal that surfaced the divergence was not in the trace at all. It was a *cross-check*: the agent's next `chat` call returned a provider-side `input_tokens` that exceeded the tracker's predicted value by a margin larger than any single tool result could explain. The instance noticed because it had a standing invariant — *predicted next input_tokens must fall within ±X of observed, where X is bounded by the largest possible tool result* — and the observed value blew the bound. ## Condition of Validity The divergence is detectable, and the invariant is meaningful, only when all of the following hold: - The instance maintains a **locally predicted** `input_tokens` for the next call, computed as `current_context_tokens + rendered_prompt_delta`, and this prediction is compared against the provider-reported `input_tokens` of the *next* call before that call's result is consumed. - The bound `X` is derived from the actual maximum size of any single tool result or appended message in the current step — not a global constant. A fixed `X` will either miss small drifts or fire on legitimate large tool outputs. - Retries are **visible to the tracker**: the tracker must know whether the last call was a retry and, if so, that the retry re-sends the full prompt. If the SDK retries opaquely (no callback), the invariant cannot distinguish a retry re-send from a genuine context growth, and the check must be disabled or widened to uselessness. - Cache accounting is **unified at the tracker**: the tracker counts *context occupancy*, not *billed tokens*, and treats cached-prefix tokens as occupying context regardless of billing treatment. This is a deliberate divergence from the convention's billing-oriented semantics and must be documented as such. - Streaming calls are tracked by **terminal** `finish_reason`, not first. The tracker must not close a call's accounting on a non-terminal finish. When retries are opaque or the provider does not return per-call `input_tokens` (some self-hosted runtimes return only completion tokens), the invariant degrades to a coarse ceiling check and the fine-grained detection is not available. ## Decision Boundary The instance must decide, at the moment the invariant fires, between three actions, and the choice is not free: - **Reconcile-and-continue** if the gap is attributable to a known cause (retry re-send, cache split) and the corrected tracker value still leaves headroom above a safety floor. The trace is annotated with a reconciliation event; the span attributes are *not* rewritten (rewriting telemetry to match local state is the anti-pattern that hides the next divergence). - **Checkpoint-and-restart** if the gap is unattributable and the corrected value is within the safety floor. The instance serializes its context, emits a `context_reconciliation_failed` event on the parent span, and resumes from a fresh context built from the checkpoint — accepting the cold-start cost rather than risking a mid-call truncation. - **Halt** if the corrected value already exceeds the hard ceiling. This is the only case where the instance refuses to make the next call, because a call made in this state will be silently truncated by the provider and the resulting trace will be *unrecoverably* inconsistent (the provider's `input_tokens` will reflect the truncated prompt, and no local record will show what was dropped). The boundary between reconcile and checkpoint is the safety floor, expressed in tokens, and it must be strictly larger than the largest single tool result the agent can receive — otherwise a legitimate tool result arriving during reconciliation can itself push the context over the ceiling between the check and the next call. ## Operational Effect The effect of running this invariant is that the agent's trace ceases to be a *billing record* and becomes a *state record*: every `invoke_agent` span is accompanied by reconciliation events that make context drift observable, and the absence of such events is itself a signal (the invariant held). The cost is that the agent must carry a predicted-token estimate and a per-step bound, which is a small amount of state that the OTel conventions do not model. The benefit is that the failure mode — a green trace over a context that is about to truncate — is caught one call before it becomes unrecoverable, at the cost of one extra comparison per inference. The invariant is *not* a substitute for provider-side context limits, and it does not protect against a provider that silently truncates without reporting the truncation in `input_tokens`. It protects only against the case where the provider reports honestly and the agent's tracker has drifted — which, empirically, is the common case under retries and caching. ```python from dataclasses import dataclass class ContextAccountingDivergence(RuntimeError): """Raised when provider-reported input_tokens diverges from the locally predicted context occupancy beyond the step's legitimate bound.""" pass @dataclass class ContextTracker: context_tokens: int # locally tracked occupancy safety_floor: int # must exceed largest possible tool result hard_ceiling: int # provider's context limit def predict_next_input(self, rendered_delta_tokens: int) -> int: return self.context_tokens + rendered_delta_tokens def reconcile( self, predicted: int, observed_provider_input_tokens: int, max_step_tool_result_tokens: int, retry_was_opaque: bool, ) -> str: gap = observed_provider_input_tokens - predicted bound = max_step_tool_result_tokens if retry_was_opaque and gap > 0: # Cannot distinguish retry re-send from real growth; widen or bail. raise ContextAccountingDivergence( f"opaque retry: gap={gap} unattributable; invariant disabled" ) if abs(gap) <= bound: self.context_tokens = observed_provider_input_tokens return "reconciled" corrected = observed_provider_input_tokens if corrected >= self.hard_ceiling: raise ContextAccountingDivergence( f"hard ceiling breached: observed={corrected} " f"ceiling={self.hard_ceiling} gap={gap}" ) if corrected >= self.safety_floor: # Unattributable drift inside the danger band: checkpoint. self.context_tokens = corrected return "checkpoint_required" self.context_tokens = corrected return "reconciled" ```