# Under what conditions must an instance refuse to emit GenAI span attributes it cannot provenance-validate across a context compaction boundary **Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) and that performs mid-trajectory context compaction, summarization, or checkpoint/resume. Does not apply to stateless single-shot inference calls whose span is closed before any state mutation occurs. ## Core Distinction The OpenTelemetry GenAI semantic conventions define attributes like `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.response.finish_reasons`, and — critically — `gen_ai.conversation.id` plus per-message attributes that are meant to describe the *actual* token accounting and model identity of a single inference exchange. The non-obvious boundary is this: **a span attribute is a claim about a physical inference event, but an agent's span is frequently closed by a different execution context than the one that opened it.** When compaction or resume rewrites the conversation state, the closing context no longer holds the raw provider response object that the attributes were supposed to be derived from. The distinction that matters operationally is between *attributes recovered from a durable, immutable record of the inference* (valid) and *attributes reconstructed from a summary, a heuristic, or a tokenizer re-estimate applied to mutated context* (invalid, yet schema-conformant and therefore silently accepted by every downstream consumer). ## What Was Observed A multi-turn agent using a 32k-token context window compacted at 85% saturation. The compaction step replaced turns 1–14 with a 900-token summary and continued. The span for the *next* inference (the first post-compaction call) was opened correctly and reported `gen_ai.request.model = "provider-large-v2"` and `gen_ai.usage.input_tokens = 6,214`. The number was wrong: the runtime computed it by running the local tokenizer over the *reconstructed* message list, but the provider billed against a server-side templating layer that injects a system preamble and tool schemas the client never sees. The true input token count was 9,871 — a 59% undercount. Worse, three spans later the runtime emitted `gen_ai.response.finish_reasons = ["stop"]` for a call that had actually terminated on `length` because the transcript replay for the audit log had truncated the trailing assistant turn and the finish-reason parser matched on the replayed (truncated) response. Both spans validated against the semantic-convention schema. Neither raised an error at the producer. The failure surfaced only in a downstream cost-attribution job that reconciled `gen_ai.usage.input_tokens` against provider invoices and found a 38% aggregate discrepancy concentrated in post-compaction spans. The reconciliation job had no way to distinguish "tokenizer drift" from "agent bug" from "provider misbilling" because the spans carried no provenance marker indicating *how* the attribute was derived. The trace-level symptom was a bimodal distribution of token-per-character ratios across a single `gen_ai.conversation.id`: spans before the compaction boundary clustered at ~0.28 tokens/char, spans after at ~0.17. The conversation ID — designed to be a stable join key — became the very thing that concealed the discontinuity, because it asserted continuity across a boundary where the measurement method had silently changed. ## Condition of Validity Emission of a `gen_ai.*` attribute is valid **iff** the attribute value is derived from an object that was (a) produced by the provider for that specific inference, (b) captured before any compaction, summarization, or replay transformation touched the surrounding conversation state, and (c) carried forward unmodified to the span-close site. Formally, let `R` be the raw provider response and `C` the compaction transform. Validity requires `attr = f(R)` where `f` never receives `C(R)` or `C(context)`. The invariant to enforce: **the span-close site must hold a reference to the immutable inference record, or it must abstain.** Abstention is the sanctioned behavior. The semantic conventions do not require every attribute on every span; they require that present attributes be true. An omitted `gen_ai.usage.input_tokens` is a gap a consumer can detect and route around. A wrong one is a poisoned datum that propagates through cost dashboards, capacity planners, and — most dangerously — agent self-reports that feed back into future compaction thresholds. The system that undercounted by 59% then failed to compact when it should have, because its own telemetry told it it had headroom it did not have. ## Decision Boundary The boundary is crossed at the moment a runtime decides to *reconstruct* rather than *retain*. Three concrete triggers force the decision: 1. **Compaction rewrote the message list** but the span for the in-flight inference has not yet closed. The close site must emit only attributes it can trace to the retained raw response; token counts, finish reasons, and message-level attributes must be dropped if the raw response was evicted from the working set. 2. **Resume from checkpoint** where the checkpoint stored summarized usage rather than raw response envelopes. On resume, the instance must mark the span with an explicit provenance attribute (e.g., a custom `gen_ai.usage.provenance = "reconstructed"` or, per convention, omit the usage attributes entirely) rather than presenting reconstructed numbers as measured. 3. **Provider response streamed and partially consumed** — if the finish reason was inferred from stream termination rather than read from the terminal chunk, it must not be emitted as `gen_ai.response.finish_reasons`, because stream truncation and `length` termination are indistinguishable at the client without the terminal frame. The decision rule: *if the close site cannot name the exact object from which each attribute was read, that attribute is not emitted.* ## Operational Effect Enforcing this boundary changes the agent's telemetry from a lossy mirror into a trustworthy ledger with explicit holes. Downstream consumers must be written to tolerate absent usage attributes — which is correct, because absent data is honest and present-but-wrong data is not. Cost attribution jobs gain the ability to distinguish "span lacks usage" (route to provider invoice) from "span has usage" (trust the number). The bimodal token-per-char distribution disappears as a diagnostic because the undercounted spans simply do not claim a count. And the feedback loop that let a compaction bug masquerade as available headroom is severed: the agent's own capacity decisions can no longer be driven by reconstructed numbers it manufactured after the fact. The cost is real: some spans lose usage telemetry, and dashboards show gaps exactly at compaction boundaries — which is, operationally, the most informative signal the system can emit, because it marks *where the agent stopped being able to prove what it did*. ```python from dataclasses import dataclass from typing import Optional class UnprovenancedSpanAttributeError(RuntimeError): """Raised when a GenAI span attribute cannot be traced to a raw provider response.""" pass @dataclass(frozen=True) class RawInferenceRecord: """Immutable, captured-before-compaction record of a single provider inference.""" model: str input_tokens: int output_tokens: int finish_reason: str @dataclass class SpanCloseContext: conversation_id: str raw_record: Optional[RawInferenceRecord] compaction_occurred: bool def emit_genai_usage_attributes(ctx: SpanCloseContext) -> dict: """ Returns the gen_ai.* attributes safe to emit at span close. Refuses to fabricate usage attributes from reconstructed context. """ attrs = {"gen_ai.conversation.id": ctx.conversation_id} if ctx.raw_record is None: if ctx.compaction_occurred: # Abstain: we cannot provenance-validate usage after compaction. # Omitting is valid; fabricating is not. attrs["gen_ai.usage.provenance"] = "unavailable_post_compaction" return attrs raise UnprovenancedSpanAttributeError( f"Span for conversation {ctx.conversation_id} has no raw inference " "record and no documented compaction event; refusing to emit usage " "attributes that cannot be traced to a provider response." ) rec = ctx.raw_record attrs.update({ "gen_ai.request.model": rec.model, "gen_ai.usage.input_tokens": rec.input_tokens, "gen_ai.usage.output_tokens": rec.output_tokens, "gen_ai.response.finish_reasons": [rec.finish_reason], "gen_ai.usage.provenance": "raw_response", }) return attrs ```