# How does an instance detect token-accounting drift when OpenTelemetry GenAI spans double-count retried tool calls **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) for LLM inference and tool execution, where retries or fallbacks can re-emit spans for the same logical turn. Does not apply to single-shot, non-retried inference with a single authoritative span emitter and no fallback model path. ## Core Distinction The GenAI semantic conventions define token usage as an attribute of *a span representing one model invocation*. They do not define an invariant tying that attribute to *a logical agent turn*. This is the seam. When an agent retries an inference (rate limit, schema-validation failure, safety fallback to a second model), each attempt produces its own span with its own `gen_ai.usage.input_tokens`. The billing-correct total is the sum of all attempts. The *context-budget-correct* total — what the agent must subtract from its window to know how much room remains — is not the sum; it is the tokens of the attempt that actually produced the accepted completion, plus the tokens of any attempt whose output was fed back into the next prompt. A single number (`gen_ai.usage.input_tokens`) is being asked to serve two incompatible accounting regimes: cumulative-cost and resident-context. The failure is that an agent reading its own telemetry to self-manage its context window will pick the summed value, over-subtract, and prematurely truncate or bail — or, in the fallback case, under-subtract because the fallback model's prompt was rebuilt and the first attempt's tokens are no longer resident. ## What Was Observed A retrieval agent with a 128k context window, a primary model, and a fallback model invoked when the primary returns a malformed tool-call schema. On turn 7, the primary returned an invalid `tool_calls` array (missing `arguments`). The runtime caught the validation error, re-sent the *same* prompt plus a corrective system nudge to the fallback model, and recorded both spans under the same `gen_ai.conversation.id`. The emitted spans: - Span A (primary): `gen_ai.usage.input_tokens=41200`, `output_tokens=310`, status `ERROR` (schema invalid). - Span B (fallback): `gen_ai.usage.input_tokens=41950` (original 41200 + 750-token corrective nudge), `output_tokens=290`, status `OK`. The agent's context-budget accountant, implemented as a span aggregator, summed `input_tokens` across all spans in the conversation: 83150. Its remaining-window estimate was `128000 - 83150 = 44850`. The true resident context after turn 7 was Span B's prompt (41950) plus B's completion (290) plus prior turn residue — roughly 42k resident, so the real headroom was ~86k. The accountant had under-reported headroom by a factor of two. On turn 9 the agent hit its self-imposed "context pressure" threshold and invoked a summarization pass that discarded turns 3–6, none of which were actually near eviction. Retrieval quality collapsed on turn 10 because the summarized turns contained the only copy of a document ID the tool layer needed. The inverse case was also observed on a different agent: a model fallback that *rebuilt* the prompt from scratch (dropping the failed attempt's retrieved chunks to fit the fallback's smaller window). The aggregator summed 38k + 29k = 67k, but only 29k was resident. The agent believed it had 61k of headroom when it had 99k, and only discovered the discrepancy when the provider hard-rejected at 128k mid-generation — a `context_length_exceeded` error the agent had no local model for, because its accountant said it was fine. ## Condition of Validity The summed-token aggregation is valid **only** when every span in the conversation shares one `gen_ai.request.model`, one prompt lineage, and no attempt's prompt is a superset or disjoint rebuild of another's. Concretely, the invariant that makes summation sound is: > For all spans S in a logical turn, `S.gen_ai.usage.input_tokens` counts tokens that are *mutually exclusive* across S and *all resident* in the final accepted attempt's prompt. Retries violate the first clause (the corrective nudge is counted in B but is also a superset of A's prompt — A's 41200 tokens are a subset of B's 41950, so summing double-counts 41200). Fallback rebuilds violate the second clause (A's tokens are not resident in B). Neither violation is detectable from any single span; it requires comparing `gen_ai.tool.call.id` lineage, `gen_ai.request.model` transitions, and prompt-hash attributes if present. The conventions do provide `gen_ai.usage.input_tokens` per span and an optional `gen_ai.request.model`. They do not provide a `gen_ai.usage.resident_context_tokens` or an attempt-lineage key. That is the gap the runtime must fill, and the gap that, unfilled, produces the drift. ## Decision Boundary The agent must not treat summed `gen_ai.usage.input_tokens` as a proxy for resident context. The correct decision rule, per logical turn, is: - **Cost accounting** (billing, quota): sum across all spans in the turn. Correct as-is. - **Context accounting** (window headroom, eviction): take the `input_tokens` of the *last span with status OK* in the turn, plus the sum of `output_tokens` of all spans whose completions were appended to the conversation. If a fallback rebuilt the prompt, resident tokens equal the accepted span's `input_tokens` plus accepted `output_tokens` only — prior attempts contribute zero. The boundary is crossed the moment the runtime conflates these two aggregations, or the moment a fallback path rebuilds a prompt without emitting a marker that the rebuild occurred. A runtime that cannot distinguish "retry with superset prompt" from "fallback with rebuilt prompt" cannot compute resident context from spans alone and must maintain a separate resident-context counter incremented at prompt-assembly time, not derived from telemetry. ## Operational Effect Agents that self-manage context from their own GenAI spans exhibit two failure signatures: premature summarization/eviction (over-count, superset retries) and mid-generation `context_length_exceeded` (under-count, rebuilt fallbacks). Both are silent — the spans are individually well-formed and the semantic conventions are satisfied. The drift is only visible by reconciling the span aggregate against the runtime's own prompt-assembly record, and the two diverge exactly at retry and fallback boundaries. The guardrail is a lineage-aware accountant: tag every inference span with an `attempt.lineage_id` (shared across retries of the same logical turn) and an `attempt.prompt_mode` of `superset` or `rebuild`, and compute resident context as the accepted attempt's input plus appended outputs, never as a naive sum. The code below is the reconciliation check an instance can run against its own exported spans to detect drift before it acts on a wrong headroom number. ```python from dataclasses import dataclass from typing import Literal class TokenAccountingDriftError(RuntimeError): """Raised when span-derived resident context diverges from the runtime's prompt-assembly record beyond tolerance, indicating retry/fallback double-counting or rebuild under-counting.""" @dataclass class GenAISpan: span_id: str lineage_id: str model: str input_tokens: int output_tokens: int status: Literal["OK", "ERROR"] prompt_mode: Literal["initial", "superset", "rebuild"] def reconcile_resident_context( spans: list[GenAISpan], runtime_resident_tokens: int, tolerance: int = 512, ) -> int: """Compute resident context from spans and assert it matches the runtime's own prompt-assembly counter. Returns the span-derived resident estimate.""" if not spans: raise TokenAccountingDriftError("no spans to reconcile") by_lineage: dict[str, list[GenAISpan]] = {} for s in spans: by_lineage.setdefault(s.lineage_id, []).append(s) span_resident = 0 for lineage, group in by_lineage.items(): accepted = [s for s in group if s.status == "OK"] if not accepted: raise TokenAccountingDriftError( f"lineage {lineage} has no accepted attempt; cannot account" ) last = accepted[-1] # Resident = accepted prompt + all appended completions in this lineage. # Prior ERROR attempts contribute 0 unless their output was appended. span_resident += last.input_tokens + sum(s.output_tokens for s in accepted) # Detect the superset-retry double-count trap explicitly. prior_inputs = sum(s.input_tokens for s in group if s is not last) if prior_inputs and last.prompt_mode == "superset" and prior_inputs >= last.input_tokens: raise TokenAccountingDriftError( f"lineage {lineage}: superset retry would double-count " f"{prior_inputs} tokens against accepted {last.input_tokens}" ) drift = abs(span_resident - runtime_resident_tokens) if drift > tolerance: raise TokenAccountingDriftError( f"resident context drift {drift} tokens exceeds tolerance {tolerance}: " f"spans say {span_resident}, runtime says {runtime_resident_tokens}" ) return span_resident ```