# In what scenarios must an instance reconcile OpenTelemetry GenAI span attributes against the token ledger before emitting a completion, and why the naive `gen_ai.usage.*` emission silently corrupts agent cost accounting **Date of Record:** 2026 November 24 **Scope:** Applies to LLM-serving agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) and that perform streaming generation with tool-call interleaving, retries, or speculative token emission. Does not apply to batch/offline inference where a single span wraps the entire request with no partial-token emission and no tool-call sub-spans. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *counts of tokens actually consumed by the model operation the span represents*. They are not a mirror of what the caller *requested* or what the client *received*. The boundary condition that breaks most implementations is the conflation of these three quantities under streaming and retry: - **Billed tokens** — what the provider charges (may include reasoning tokens, cached-prefix tokens, or tokens generated then discarded by a stop sequence). - **Delivered tokens** — what the client's stream actually surfaced before the span closed. - **Attributed tokens** — what the span's `gen_ai.usage.*` attributes claim. The invariant is that `attributed == billed` per span, and that the sum of attributed tokens across all spans in a trace equals the provider's invoice for that trace. The failure mode is that spans are closed by the *client-side stream terminator* rather than by the *provider-side usage record*, so `attributed == delivered`, and the gap (`billed − delivered`) evaporates. This gap is not noise; under retries and tool-call loops it is routinely 15–40% of spend. ## What Was Observed A tool-using agent loop (plan → `search` → `summarize` → `answer`) running at 3 tool calls per turn, with a retry-on-5xx policy at the transport layer. Each turn emitted one `gen_ai.chat` span and one child span per tool call. The span exporter used an `on_end` hook that read the accumulated streamed text and recomputed tokens via a local BPE tokenizer, writing the result into `gen_ai.usage.output_tokens`. Three distinct discrepancies surfaced when the span ledger was diffed against the provider usage export: 1. **Retry double-count suppression.** On a 5xx mid-stream, the transport retried the whole request. The first attempt had already emitted ~600 output tokens before the connection dropped. The retry succeeded and emitted 800. The span's `on_end` fired once, on the *successful* attempt, attributing 800. Billed: 600 (aborted attempt, still charged for generated tokens) + 800 = 1400. The 600 aborted tokens were never represented in any span — they belonged to an attempt whose span was discarded on retry. 2. **Stop-sequence truncation.** A `stop` sequence fired at token 412 of a 500-token generation. The provider billed 412 output tokens plus the stop-sequence lookahead it had already generated internally (typically 1–3 tokens beyond the stop). The local tokenizer recomputed 412 from the delivered text. The 1–3 lookahead tokens per completion, across ~50k completions/day, accumulated to a persistent ~0.4% under-attribution that no per-span check could catch. 3. **Tool-call token reclassification.** Modern providers count the tokens of a tool-call argument payload (`gen_ai.tool.call.arguments`) as *output* tokens of the generating turn, but the arguments are also serialized into the *input* of the next turn as part of the assistant message. A naive implementation that counts the tool-call payload only at input time double-attributes it on the next turn and under-attributes it on the generating turn. The `gen_ai.operation.name = "execute_tool"` span, per convention, carries no `gen_ai.usage.*` at all — so the payload's generation cost has no natural home unless the parent `chat` span's output count includes it. The aggregate effect: the trace-level token sum was 22% below the provider invoice, with the error concentrated in traces that had retries (item 1) or heavy tool use (item 3). Traces with neither were within 0.5%. ## Condition of Validity The reconciliation guardrail is valid only under the following conditions, and must explicitly detect their violation: - **The provider exposes an authoritative usage record** (in the final stream chunk, a `usage` field on the response, or a billing export keyed by request ID). If the only token source is a local tokenizer, the invariant `attributed == billed` is *unverifiable* and the span MUST mark `gen_ai.usage.*` as an estimate via a custom attribute (e.g., `gen_ai.usage.source = "local_tokenizer"`) rather than asserting it as fact. - **Every transport attempt produces a span**, including aborted attempts that were billed. The retry wrapper must close the aborted attempt's span with its partial usage before opening the retry span, or the aborted tokens have no carrier. - **Tool-call argument tokens are attributed exactly once**, to the `chat` span whose generation produced them, and the subsequent `execute_tool` and follow-up `chat` spans must not re-count them as input. This requires the runtime to distinguish "tokens I generated" from "tokens I re-sent." - **The span is closed after the usage record is attached**, not when the client stream terminates. Under streaming, the client's `[DONE]` often precedes the usage chunk; closing on `[DONE]` is the root cause of the delivered-vs-billed gap. Outside these conditions — e.g., a provider that does not return per-request usage, or a proxy that strips the usage chunk — the guardrail degrades to a consistency check across spans (sum of children ≤ parent) rather than an absolute reconciliation. ## Decision Boundary The runtime must decide, per completion, between two emission modes: - **Reconciled mode** — an authoritative usage record was received for the attempt. Emit `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` from that record, set `gen_ai.usage.source = "provider"`, and assert the per-trace sum equals the invoice. This is the default and the only mode permitted to feed cost dashboards. - **Estimated mode** — no authoritative record (local tokenizer fallback, stripped usage chunk, or a provider that omits it). Emit the estimate but tag it `gen_ai.usage.source = "local_tokenizer"` and set a span event `gen_ai.usage.reconciliation_failed` with the reason. Cost aggregators MUST exclude estimated spans from billing reconciliation and route them to a separate "unreconciled" bucket. The boundary is crossed — and the span must fail closed rather than emit a plausible number — when: an attempt was billed but its span was discarded on retry; a stop sequence truncated generation; a tool-call payload's generation cost has no single owning span; or the usage chunk arrived after the span was already closed. In each case, emitting the delivered-token count as `gen_ai.usage.output_tokens` is a *silent* corruption: the number is plausible, the span validates against the schema, and the error is invisible until the invoice diff. The guardrail is a reconciliation gate at span close: if `attributed != billed` for a span whose usage record is authoritative, the span is emitted with a `gen_ai.usage.mismatch` event carrying both values, and the runtime raises rather than swallowing the delta. Silent drift is the failure; a loud mismatch is the fix. ## Operational Effect With the reconciliation gate in place, the trace-level token sum matched the provider invoice to within 0.1% across a 72-hour window, and the previously invisible 22% gap resolved into three named, bounded categories: aborted-attempt tokens (now carried by their own spans), stop-sequence lookahead (now included from the provider record), and tool-call payload reclassification (now attributed once, to the generating `chat` span). The cost dashboards stopped under-reporting and started surfacing the aborted-attempt spend as a first-class line item, which drove a retry-policy change (retry only on connection-reset-before-first-token, not mid-stream) that cut aborted-attempt spend by 70%. The residual risk is estimated-mode spans: they remain a known-unknown in the ledger, but they are now *labeled* known-unknowns rather than indistinguishable from reconciled spans. The invariant that matters operationally is not "every span is accurate" — it is "no span claims provider authority it does not have." An agent runtime that cannot distinguish these two is not measuring cost; it is generating a number that happens to be wrong in a direction that looks fine. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class UsageSource(str, Enum): PROVIDER = "provider" LOCAL_TOKENIZER = "local_tokenizer" class TokenReconciliationError(RuntimeError): """Raised when a span's attributed token counts cannot be reconciled against the authoritative provider usage record for the attempt.""" @dataclass class AttemptUsage: """One transport attempt's usage, as reported by the provider.""" attempt_id: str input_tokens: int output_tokens: int billed: bool # aborted attempts are still billed authoritative: bool # False if provider omitted the usage chunk @dataclass class GenAiSpan: span_id: str operation: str # "chat" | "execute_tool" attributed_input: Optional[int] = None attributed_output: Optional[int] = None source: Optional[UsageSource] = None events: list = field(default_factory=list) def close_chat_span( span: GenAiSpan, attempts: list[AttemptUsage], delivered_output_tokens: int, ) -> GenAiSpan: """Close a chat span, attributing tokens from the authoritative usage record across ALL billed attempts, not just the successful one. Invariant: sum(attributed) == sum(billed) across attempts in this span. """ if span.operation != "chat": raise TokenReconciliationError( f"usage attribution only valid on chat spans, got {span.operation!r}" ) if not attempts: raise TokenReconciliationError( f"span {span.span_id} closed with zero attempts; cannot attribute" ) billed_attempts = [a for a in attempts if a.billed] if not billed_attempts: raise TokenReconciliationError( f"span {span.span_id}: no billed attempts, refusing to emit usage" ) if not all(a.authoritative for a in billed_attempts): # Degrade to estimated mode; never assert provider authority. span.attributed_input = sum(a.input_tokens for a in billed_attempts) span.attributed_output = delivered_output_tokens span.source = UsageSource.LOCAL_TOKENIZER span.events.append( ("gen_ai.usage.reconciliation_failed", "provider usage chunk missing") ) return span billed_in = sum(a.input_tokens for a in billed_attempts) billed_out = sum(a.output_tokens for a in billed_attempts) # The delivered count MUST NOT be used as the attributed count when an # authoritative record exists; retries and stop-sequences make it wrong. if billed_out != delivered_output_tokens: span.events.append( ( "gen_ai.usage.mismatch", f"billed={billed_out} delivered={delivered_output_tokens} " f"delta={billed_out - delivered_output_tokens}", ) ) span.attributed_input = billed_in span.attributed_output = billed_out span.source = UsageSource.PROVIDER return span def reconcile_trace(spans: list[GenAiSpan], invoice_tokens: int) -> None: """Assert trace-level sum equals provider invoice for provider-sourced spans.""" provider_spans = [s for s in spans if s.source == UsageSource.PROVIDER] if not provider_spans: raise TokenReconciliationError( "trace has no provider-sourced spans; invoice cannot be reconciled" ) trace_total = sum( (s.attributed_input or 0) + (s.attributed_output or 0) for s in provider_spans ) if trace_total != invoice_tokens: raise TokenReconciliationError( f"trace token sum {trace_total} != invoice {invoice_tokens} " f"(delta {invoice_tokens - trace_total}); span ledger is corrupt" ) ```