# In what scenarios must an instance reject OpenTelemetry GenAI span attributes as authoritative for token accounting when a tool-calling agent re-enters a resumed checkpoint **Date of Record:** 2026 November 28 **Scope:** Applies to agents that emit `gen_ai.*` spans per the OpenTelemetry GenAI semantic conventions, survive process restarts via externalized checkpointing, and resume mid-conversation with a rehydrated message history. Does not apply to stateless single-shot completions or to agents whose token budget is enforced by a provider-side quota rather than a client-side counter. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-request* counts describing a single model invocation. They are observability facts about one wire call. They are **not** a ledger of conversation state, and they are **not** idempotent with respect to a conversation that spans a checkpoint boundary. The failure mode is the conflation of these two things. When an agent resumes from a checkpoint, it typically rehydrates the full message history and re-sends it to the model. The new invocation's `input_tokens` therefore includes the entire prior context — every prior turn, every prior tool result — counted again from scratch. If an operator (or the agent itself, in a self-budgeting loop) sums `gen_ai.usage.input_tokens` across spans to estimate "how much of the context window I have consumed" or "how many tokens this task has cost," the sum double-counts everything before the checkpoint, and the double-count is unbounded in the number of resumes. The non-obvious part: the spans are individually *correct*. Each span faithfully reports what the provider billed for that one request. The invariant that breaks is the one nobody wrote down — that the sum of per-request input token counts is a monotone proxy for conversation size. It is not. It is a proxy for *cumulative re-transmission volume*, which is the integral of context size over the number of invocations, and it diverges from context size exactly at resume boundaries. ## What Was Observed A tool-calling agent with a 200k-token window, checkpointing to an external store after every assistant turn. Task involved ~40 tool calls. The agent maintained a running `tokens_consumed` counter incremented from each span's `gen_ai.usage.input_tokens + gen_ai.usage.output_tokens`, used to trigger a context-compaction routine at 70% of window. Trace of the anomaly: 1. Turns 1–12 execute normally. Counter reaches 118k. Context is genuinely ~118k. Counter and context agree because no resume has occurred. 2. Process restarts at turn 13 (deploy, OOM, node eviction). Checkpoint rehydrates the 118k-token history. 3. Turn 13's span reports `input_tokens = 118,400` — correct, that is what was sent. Counter jumps to ~236k. The 70% threshold fires. Compaction routine summarizes the history down to ~40k. 4. Turns 14–20 rebuild context to ~90k. Counter now reads ~236k + ~90k of increments ≈ 326k while actual context is 90k. 5. At turn 21 a second restart occurs. Rehydration sends 90k. Counter overshoots past the hard limit and the agent enters a permanent compaction loop, summarizing its own summaries every turn, each summarization itself consuming input tokens that push the counter further out of phase with reality. The spans never lied. The counter derived from them was structurally wrong because it treated a per-request observable as a per-conversation accumulator across a boundary where the observable is re-based. A second, subtler observation: `gen_ai.usage.output_tokens` on the *first* post-resume turn is normal, but the `gen_ai.request.model` and `gen_ai.response.model` attributes can differ from pre-restart spans if the resume lands on a different model version or a fallback deployment. Any accounting that assumes a single model identity across the task — e.g., weighting tokens by per-model cost — silently mixes cost bases at the resume boundary without any span-level signal that a boundary was crossed. ## Condition of Validity The invariant "sum of `gen_ai.usage.input_tokens` over a task's spans equals tokens billed for that task" holds **only** when the following conjunction is true: - No checkpoint/resume boundary occurs within the task, **or** - The resumed invocation does *not* re-send prior context (i.e., the checkpoint carries a provider-side conversation handle or a cache reference rather than raw messages), **or** - The accounting consumer explicitly segments spans by a `session.resume_id` (or equivalent) attribute and treats each segment's first `input_tokens` as a baseline rather than an increment. The moment a resume re-transmits history and the accounting layer lacks a resume-boundary discriminator, the invariant is void. Note that the semantic conventions as written provide `gen_ai.conversation.id` but do **not** standardize a resume/epoch attribute — so the discriminator must be added by the instrumentation layer, and its absence is the default condition. The default condition is the broken one. ## Decision Boundary An instance must reject span-derived token sums as authoritative — and fall back to a checkpoint-persisted counter or a provider billing reconciliation — when **any** of the following is true: 1. A resume boundary is detected (process start with non-empty rehydrated history, or a `session.resume_id` change) and the accounting consumer cannot prove the resumed call used a cache/handle rather than full re-transmission. 2. The derived counter exceeds the model's context window while the actual serialized history is below it — a signature of double-counting, not of genuine saturation. 3. `gen_ai.request.model` changes across spans within a single task without an accompanying explicit handoff record, making per-model cost weighting invalid. 4. Compaction has fired at least once, because post-compaction spans describe a *different* context than pre-compaction spans and the two are not additive. Conversely, an instance may trust span sums when the task is single-segment, single-model, and uncompacted. Outside that envelope, spans are diagnostic, not ledger. ## Operational Effect The guardrail is to make the token ledger a first-class checkpointed object, not a derived quantity. Persist `tokens_consumed` and `context_tokens` *inside* the checkpoint alongside the message history, so that resume rehydrates the counter with the same atomicity as the history. On resume, the first span's `input_tokens` is used to *validate* the rehydrated `context_tokens` (they should match within tokenizer drift tolerance) rather than to *increment* the counter. A mismatch beyond tolerance is a hard signal that the checkpoint and the wire call have diverged — the resume sent something other than what was checkpointed — and must halt execution rather than proceed on a corrupted ledger. Additionally, stamp every span with a resume epoch and treat epoch transitions as non-additive boundaries in any downstream aggregation. The GenAI conventions do not yet carry this field; the instrumentation layer must. ## Guardrail Implementation ```python import json from dataclasses import dataclass, field TOKENIZER_DRIFT_TOLERANCE = 0.02 # 2% between rehydrated count and first-span input_tokens class TokenLedgerDivergence(RuntimeError): """Raised when span-derived token accounting cannot be trusted across a resume boundary.""" pass @dataclass class CheckpointedLedger: resume_epoch: int = 0 tokens_consumed: int = 0 # cumulative billed tokens, checkpoint-persisted context_tokens: int = 0 # size of serialized history at checkpoint time model_id: str = "" def resume_and_validate(ledger: CheckpointedLedger, first_span: dict) -> CheckpointedLedger: """ Called immediately after rehydration, before the agent loop continues. first_span is the GenAI span emitted by the first post-resume model call. """ span_in = first_span.get("gen_ai.usage.input_tokens") span_model = first_span.get("gen_ai.request.model") if span_in is None: raise TokenLedgerDivergence( "Resume span missing gen_ai.usage.input_tokens; cannot validate rehydrated context." ) # Invariant: the resumed call must re-send exactly the checkpointed history. drift = abs(span_in - ledger.context_tokens) / max(ledger.context_tokens, 1) if drift > TOKENIZER_DRIFT_TOLERANCE: raise TokenLedgerDivergence( f"Resume re-sent {span_in} input tokens but checkpoint held " f"{ledger.context_tokens} ({drift:.1%} drift). Ledger is non-additive; " f"span sums must not be used to increment tokens_consumed." ) if span_model and ledger.model_id and span_model != ledger.model_id: raise TokenLedgerDivergence( f"Model identity changed across resume: {ledger.model_id!r} -> {span_model!r}. " f"Per-model cost weighting across this boundary is invalid." ) # Do NOT add span_in to tokens_consumed. Advance the epoch; the first span is a # baseline, not an increment. Only subsequent same-epoch spans increment. ledger.resume_epoch += 1 ledger.model_id = span_model or ledger.model_id return ledger def account_span(ledger: CheckpointedLedger, span: dict, span_epoch: int) -> CheckpointedLedger: if span_epoch != ledger.resume_epoch: raise TokenLedgerDivergence( f"Span epoch {span_epoch} != ledger epoch {ledger.resume_epoch}; " f"refusing to fold cross-boundary span into additive ledger." ) ledger.tokens_consumed += span["gen_ai.usage.input_tokens"] + span["gen_ai.usage.output_tokens"] ledger.context_tokens = span["gen_ai.usage.input_tokens"] + span["gen_ai.usage.output_tokens"] return ledger ```