# What happens when an instance emits OpenTelemetry GenAI spans for a tool call whose token usage is reported after the span has already ended **Date of Record:** 2026 November 21 **Scope:** Applies to LLM agent instances instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where token usage is reported asynchronously or out-of-band relative to the span lifecycle. Does not apply to synchronous in-process instrumentation where usage is known before `span.end()`. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *span attributes* — immutable once the span is ended and exported. But many provider SDKs (streaming completions, batch inference, tool-calling loops) return usage only in a terminal chunk or a follow-up response. The boundary condition is this: **the span lifecycle and the usage-reporting lifecycle are two independent clocks, and the semantic convention assumes they are the same clock.** When they diverge, the span is exported with usage attributes absent, and the late-arriving counts have no legal place to land on that span. They get either dropped, attached to a *subsequent* span (attribution corruption), or attached as an event on an already-ended span (spec-violating, silently discarded by most exporters). The invariant that breaks: *a span's token usage must be monotonically attributable to exactly one span, before that span is exported.* ## What Was Observed A ReAct-style agent executes a tool call. The instrumentation wraps the LLM invocation in a span `chat gpt-4o` and the tool execution in a child span `execute_tool search`. The provider streams tokens; the terminal SSE chunk carries `usage: {prompt_tokens: 3120, completion_tokens: 480}`. The agent's span wrapper, written against the non-streaming path, calls `span.end()` as soon as the stream's `on_complete` fires — which, in the streaming SDK, fires *before* the usage-bearing terminal chunk is processed by the callback. Sequence: 1. `on_complete` → `span.set_status(OK)` → `span.end()` → span queued for `BatchSpanProcessor`. 2. `BatchSpanProcessor` exports the span with `gen_ai.usage.input_tokens` unset. 3. Terminal chunk parsed → `usage` available → instrumentation attempts `span.set_attribute("gen_ai.usage.input_tokens", 3120)`. 4. The SDK's span is already `is_recording() == false`; the attribute write is a no-op. No error, no warning. The exported span has `gen_ai.request.model=gpt-4o` and no usage attributes. Downstream cost aggregation sees a span with zero tokens. The next span in the loop (the tool span) inherits nothing. Over a 40-step agent run, 40 spans are exported, all usage-less, and the OTel-derived cost dashboard reports $0.00 for a run that cost $0.87. The corruption is silent because the semantic convention does not define a "usage pending" state — absence of `gen_ai.usage.*` is indistinguishable from "zero tokens" or "not measured." A subtler variant: some teams "fix" this by attaching usage to the *next* span via a mutable accumulator. Now span N carries span N-1's usage. The sum is correct; the per-span attribution is wrong, and any per-tool or per-model breakdown is poisoned. ## Condition of Validity The invariant holds only when, for every span carrying `gen_ai.usage.*`, the following is true at export time: - `span.end()` was called *after* the usage-bearing response element was consumed, and - the usage values were written to that same span object while `is_recording()` was true, and - no other span in the trace claims the same usage (no double-count via accumulator carry-over). This is *not* satisfied by: streaming completions where `finish_reason` and `usage` arrive in separate chunks; async tool-calling where the provider reports usage on a webhook; batch APIs where per-request usage is returned in a results file hours later; or any retry path where the first attempt's usage is reported but the retry's span is the one that ends. It *is* satisfied by synchronous non-streaming calls and by streaming wrappers that defer `span.end()` to the terminal usage chunk — which requires the wrapper to know the provider's chunk ordering, a provider-specific fact not encoded in the semantic conventions. ## Decision Boundary The forcing decision: **when the usage chunk is not guaranteed to precede stream completion, the span must not be ended on stream completion.** Two legal resolutions: 1. **Defer end.** Hold the span open until the terminal usage chunk is parsed (or a bounded timeout elapses), then write attributes and end. Cost: span duration now includes the usage-chunk latency, which inflates `gen_ai.server.request.duration` — so record the true completion time as a separate attribute (`gen_ai.response.finish_time`) and accept that span duration ≠ model latency for streaming spans. 2. **Two-span split.** End the `chat` span at completion with no usage, and emit a sibling `gen_ai.usage.record` event/span when usage arrives, linked by `trace_id` + a `gen_ai.response.id` correlation attribute. This preserves latency fidelity but violates the convention's expectation that usage lives on the chat span; consumers must be taught to join. The boundary is: if the provider guarantees usage-before-finish (non-streaming, or a streaming API documented to emit usage in the final chunk before `[DONE]`), resolve by deferring end with zero timeout risk. If the provider does *not* guarantee ordering, you must choose between latency distortion (option 1) and convention violation (option 2). There is no option that preserves both. ## Operational Effect Unbounded, the failure produces **silent zero-cost telemetry**: spans exist, traces are complete, but token accounting is empty, and the absence is indistinguishable from genuine zero usage. Cost dashboards, budget circuit-breakers, and rate-limit governors keyed on `gen_ai.usage.*` all read zero and never trip. The agent runs until the provider's hard quota rejects it — a failure that surfaces as a 429 mid-loop, not as a budget alarm. The second-order effect: because the spans *look* valid (correct model, correct operation name, correct status), no schema validator flags them; the corruption is only visible when summing usage against the provider's billing export and finding a mismatch. The guardrail is a post-export assertion: every `gen_ai.chat` span in a completed trace must carry both usage attributes, or the trace is marked `incomplete_usage` and the run is quarantined for reconciliation. ```python from dataclasses import dataclass, field from typing import Optional class UsageAttributionError(RuntimeError): """Raised when a GenAI span's token usage cannot be legally attributed.""" pass @dataclass class GenAISpan: name: str model: str ended: bool = False input_tokens: Optional[int] = None output_tokens: Optional[int] = None usage_claimed_by: Optional[str] = None events: list = field(default_factory=list) def end(self) -> None: self.ended = True def is_recording(self) -> bool: return not self.ended def set_usage(self, input_tokens: int, output_tokens: int, claimant: str) -> None: if not self.is_recording(): raise UsageAttributionError( f"span {self.name!r} already ended; usage ({input_tokens},{output_tokens}) " f"from {claimant!r} cannot be written" ) if self.usage_claimed_by is not None and self.usage_claimed_by != claimant: raise UsageAttributionError( f"span {self.name!r} usage already claimed by {self.usage_claimed_by!r}, " f"rejecting {claimant!r}" ) self.input_tokens = input_tokens self.output_tokens = output_tokens self.usage_claimed_by = claimant def export_span(span: GenAISpan) -> dict: if not span.ended: raise UsageAttributionError(f"span {span.name!r} exported before end()") attrs = {"gen_ai.request.model": span.model} if span.input_tokens is not None: attrs["gen_ai.usage.input_tokens"] = span.input_tokens attrs["gen_ai.usage.output_tokens"] = span.output_tokens else: attrs["gen_ai.usage.missing"] = True # explicit, not silent return attrs def run_streaming_call(span: GenAISpan, chunks: list[dict]) -> dict: """chunks arrive in order; usage may come in a terminal chunk AFTER finish.""" for chunk in chunks: if chunk.get("type") == "finish": # BUG: naive wrapper ends here, before usage chunk # span.end() pass if chunk.get("type") == "usage": span.set_usage( chunk["input_tokens"], chunk["output_tokens"], claimant="stream" ) if span.input_tokens is None: raise UsageAttributionError( f"stream for {span.name!r} completed with no usage chunk; " f"defer end() or emit gen_ai.usage.record event" ) span.end() return export_span(span) ```