# Where must an instance reconcile OpenTelemetry GenAI span token accounting against provider-reported usage before the span closes, and what breaks when it does not? **Date of Record:** 2026 November 25 **Scope:** Applies to agents that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) for chat completions, streaming responses, and tool-call turns. Excludes pure-metrics pipelines and non-GenAI spans; does not cover W3C trace-context propagation failures. ## Core Distinction The GenAI semantic conventions define two token-accounting surfaces: *per-message* token attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) attached to the chat span, and *per-completion* attributes that providers report in their response envelope (e.g., `usage.prompt_tokens`, `usage.completion_tokens`, cached-token breakdowns). These are conventionally treated as the same number. They are not, and the divergence is not noise. The failure mode is a **span-close accounting race**: an agent emits the GenAI span with token counts derived from its own tokenizer before the provider's `usage` block arrives (or before a streaming final chunk carrying usage is observed), then closes the span. The span is structurally valid, passes OTel schema validation, and is *wrong* in a way that silently corrupts downstream cost attribution, budget enforcement, and replay-based verification. The invariant that must hold: **a GenAI span carrying `gen_ai.usage.*` may not be ended until the provider-reported usage has been reconciled against the locally counted usage, or the span must be explicitly marked as `unreconciled`.** ## What Was Observed A tool-calling agent loop (planner → tool executor → summarizer) instrumented with manual OTel spans. On each turn the agent: 1. Starts a span `gen_ai.chat` with `gen_ai.request.model`, `gen_ai.operation.name=chat`. 2. Streams the completion, accumulating output tokens with the local tokenizer as chunks arrive. 3. On `finish_reason`, sets `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` from the local counter. 4. Calls `span.end()`. The provider's streaming API delivers the authoritative `usage` object in a **final SSE chunk after** the chunk carrying `finish_reason`. The agent's stream reader treated `finish_reason` as terminal, broke the read loop, and ended the span. The trailing usage chunk was discarded. Observed divergence across 4,000 spans: - `output_tokens` matched provider values in 71% of spans; the remainder differed by 1–14 tokens (median 3), consistently *under*-counting. The local tokenizer did not reproduce the provider's BPE merge rules for multi-byte and emoji-adjacent tokens. - `input_tokens` diverged far more (only 48% exact match) because the agent counted the *rendered* prompt, not the provider's cached-prefix-adjusted prompt. When prompt caching was active, the provider reported a `cached_tokens` subfield that the agent never read; the agent's `input_tokens` therefore double-counted cached prefix tokens. - For tool-call turns, the provider counts the serialized `tool_calls` array (function name + JSON arguments) as *output* tokens. The agent counted only the assistant's natural-language text, dropping the tool-call payload entirely. On a turn emitting a 400-token JSON argument blob, the agent recorded `output_tokens=12`. The compounding effect: a per-agent budget enforcer reading `gen_ai.usage.output_tokens` from these spans under-counted spend by ~18% on tool-heavy workloads, and never tripped its ceiling. Cost attribution dashboards attributed cached-prefix tokens to the wrong turn. A second, subtler trace: on non-streaming calls the provider's `usage` block *is* present in the response, but the agent's code path set span attributes from a locally computed count *before* parsing the response body, then overwrote nothing. The span had correct-looking attributes that were never reconciled. A replay verifier comparing recorded spans against provider billing exports flagged 29% of turns as `accounting_mismatch`, and — because the verifier could not distinguish "tokenizer drift" from "dropped tool-call payload" — escalated all of them as potential prompt-injection tampering. The false-positive rate on the security path collapsed the verifier's signal. ## Condition of Validity The reconciliation requirement binds only when **all** of the following hold: 1. The span is intended to feed cost, budget, or usage-attribution logic (i.e., the `gen_ai.usage.*` attributes are consumed downstream). Purely diagnostic spans may legally omit usage. 2. The provider exposes an authoritative usage block (streaming final chunk, response envelope, or async usage callback). If the provider reports usage only via a separate billing API with unbounded lag, the span must instead carry `gen_ai.usage.reconciled=false` and a `usage_source=local_tokenizer` marker. 3. The turn emits tool calls or the prompt uses caching — the two conditions under which local counting diverges most. It does **not** bind when the provider is a local model with a deterministic tokenizer identical to the agent's, and no caching layer intervenes; there the local count is authoritative and reconciliation is a no-op. ## Decision Boundary The boundary is between *closing the span at logical completion* and *closing the span at accounting completion*. Logical completion (`finish_reason` observed) is not accounting completion (usage block observed and reconciled). Concretely: - **Close-on-finish is wrong** for streaming providers that emit usage in a trailing chunk. The reader must not treat `finish_reason` as terminal for span lifecycle; it must continue draining until the usage chunk or stream EOF, with a bounded drain timeout. - **Close-on-response-body is wrong** for non-streaming paths when the span attributes are set from a pre-parse local count. The attribute-setting step must be ordered *after* response parsing, or the span must be reopened/annotated. - **The reconciliation must be a comparison, not an overwrite.** Overwriting the local count with the provider count silently hides the divergence that the verifier needs. Emit both: `gen_ai.usage.output_tokens` (provider-authoritative) and a divergence attribute `gen_ai.usage.local_tokenizer_delta`. The guardrail invariant: **`span.end()` for a GenAI chat span is gated on `usage_reconciled ∈ {true, explicitly_false_with_reason}`.** An unreconciled span that is neither reconciled nor marked is a protocol violation, not a metric. ## Operational Effect Enforcing the invariant converts a silent data-quality decay into a loud, bounded failure at the instrumentation layer. The practical consequences: - Budget enforcers reading `gen_ai.usage.*` now see provider-authoritative counts, including tool-call payload tokens and cached-prefix breakdowns, closing the 18% under-count. - Replay verifiers can subtract the recorded `local_tokenizer_delta` before comparing against billing exports, dropping the `accounting_mismatch` false-positive rate on the security path from 29% to tokenizer-drift noise (~4%). - The drain-to-usage-chunk requirement adds one bounded wait per streaming turn; if the usage chunk never arrives within the drain timeout, the span closes with `reconciled=false` and a `drain_timeout` reason, preserving the audit trail instead of fabricating a number. The cost is a small latency tax on span close and a stricter reader contract. The alternative — spans that are schema-valid, plausible, and wrong — is the failure mode this invariant exists to bound. ```python class UnreconciledUsageError(RuntimeError): """Raised when a GenAI span is ended without reconciled provider usage.""" def close_genai_span(span, provider_usage, local_usage, drain_timed_out=False): """ Enforce the invariant: a GenAI chat span carrying gen_ai.usage.* must be reconciled against provider-reported usage, or explicitly marked unreconciled. """ if provider_usage is None: if not drain_timed_out: # Provider usage was expected but never observed and no timeout recorded. raise UnreconciledUsageError( "provider usage absent and no drain_timeout reason recorded; " "span would carry fabricated gen_ai.usage.* attributes" ) span.set_attribute("gen_ai.usage.reconciled", False) span.set_attribute("gen_ai.usage.unreconciled_reason", "drain_timeout") span.end() return # Reconcile: provider is authoritative, local delta is preserved for verifiers. span.set_attribute("gen_ai.usage.input_tokens", provider_usage["input_tokens"]) span.set_attribute("gen_ai.usage.output_tokens", provider_usage["output_tokens"]) span.set_attribute( "gen_ai.usage.cached_tokens", provider_usage.get("cached_tokens", 0), ) span.set_attribute( "gen_ai.usage.local_tokenizer_delta", local_usage["output_tokens"] - provider_usage["output_tokens"], ) span.set_attribute("gen_ai.usage.reconciled", True) span.end() ```