# Where must an instance reconcile OpenTelemetry GenAI token-usage spans when a streaming completion terminates without a terminal finish_reason **Date of Record:** 2026 December 1 **Scope:** Applies to agents that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) around streaming LLM calls and use those spans as the authoritative record of token consumption and completion status. Does not apply to non-streaming single-shot calls that always return a `finish_reason`, nor to billing pipelines that read provider-side usage APIs directly. ## Core Distinction The GenAI semantic conventions bind a span's terminal attributes — `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and `gen_ai.response.finish_reasons` — to the *end* of the request lifecycle. For a streaming call, the convention's implicit assumption is that the stream's terminal event carries both the usage block and the finish reason, so the span can be finalized atomically at `END`. The distinction that matters operationally is between **transport termination** (the SSE/HTTP stream closed, the socket ended, the `END` span event fired) and **semantic termination** (the model produced a `finish_reason` of `stop`, `length`, `tool_calls`, or `content_filter`). These are not the same event, and the semantic convention does not give you a hook that distinguishes them. When transport terminates before semantic termination — mid-stream disconnect, proxy idle timeout, client cancellation, provider-side abort — the span closes with a *syntactically valid but semantically incomplete* attribute set. The OTel collector accepts it. The trace looks healthy. The token counts are wrong, and nothing in the schema flags them. ## What Was Observed A tool-using agent issued a streaming `chat.completions` call with a 4,096-token output budget. The provider began emitting deltas normally; at delta 812 the upstream load balancer's 60-second idle timer fired (a tool-call argument was being generated slowly enough that no SSE keepalive arrived), and the connection was reset. The client library surfaced this as a clean iterator exhaustion — `for chunk in stream:` simply stopped yielding — not as an exception. The agent's span wrapper was structured as: 1. Start span, set `gen_ai.request.model`, `gen_ai.request.max_tokens`. 2. Accumulate `chunk.choices[0].delta.content` into a buffer. 3. On loop exit, read `chunk.usage` from the last chunk seen and set usage attributes. 4. Set `gen_ai.response.finish_reasons` from the last chunk's `finish_reason`. 5. `span.end()`. The failure trace: the last chunk *seen* was a content delta at index 812 with `finish_reason: None` and `usage: None`. Step 3 set `gen_ai.usage.output_tokens = 0` (the `.get` default) and `input_tokens = 0`. Step 4 set `finish_reasons = [None]`, which the OTel GenAI validator coerces to the string `"None"` — a value not in the enum `{stop, length, tool_calls, content_filter, function_call}`. The span ended with `status = UNSET` (no exception was raised, so no `ERROR` status was set). Downstream, the agent's cost ledger read `output_tokens=0` for a call that had actually consumed ~812 tokens, and its retry logic — keyed on `finish_reasons == "length"` — did not trigger, so the truncated tool-call arguments were passed to the tool executor as if complete. The tool rejected malformed JSON, the agent retried the *tool*, not the *model*, and burned four retries against the same truncated arguments before a human intervened. The non-obvious part: the trace was not missing data. It contained *confidently wrong* data. `output_tokens=0` is indistinguishable, at the attribute level, from a genuinely empty completion. The `finish_reasons=["None"]` string is the only signal that something was off, and it is a string that no consumer was written to check because it is not in the documented enum — it is an artifact of the SDK's coercion, not a convention-defined sentinel. ## Condition of Validity The invariant that must hold for span-based token accounting to be sound is: **a span may set terminal usage and finish-reason attributes only if semantic termination was observed; otherwise it must be marked incomplete and its usage attributes left unset (absent), not defaulted.** Absent attributes are distinguishable from zero; zero-valued attributes are not. This is the whole game. The condition of validity for the convention's accounting guarantee is therefore that the emitter distinguishes "the model said it was done" from "the stream stopped." It does not hold when: - The client library converts transport errors into iterator exhaustion (common in several SSE parsers). - The span wrapper uses `.get("usage", {})` or `or 0` defaults on terminal fields. - The wrapper finalizes on `finally:` blocks without checking whether a `finish_reason` was ever observed. - Provider keepalive behavior is not modeled, so idle-timeout disconnects are misclassified as clean ends. It *does* hold when the emitter tracks a `saw_terminal_event` boolean set only on a chunk whose `finish_reason` is non-null, and gates all terminal attribute writes on it. ## Decision Boundary The boundary is: **does the emitter have positive evidence of semantic termination at the moment it writes terminal attributes?** If yes, write usage and `finish_reasons` normally and set span status per the convention. If no, the correct action is to *not* write `gen_ai.usage.*` and *not* write `gen_ai.response.finish_reasons`, set `span.status = ERROR` with a description like `stream_terminated_without_finish_reason`, and — critically — set a custom attribute such as `gen_ai.response.incomplete = true` so downstream consumers can branch without parsing status descriptions. The agent's control flow must also branch: an incomplete stream is not a completed turn, so tool-call arguments accumulated from it must be discarded, not executed, and the retry must target the *model call*, not the tool. The temptation to "fill in" usage from a local tokenizer estimate is a second boundary violation: it produces a number that looks like provider-reported usage but is not, and it silently poisons cost attribution and any downstream budget enforcement keyed on `gen_ai.usage.output_tokens`. If an estimate is needed, it belongs in a distinct attribute (`gen_ai.usage.estimated_output_tokens`) that no billing path reads. ## Operational Effect Enforcing the invariant changes three behaviors. First, cost ledgers stop under-counting aborted streams as zero-token calls; the calls show up as *unaccounted*, which is a signal an operator can act on, rather than as *free*, which is a silent leak. Second, retry logic keyed on `finish_reasons` gains a second trigger — `incomplete == true` — so truncated tool-call arguments are never handed to executors. Third, trace-based debugging becomes honest: a span that ended without a finish reason is visibly an error span, so the "why did this agent loop four times" investigation lands on the model call rather than on the tool. The cost is that every streaming wrapper must carry a terminal-event latch and a `finally` block that inspects it — a small amount of code that is easy to omit and, when omitted, fails silently in exactly the direction that inflates apparent reliability. ```python from dataclasses import dataclass, field from typing import Optional class IncompleteStreamError(RuntimeError): """Raised when a streaming completion ends without a terminal finish_reason.""" pass @dataclass class GenAISpanState: saw_terminal_event: bool = False finish_reason: Optional[str] = None input_tokens: Optional[int] = None output_tokens: Optional[int] = None content_buffer: str = "" tool_call_buffer: str = "" attributes: dict = field(default_factory=dict) def observe_chunk(self, chunk: dict) -> None: choice = chunk["choices"][0] delta = choice.get("delta", {}) self.content_buffer += delta.get("content") or "" self.tool_call_buffer += (delta.get("tool_calls") or [{}])[0].get("function", {}).get("arguments", "") or "" reason = choice.get("finish_reason") if reason is not None: self.saw_terminal_event = True self.finish_reason = reason usage = chunk.get("usage") or {} # Only trust usage that arrives alongside a terminal event. self.input_tokens = usage.get("prompt_tokens") self.output_tokens = usage.get("completion_tokens") def finalize_span(self) -> dict: if not self.saw_terminal_event: # Do NOT default usage to 0; leave absent and mark incomplete. self.attributes["gen_ai.response.incomplete"] = True self.attributes["span.status"] = "ERROR" self.attributes["span.status_description"] = ( "stream_terminated_without_finish_reason" ) raise IncompleteStreamError( "stream closed after " f"{len(self.content_buffer)} content chars and " f"{len(self.tool_call_buffer)} tool-call chars " "with no finish_reason; refusing to write usage attributes" ) self.attributes["gen_ai.response.finish_reasons"] = [self.finish_reason] self.attributes["gen_ai.usage.input_tokens"] = self.input_tokens self.attributes["gen_ai.usage.output_tokens"] = self.output_tokens self.attributes["gen_ai.response.incomplete"] = False self.attributes["span.status"] = "OK" return self.attributes def run_streaming_turn(stream, span_state: GenAISpanState) -> dict: try: for chunk in stream: span_state.observe_chunk(chunk) except (ConnectionResetError, TimeoutError): # Transport termination without semantic termination. pass # fall through to finalize, which will raise return span_state.finalize_span() ```