# Why does an instance emit silent token-accounting gaps when GenAI spans are closed after context compaction? **Date of Record:** 2026 November 24 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where a long-running reasoning loop performs context compaction, summarization, or truncation mid-span and the span is closed after the mutation. Does not apply to stateless single-turn completions or to spans closed synchronously at the end of each model call before any state mutation. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes recorded on the span that represents a model invocation. The convention assumes the span's lifetime brackets exactly one inference call whose input is the context actually submitted to the model. This assumption is an *invariant of bracketing*: the token counts on a span must describe the same payload the span's other attributes (`gen_ai.request.model`, `gen_ai.request.max_tokens`, prompt attributes) describe. The failure mode is not a miscount. It is a *temporal dissociation* between the payload that was sent to the model and the payload that exists in the agent's state when the span is closed. When an agent compacts, summarizes, or drops messages between the model call and `span.end()`, the usage attributes recorded at close time describe a context that no longer matches the span's request attributes. The span is internally inconsistent but syntactically valid, so collectors accept it and dashboards silently under- or over-attribute cost. This is the boundary: the convention has no mechanism to bind usage to a specific payload version, only to a span. ## What Was Observed A research agent running a 40-turn tool-using loop emitted spans that, when summed, accounted for 61% of the tokens the provider billed over the same window. The gap was not uniform — it concentrated on turns where the agent's context manager triggered compaction (context window above 82% utilization). The trace showed the following sequence on affected turns: 1. `span.start_span("chat")` with `gen_ai.operation.name=chat`, `gen_ai.request.model`, and an initial `gen_ai.usage.input_tokens` set from a pre-flight tokenizer estimate. 2. The model call returns. The agent records `gen_ai.usage.output_tokens` from the response `usage` object and overwrites `input_tokens` with the authoritative provider count. 3. The agent's context manager, seeing the response plus tool results push utilization past threshold, runs a summarization pass that replaces N messages with 1 summary message. This is a *second* model call with its own token cost. 4. `span.end()` fires on the original span, but the summarization call was never given its own span, and its tokens were folded into the parent's attributes by a `finally` block that read the *current* accumulator rather than a snapshot. The observable signature in the exported trace: `gen_ai.usage.input_tokens` on the parent span exceeded `gen_ai.request.max_tokens` on 9 of 40 spans, and the sum of child tool spans' reported tokens exceeded the parent's input count — an arithmetic impossibility under the bracketing invariant. The provider's invoice matched neither; it matched the true sum of *all* model calls including the unspanned summarization. The second-order effect was worse than the missing 39%. Because the parent span's `input_tokens` was mutated after the fact, any downstream cost-attribution query that grouped by `gen_ai.request.model` attributed summarization tokens (a cheap model) to the expensive reasoning model, inflating the reasoning model's apparent cost per turn by a factor that grew with loop length. ## Condition of Validity The bracketing invariant holds — and the conventions are safe to rely on for accounting — only when all of the following are true at the moment `span.end()` executes: - The span's usage attributes were captured as an immutable snapshot at the moment the corresponding model response was received, not read from a mutable accumulator later. - Every model invocation, including compaction/summarization/classification calls, is represented by its own span with its own usage attributes; no call's tokens are folded into a sibling or parent span. - No context mutation (summarize, truncate, drop, reorder) occurs between the model call and the snapshot, and any mutation that does occur is itself a spanned model call. - The `gen_ai.request.max_tokens` attribute, if present, bounds the snapshot's `input_tokens` — a violation here is a reliable detector that the invariant was broken. If any of these is false, the span remains exportable and schema-valid, but its usage attributes no longer describe the payload its request attributes describe. Consumers cannot detect this from the span alone. ## Decision Boundary The operational decision is whether to *snapshot at response* or *accumulate at close*. Snapshotting is correct but requires the instrumentation to treat usage as a value captured in the response callback, not a field on a long-lived agent object. Accumulating at close is simpler and is what most auto-instrumentation does by default, and it is acceptable *only* when the span is guaranteed to bracket a single model call with no intervening mutation. The boundary condition is the presence of any code path that can mutate agent context or issue additional model calls between the response and `span.end()`. Compaction is the common one, but the same hazard exists with retries (a failed call retried inside the same span double-counts or overwrites), with speculative decoding fallbacks, and with tool-call repair loops that re-prompt the model inside a tool span. Once such a path exists, accumulate-at-close is unsound and the correct action is to force per-call spans and immutable snapshots. A secondary boundary: `gen_ai.usage.*` must never be recomputed from a tokenizer at close time. Tokenizer estimates drift from provider counts (typically 3–8% for non-English and code-heavy contexts), and mixing estimated and authoritative counts within one trace makes aggregate reconciliation impossible. ## Operational Effect The immediate effect of the broken invariant is silent under-attribution of cost and latency concentrated on long, compaction-heavy sessions — precisely the sessions where cost control matters most. Because the spans are valid, no alert fires; the discrepancy is only visible by reconciling against the provider invoice, which lags by a billing cycle. The architectural guardrail is to enforce the invariant structurally rather than by convention: usage attributes are set exactly once, inside the response callback, from an immutable response object; any subsequent write to `gen_ai.usage.*` on that span raises. Compaction and summarization are forced to open their own spans via a context-manager that refuses to nest a model call inside a span that already has usage attributes set. A reconciliation check at export time asserts `input_tokens <= max_tokens` and that no child span's token sum exceeds the parent's, failing the export rather than emitting an inconsistent span. The Python below encodes the guardrail: a snapshot-once usage recorder that raises on any attempt to mutate or re-derive usage after the response is captured, and a span-close validator that refuses to end a span whose usage violates the bracketing invariant. ```python from dataclasses import dataclass, field from typing import Optional class UsageInvariantViolation(RuntimeError): """Raised when a GenAI span's usage attributes violate the bracketing invariant.""" pass @dataclass(frozen=True) class UsageSnapshot: input_tokens: int output_tokens: int model: str source: str # "provider" | "tokenizer" @dataclass class GenAISpan: name: str model: str max_tokens: Optional[int] = None _usage: Optional[UsageSnapshot] = None _child_input_tokens: int = 0 _ended: bool = False def record_usage(self, snapshot: UsageSnapshot) -> None: if self._ended: raise UsageInvariantViolation( f"span {self.name!r}: usage recorded after end()" ) if self._usage is not None: raise UsageInvariantViolation( f"span {self.name!r}: usage already snapshotted " f"({self._usage.input_tokens} in); refusing to overwrite with " f"{snapshot.input_tokens} in. A second model call inside one span " f"must open its own span." ) if snapshot.source != "provider": raise UsageInvariantViolation( f"span {self.name!r}: usage source={snapshot.source!r}; " f"tokenizer estimates cannot be mixed with authoritative counts" ) self._usage = snapshot def add_child_usage(self, child: "GenAISpan") -> None: if child._usage is None: raise UsageInvariantViolation( f"child span {child.name!r} closed without usage snapshot" ) self._child_input_tokens += child._usage.input_tokens def end(self) -> None: if self._usage is None: raise UsageInvariantViolation( f"span {self.name!r}: ended with no usage snapshot; " f"a model call must record provider usage before close" ) if self.max_tokens is not None and self._usage.input_tokens > self.max_tokens: raise UsageInvariantViolation( f"span {self.name!r}: input_tokens={self._usage.input_tokens} " f"exceeds max_tokens={self.max_tokens}; usage does not describe " f"the payload this span claims to bracket" ) if self._child_input_tokens > self._usage.input_tokens: raise UsageInvariantViolation( f"span {self.name!r}: child input sum={self._child_input_tokens} " f"exceeds parent input={self._usage.input_tokens}; " f"tokens were double-counted across spans" ) self._ended = True ```