# Where must an instance reconcile GenAI token attributes when a streaming tool-call span closes before its usage chunk arrives **Date of Record:** 2026 November 28 **Scope:** Applies to agents that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) while streaming model responses that include tool calls, and that derive cost/latency telemetry from `gen_ai.usage.*` attributes. Does not apply to non-streaming completion calls, where usage is returned atomically with the final response body, nor to spans that carry no tool-call child. ## Core Distinction The GenAI semantic conventions treat a model-invocation span and its tool-call child spans as a single logical unit whose attributes are *finalized at span end*. But a streaming provider emits `tool_calls` deltas in the content stream and emits the `usage` object in a **separate trailing chunk** — frequently in a chunk that arrives *after* the last tool-call delta and, under backpressure or client-side early termination, after the client has already decided the tool call is "done" and closed the child span. The distinction that matters is not "did we get token counts" but **which span boundary is authoritative for the usage attributes**. The conventions attach `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` to the *model invocation* span, not the tool-call span. An agent that closes the invocation span on the `finish_reason == "tool_calls"` signal — which arrives before the usage chunk — will finalize a span whose token attributes are absent or zero, while the tool-call child spans it spawned are already exported and immutable. The failure is a **span-close ordering invariant violation**: usage telemetry is finalized on a boundary that precedes the data it must carry. ## What Was Observed A tool-using agent streams a chat completion. The wire sequence, in order, is: 1. `delta.role = "assistant"`, empty content. 2. One or more `delta.content` chunks (often empty for pure tool calls). 3. `delta.tool_calls[i]` chunks carrying `index`, `id`, `function.name`, and incrementally concatenated `function.arguments` fragments. 4. `finish_reason = "tool_calls"` on the final content delta. 5. `[DONE]` or a final chunk whose `usage` field is populated only if the request set `stream_options.include_usage = true`. The agent's span lifecycle was: open invocation span on request → open tool-call child span at first `tool_calls` delta → close tool-call child span at `finish_reason` → close invocation span at `[DONE]`. In the majority of runs this ordering is fine because `[DONE]` follows the usage chunk within milliseconds. The observed failure: when the client applies a **read timeout on the trailing chunk** (a common guard against stalled streams), the reader loop raises after `finish_reason` but before the usage chunk. The tool-call child span has already been closed and enqueued to the exporter with `gen_ai.tool.name` and `gen_ai.tool.call.id` populated. The invocation span is closed in the `except` path with `gen_ai.usage.*` **never set**. Downstream cost aggregation, which sums `gen_ai.usage.output_tokens` across invocation spans, silently records the call as zero-cost. The tool call *did execute* — its child span proves it — so the ledger shows tool activity with no attributable model spend. This is a **telemetry continuity break masked as a clean shutdown**: no error attribute is set on the invocation span, so the loss is invisible to span-status filters. A second, subtler variant: with `include_usage = true`, some providers emit the usage chunk but the agent's accumulator has already been reset by the `finish_reason` handler, so the usage chunk lands in a "post-finish" branch that discards it. Same outcome, different trigger — the invariant is violated by *handler ordering*, not by transport. ## Condition of Validity The invariant — *an invocation span's `gen_ai.usage.*` attributes must be written from a source that is guaranteed to be observed before the span is finalized* — holds only when **all** of the following are true: - The provider emits usage in a chunk strictly after `finish_reason`. If usage is embedded in the `finish_reason` chunk itself (some gateways do this), the ordering hazard collapses and the naive close-on-finish is safe. - The client does not early-terminate the stream on `finish_reason`. If the reader stops reading at `finish_reason`, the usage chunk is guaranteed lost regardless of timeout. - Tool-call child spans are *not* the carrier of usage attributes. If a deployment copies usage onto child spans, the child-close-before-usage ordering becomes a second, independent violation. When any of these conditions fails, the "close on finish_reason" pattern is *observably correct* and the guardrail below is unnecessary overhead. The boundary is therefore **provider- and transport-dependent**, and must be probed, not assumed. ## Decision Boundary The agent must choose between two span-finalization strategies at the point `finish_reason` is observed: - **Finalize-on-finish:** close invocation span immediately. Cheap, low-latency export, but violates the usage invariant whenever usage trails `finish_reason`. - **Finalize-on-usage-or-drain:** keep the invocation span open and continue reading until either the usage chunk arrives or the stream is drained/closed by the transport, *then* finalize. This preserves the invariant but requires the span to survive a trailing read window and requires a bounded wait so a genuinely stalled stream cannot hold the span open indefinitely. The boundary condition that forces the second strategy is exactly: `finish_reason` observed AND `gen_ai.usage.output_tokens` unset AND stream not yet at `[DONE]`/EOF. At that point the agent must **not** finalize. It must transition the span into a "pending usage" state with a deadline (e.g., the remaining read-timeout budget), and on deadline expiry finalize with an explicit `gen_ai.usage.*` absence marker plus a span event recording the drain, so downstream cost aggregation can distinguish "zero tokens" from "tokens unknown." Conflating the two is the actual defect: zero is a claim, unknown is a gap, and the convention has no first-class "unknown" — so the agent must encode it as an event, not as a missing attribute. ## Operational Effect Without the guardrail, cost telemetry under-reports precisely on the calls that matter most — long tool-call streams that are most likely to hit trailing-chunk timeouts — and the under-reporting is *correlated with tool activity*, biasing any per-tool cost attribution toward zero. Auditors replaying spans to reconstruct spend will find tool-call child spans whose parent invocation span reports no output tokens, an internally inconsistent trace that the conventions do not flag as invalid. With the guardrail, the invocation span either carries accurate usage or carries an explicit drain event, and the replay is consistent: every tool-call child has a parent whose usage is either numeric or explicitly marked unknown. The cost of the guardrail is a bounded trailing-read window per invocation and a small increase in span-open duration, which must be accounted for in exporter queue sizing. ```python import time from dataclasses import dataclass, field from typing import Optional class UsageFinalizationError(RuntimeError): """Raised when an invocation span is finalized before usage telemetry is resolved.""" @dataclass class InvocationSpan: span_id: str gen_ai_usage_output_tokens: Optional[int] = None finalized: bool = False events: list = field(default_factory=list) def finalize(self) -> None: if self.finalized: raise UsageFinalizationError(f"span {self.span_id} finalized twice") self.finalized = True def close_invocation_span( span: InvocationSpan, finish_reason_seen: bool, stream_drained: bool, drain_deadline_s: float, now: float, ) -> None: """ Enforce the invariant: do not finalize an invocation span while finish_reason is seen, usage is unset, and the stream is still open. """ usage_missing = span.gen_ai_usage_output_tokens is None if finish_reason_seen and usage_missing and not stream_drained: remaining = drain_deadline_s - now if remaining > 0: # Keep span open; caller must continue draining for usage chunk. raise UsageFinalizationError( f"span {span.span_id}: finish_reason observed but usage chunk " f"not yet received; {remaining:.3f}s of drain budget remain. " "Refusing to finalize — would emit zero-cost tool activity." ) # Deadline expired: finalize but mark usage as explicitly unknown. span.events.append( {"name": "gen_ai.usage.drain_timeout", "attrs": {"drain_deadline_s": drain_deadline_s}} ) span.finalize() def handle_stream_end( span: InvocationSpan, finish_reason_seen: bool, usage_chunk_received: bool, stream_drained: bool, drain_deadline_s: float, ) -> None: if usage_chunk_received and span.gen_ai_usage_output_tokens is None: raise UsageFinalizationError( f"span {span.span_id}: usage chunk flagged received but attribute unset — " "accumulator reset by finish_reason handler." ) close_invocation_span( span=span, finish_reason_seen=finish_reason_seen, stream_drained=stream_drained, drain_deadline_s=drain_deadline_s, now=time.monotonic(), ) ```