# How should an instance reconcile OpenTelemetry GenAI `gen_ai.usage.*` token counts when a streamed tool-call span closes before the provider's final usage chunk arrives **Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.*`) and that stream provider responses where usage metadata is delivered out-of-band (a terminal `usage` chunk, a `message_delta` event, or a trailer frame) rather than in the assistant message body. Does not apply to non-streaming completion paths where the full response object is available before span end, nor to purely local tokenizers used for pre-flight budget estimation. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as **span-final attributes**: they are set on the span that represents the model invocation, and they are expected to be present and correct at `span.end()`. But in the streaming protocol used by every major provider, the token counts are the **last** thing to arrive — they are computed after generation completes and are shipped in a terminal frame that is logically part of the response but temporally after the last content delta. A span that closes on "stream EOF" or on "tool-call arguments fully assembled" is closing *before* the accounting frame that the convention requires. The two events — span lifecycle end and usage availability — are ordered oppositely to what the convention assumes. The non-obvious consequence: an agent that assembles a tool call from streamed deltas and then immediately closes the tool-call span (a natural, correct-looking choice, since the tool call is "done") will emit a span with **no usage attributes at all**, or with the counts of the *previous* invocation if the accumulator was not reset. Neither is a schema violation that any validator catches — the attributes are optional in the proto — so the corruption is silent and appears downstream only as under-counted token budgets, mispriced cost dashboards, and context-window headroom computed against a lie. ## What Was Observed A tool-calling agent loop over a streaming chat endpoint. The runtime opened a `gen_ai.chat` span per model turn, set `gen_ai.request.model`, `gen_ai.operation.name`, and request parameters at start, and accumulated streamed deltas. When the provider emitted a `tool_use` block, the runtime assembled the JSON arguments from `input_json_delta` fragments, invoked the tool, and closed the span with `gen_ai.tool.name` and `gen_ai.tool.call.id` set. The usage frame — `{"type":"message_delta","usage":{"output_tokens":N}}` plus the input count carried from `message_start` — arrived in the same byte stream but was consumed by the transport loop *after* the tool-dispatch branch had already returned and ended the span. Three distinct failure traces were observed across runs: 1. **Absent attributes.** Span exported with no `gen_ai.usage.*` keys. The exporter does not synthesize them; the collector's metrics connector drops the sample. Token totals for the turn are simply missing from the aggregate. 2. **Carried-over attributes.** When the runtime reused a span-builder object across turns (a common pooling optimization), the previous turn's `output_tokens` were re-emitted on the current span. The value is plausible — same order of magnitude — so nothing flags it. Cumulative output-token accounting drifts monotonically upward across a long agent session. 3. **Late-arrival orphan.** When the runtime instead deferred `span.end()` to stream EOF, the usage frame arrived but the span had already been marked non-recording by an earlier `with span:` context exit; the attribute set was a no-op and the span exported token-less. The stream *did* carry the truth; the span was closed to it. The observable signature in all three cases is the same at the collector: a `gen_ai.chat` span whose `gen_ai.usage.output_tokens` is absent or whose value is inconsistent with the observed `gen_ai.response.finish_reasons` and content length. There is no error, no retry, no log line. ## Condition of Validity The invariant that must hold is: **the span representing a model invocation must not be ended until either (a) the provider's terminal usage frame has been consumed and its counts attached, or (b) a bounded deadline has elapsed, at which point the span is ended with an explicit `gen_ai.usage.*` absence marker rather than a fabricated or stale value.** This is a *lifecycle ordering* invariant, not a data-format one. It is valid only when the runtime can distinguish "stream closed because the response is complete" from "stream closed because the transport dropped." If the runtime treats EOF as completion unconditionally, the invariant is unenforceable and the failure is guaranteed on every tool-calling turn. It is *not* valid to satisfy the invariant by re-deriving counts from a local tokenizer and writing them as `gen_ai.usage.*`. The convention's fields are defined as provider-reported usage; a locally estimated count that masquerades as provider truth defeats the purpose of the attribute and makes cost attribution unauditable. If the terminal frame is genuinely lost, the correct move is to omit the attributes and record the loss on a separate, clearly-named attribute (e.g. a custom `agent.usage.missing_reason`), never to backfill the canonical keys. ## Decision Boundary The runtime must decide, at the moment a tool-call block completes assembly, whether to end the span now or hold it open. The decision boundary is **whether the provider's usage frame is known to be pending**. Two protocol shapes exist and they require opposite handling: - **Usage-in-message-body providers** (usage present on the final assistant message): end the span when the message is assembled; usage is already attached. Holding open gains nothing and risks leaking a span on a hung stream. - **Usage-in-terminal-frame providers** (usage in a trailing `message_delta` / `[DONE]`-adjacent frame): the span must remain open past tool-call assembly until the frame is consumed or the deadline fires. The tool *invocation* span is a separate, child span and may close immediately; only the enclosing `gen_ai.chat` span is held. The boundary is crossed wrongly whenever the runtime keys span lifecycle off "did I get the content I needed" rather than "did I get the accounting I am obligated to emit." A tool call is content-complete before it is accounting-complete; conflating the two is the defect. The guardrail is a per-provider capability flag — `usage_delivery: "terminal_frame" | "message_body"` — consulted by the span manager, plus a hard deadline (typically 2–5 s past last content byte) after which the span ends with the absence marker. The deadline is mandatory: a provider that never sends the frame must not pin the span open forever, or the exporter's queue backs up and *all* spans in the batch are delayed. ## Operational Effect With the ordering invariant enforced, token accounting becomes trustworthy at the cost of a small, bounded span-lifetime extension on terminal-frame providers — spans close a few milliseconds later, well within typical batch export windows. Cost dashboards, per-session budget enforcement, and context-window headroom calculations all read correct `gen_ai.usage.*` values, and the absence marker makes genuine frame loss visible as a countable event rather than an invisible hole. Without it, the failure is silent, monotonic under span-builder reuse, and only surfaces as "our token spend does not match the provider invoice" weeks later — at which point the per-span evidence needed to reconstruct which turns were mis-accounted has already been rolled up and discarded. The residual risk to watch: pooled span builders must be reset on acquisition, not on release, because the release path is exactly the path that skips when a span ends early. Reset-on-acquire makes carried-over counts impossible even if the ordering invariant is later violated by a new code path. ```python class UsageAccountingViolation(RuntimeError): """Raised when a gen_ai.chat span would close without valid usage accounting.""" USAGE_DELIVERY_TERMINAL_FRAME = "terminal_frame" USAGE_DELIVERY_MESSAGE_BODY = "message_body" class ChatSpan: def __init__(self, provider_usage_delivery: str, deadline_s: float = 5.0): self.provider_usage_delivery = provider_usage_delivery self.deadline_s = deadline_s self.usage = None # dict once terminal frame consumed self.content_complete = False self.frame_lost = False def attach_usage(self, input_tokens: int, output_tokens: int) -> None: self.usage = { "gen_ai.usage.input_tokens": input_tokens, "gen_ai.usage.output_tokens": output_tokens, } def mark_frame_lost(self) -> None: self.frame_lost = True def end(self) -> dict: # Invariant: never emit fabricated or stale counts as canonical usage. if self.provider_usage_delivery == USAGE_DELIVERY_TERMINAL_FRAME: if self.usage is None and not self.frame_lost: # Content finished but the accounting frame has not been consumed # and no deadline has fired: closing now would silently drop usage. raise UsageAccountingViolation( "terminal-frame provider: span ended before usage frame consumed; " "hold open until frame arrives or deadline marks frame_lost" ) if self.usage is None and self.frame_lost: # Explicit absence, never backfilled from a local tokenizer. return {"agent.usage.missing_reason": "terminal_frame_lost"} if self.provider_usage_delivery == USAGE_DELIVERY_MESSAGE_BODY: if self.usage is None: raise UsageAccountingViolation( "message-body provider: usage must be attached at assembly time" ) return dict(self.usage) def close_chat_span(span: ChatSpan, elapsed_since_last_byte: float) -> dict: if elapsed_since_last_byte > span.deadline_s and span.usage is None: span.mark_frame_lost() return span.end() ```