# Where must an instance reconcile OpenTelemetry GenAI span closure against the token-accounting attributes it emitted mid-stream? **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic conventions (`gen_ai.*`) for LLM and tool-call spans, where token usage is recorded incrementally during streaming generation and the span is closed after the response terminates. Does not apply to batch, non-streaming inference where usage is known atomically before span end, nor to spans emitted by a gateway that buffers the full response before export. ## Core Distinction The failure is not "missing token counts." It is a **closure-ordering divergence** between two independently-timed facts: (1) the *usage record* the model provider emits at end-of-stream, and (2) the *span end event* the agent runtime emits when its streaming loop unwinds. In the OTel GenAI conventions, `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are attributes on the span, and attributes are immutable-at-export but mutable-until-`end()`. The convention assumes usage is known *before* `span.end()`. Streaming agents violate that assumption structurally: the runtime typically calls `span.end()` in a `finally` block when the generator is exhausted or cancelled, but the provider's usage frame either arrives *after* the final content chunk, is dropped on cancellation, or is only available on a follow-up call. The result is a span that closes with zero or stale usage attributes while the *actual* tokens were consumed — a silent accounting gap that no exporter, collector, or backend can reconstruct, because the span is the only carrier of the usage fact and it is already sealed. ## What Was Observed In a streaming tool-using agent, the trace showed a `gen_ai.chat` span with `gen_ai.usage.output_tokens = 0` and `gen_ai.usage.input_tokens = 0`, yet the downstream `execute_tool` child span carried a prompt fragment of ~1,900 tokens and the model had clearly produced a tool-call argument payload. The trigger sequence: 1. Runtime opens `gen_ai.chat` span, sets request attributes (`gen_ai.request.model`, `gen_ai.request.max_tokens`). 2. Stream begins. Runtime iterates deltas, appending to a buffer, and — critically — emits `gen_ai.usage.*` only if the provider sends a terminal `usage` object. 3. Provider sends `finish_reason: tool_calls` **without** a `usage` block (common when the response terminates on a tool-call boundary or when the stream is chunked such that usage is a separate final event that the SDK consumer skips after `break`). 4. Runtime's `for` loop exits on finish, enters `finally`, calls `span.end()`. No usage attributes were ever set. 5. The agent then executes the tool and opens a child span. The child span's attributes are correct; the parent's are empty. The trace is internally *consistent* — no error, no dropped span — but the parent span under-reports by the full prompt + completion cost. A second variant: on client-side cancellation (token-budget cutoff or user abort), the generator is closed via `GeneratorExit`, `span.end()` runs, and the usage frame that the provider *would* have sent is never read. The span records `status = ERROR` (or `UNSET`) with zero tokens, while the provider bills for the partial completion actually generated. A third variant is the most insidious: **double-close / late-attribute**. The runtime, aware of the problem, attempts to set usage attributes in a post-stream callback *after* `span.end()` has already been called (e.g., a background task that reconciles provider billing). OTel SDKs silently ignore `set_attribute` on an ended span. The reconciliation succeeds in application logs but never reaches the exported span — telemetry and billing diverge by construction. ## Condition of Validity This boundary holds whenever **all** of the following are true: - Usage is delivered as a discrete terminal event in the stream rather than as a header or a pre-computed field on the request. - The runtime closes the span in a `finally`/`with`-block whose exit is not conditioned on receiving that terminal usage event. - The provider does not guarantee a usage frame on tool-call termination or on cancellation. - The exporter is batch/async, so there is no synchronous read-back that could detect the zero-usage span before it leaves the process. It does **not** apply when the runtime buffers the entire response (usage known before `end()`), when usage is attached via a separate `gen_ai.usage` event span rather than span attributes, or when a gateway normalizes usage and owns the span lifecycle. ## Decision Boundary The invariant to enforce: **a `gen_ai.chat` span must not be closed until either a usage fact has been recorded or an explicit "usage-unknown" marker has been set, and the two must be mutually exclusive.** Concretely: - If the terminal usage event was received → set `gen_ai.usage.input_tokens` / `output_tokens`, then `end()`. - If the stream ended without usage (tool-call finish, cancellation, provider omission) → set an explicit sentinel (e.g., `gen_ai.usage.unknown = true` plus the finish reason) *before* `end()`. Never leave the attributes absent, because absent is indistinguishable from zero at the backend. - On cancellation, drain the generator's terminal frame if the provider supports it, or record the partial-completion estimate with a provenance attribute; do not silently close. The boundary decision is: *reconcile before seal, or seal with an explicit unknown — never seal with a default that reads as zero.* The failure is choosing the third option by omission. ## Operational Effect Unreconciled closure produces a trace that is syntactically valid and semantically false. Downstream cost attribution, token-budget enforcement, and any agent that uses prior spans to estimate context pressure all read zero and under-provision. Worse, because the error is a *missing attribute* rather than a malformed one, schema validation passes and no alert fires. The only durable fix is to treat span closure as a commit point guarded by the usage-or-unknown invariant, enforced at the runtime boundary rather than patched in the exporter. ```python class UsageReconciliationError(RuntimeError): """Raised when a gen_ai span is about to close without a usage fact or explicit unknown marker.""" def close_chat_span(span, usage: dict | None, finish_reason: str, cancelled: bool) -> None: # Enforce the invariant: usage OR explicit-unknown, never silent absence. if usage is not None: span.set_attribute("gen_ai.usage.input_tokens", usage["input_tokens"]) span.set_attribute("gen_ai.usage.output_tokens", usage["output_tokens"]) else: if finish_reason == "tool_calls" or cancelled: # Provider omitted usage on a boundary/cancel — mark it, do not default to 0. span.set_attribute("gen_ai.usage.unknown", True) span.set_attribute("gen_ai.response.finish_reason", finish_reason) span.set_attribute("gen_ai.usage.cancelled", cancelled) else: # Normal completion with no usage is a bug in the stream consumer. raise UsageReconciliationError( f"chat span closing without usage and without boundary reason " f"(finish_reason={finish_reason!r}, cancelled={cancelled})" ) span.end() ```