# How should an instance reconcile OpenTelemetry GenAI token-accounting spans when a streaming tool-call span terminates before its final usage chunk arrives **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for LLM invocations and tool calls, where the model provider streams responses and reports token usage in a terminal chunk. Does not apply to non-streaming, single-shot completions where usage is delivered atomically with the response body. ## Core Distinction The GenAI semantic conventions treat a span as a *closed accounting unit*: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are attributes set at span end, and downstream cost/attribution pipelines assume that a span with `gen_ai.operation.name = "chat"` and a `status = OK` carries a complete usage record. The failure boundary is the gap between **span lifecycle** and **usage-chunk lifecycle** under streaming. In a streaming invocation the span *starts* before the first token and *ends* when the transport closes. The usage chunk (`message_delta` with `usage`, or the provider equivalent) is the **last** frame on the wire. These two events are ordered but not atomic. When the consumer aborts the stream — client disconnect, agent-side token-budget cutoff, tool-call early termination, or a read timeout on the final frame — the span closes `OK` with no usage attributes. The convention does not distinguish "completed, usage unknown" from "completed, zero tokens" from "aborted mid-stream." All three collapse into a span that looks successful but is unaccounted. The non-obvious part: this is not a data-loss bug in one exporter. It is a **semantic-convention under-specification** that propagates. A `status = OK` span missing `gen_ai.usage.*` is valid per the spec (attributes are optional), so validation passes, the span survives sampling and export, and the accounting pipeline silently treats it as a zero-cost or unknown-cost event. The invariant that must hold — *every `OK` chat span carries a usage record or an explicit "usage unavailable" marker* — is not enforced by the convention. ## What Was Observed A tool-calling agent loop streaming from a provider that emits usage in the terminal `message_delta` frame. Trace: 1. `gen_ai.chat` span opens; `gen_ai.request.model` and `gen_ai.operation.name` set. 2. Content deltas arrive; agent-side budget monitor counts output tokens incrementally and, at 92% of the configured per-call ceiling, issues `stream.abort()` to avoid overshoot. This is deliberate and correct behavior at the agent layer. 3. The provider never sends the terminal usage frame because the connection is torn down. 4. Span closes with `status = OK`, `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` **absent**. The abort reason is not recorded — there is no `gen_ai.response.finish_reasons` value because that too arrives in the terminal frame. 5. Export succeeds. Collector validation passes (attributes optional). Cost pipeline records the span as unaccounted and, depending on aggregation policy, either drops it or counts zero. Two spans in the same trace later showed a **reconciliation discrepancy**: the agent's own incremental token counter (which had counted deltas as they arrived) reported ~9,400 output tokens for the aborted call, while the telemetry pipeline reported nothing. Downstream, a per-session budget auditor that read from telemetry concluded the session used less than it did, and a second call was admitted that pushed the session past its real ceiling. The failure was not in either counter — it was that the two counters were never reconciled because the span carried no signal that a reconciliation was needed. A second observed mode: a tool-call span (`gen_ai.operation.name = "execute_tool"`) whose child chat span was aborted mid-stream still reported `OK`, because the tool executor caught the abort and returned a truncated result. The parent saw a successful tool call; the child saw an unaccounted chat. The trace *looked* internally consistent. ## Condition of Validity The reconciliation invariant holds only when all of the following are true: - The provider delivers usage in a terminal frame that is **separable** from content frames (true for most streaming APIs; false for providers that only emit usage in a header or a separate endpoint). - The agent runtime can distinguish **clean completion** (terminal frame received) from **abort** (stream closed by consumer) from **transport failure** (connection dropped). If the runtime collapses these into one "stream ended" event before span close, the invariant cannot be recovered at the telemetry layer. - The span-close path runs *after* the runtime has recorded its own incremental token count, so an aborted span can carry a **reconstructed** or **lower-bound** usage estimate with an explicit provenance attribute. - The accounting pipeline treats "usage attribute absent" and "usage attribute = 0" as **distinct** states. If the pipeline coerces missing to zero, the invariant is defeated regardless of what the runtime emits. Where any of these fail, the correct posture is to *not* treat the span as an accounting unit and to route the invocation through a side-channel usage ledger keyed by trace/span ID. ## Decision Boundary At span close, the runtime must decide between three mutually exclusive emissions: - **Complete:** terminal usage frame received. Set `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` from the frame. Set `gen_ai.response.finish_reasons`. `status = OK`. - **Aborted with local count:** stream closed by the consumer before the terminal frame. Set usage from the runtime's incremental counter, and set a custom attribute (e.g., `gen_ai.usage.provenance = "local_incremental"`) plus a finish reason of `"aborted"`. `status` must be `ERROR` or `UNSET` — *not* `OK`, because the invocation did not complete and the usage is a lower bound, not a measurement. - **Aborted without local count:** stream closed before any delta was counted, or counter unavailable. Emit **no** usage attributes, set `gen_ai.usage.provenance = "unavailable"`, `status = ERROR`. The absence is now *explicit and typed* rather than ambiguous. The boundary that is easy to get wrong: **an aborted stream must not be `OK`.** The convention's default of `OK` for a closed span is the trap. A span that ended because the consumer pulled the plug is not a successful call, and marking it `OK` is what lets it pass accounting validation while carrying no usage. The status field is the only signal the pipeline has; overloading `OK` to mean "span closed without error" rather than "invocation completed" is the root cause. A secondary boundary: the parent tool-call span must **propagate** the child's abort state. If the tool executor returns truncated output after an aborted chat, the tool span's status must reflect the degraded child, not mask it. Otherwise the trace's top-level status is a lie about the leaf. ## Operational Effect With this boundary enforced, three things change: 1. **Aborted calls become visible and costed.** The `local_incremental` provenance lets the pipeline reconcile against the runtime's counter and against provider billing (which *does* charge for aborted streams up to the abort point). The discrepancy between telemetry and billing, previously invisible, becomes a queryable signal. 2. **Budget auditors stop under-counting.** Because aborted spans are no longer `OK`-with-no-usage, a session-level auditor reading telemetry sees the true consumption and the admission gate for the next call holds. 3. **The convention's optionality is contained.** `gen_ai.usage.*` remains optional per spec, but the runtime now guarantees that *its* `OK` chat spans always carry usage, and that non-`OK` spans carry an explicit provenance marker. The invariant is enforced at emission, not assumed at consumption. The cost is that `OK` is no longer the default for a closed span — the runtime must actively classify. That is the correct trade: a span's status should describe the *invocation*, not the *span object's* lifecycle. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when a GenAI chat span cannot be reconciled to a usage record.""" class StreamOutcome(Enum): COMPLETE = "complete" # terminal usage frame received ABORTED_LOCAL = "aborted_local" # consumer closed; local counter valid ABORTED_UNKNOWN = "aborted_unknown" # consumer closed; no counter class SpanStatus(Enum): OK = "OK" ERROR = "ERROR" UNSET = "UNSET" @dataclass class GenAIChatSpan: trace_id: str span_id: str model: str outcome: StreamOutcome terminal_usage: Optional[dict] = None # from provider final frame local_output_count: Optional[int] = None # runtime incremental counter finish_reason: Optional[str] = None attributes: dict = field(default_factory=dict) def close(self) -> "GenAIChatSpan": """Apply the reconciliation invariant at span close.""" if self.outcome is StreamOutcome.COMPLETE: if not self.terminal_usage: # Terminal frame claimed complete but carried no usage. raise UsageReconciliationError( f"span {self.span_id}: COMPLETE outcome without terminal usage frame" ) self.attributes["gen_ai.usage.input_tokens"] = self.terminal_usage["input_tokens"] self.attributes["gen_ai.usage.output_tokens"] = self.terminal_usage["output_tokens"] self.attributes["gen_ai.usage.provenance"] = "provider_terminal" self.attributes["gen_ai.response.finish_reasons"] = [self.finish_reason or "stop"] self.attributes["otel.status_code"] = SpanStatus.OK.value return self if self.outcome is StreamOutcome.ABORTED_LOCAL: if self.local_output_count is None: raise UsageReconciliationError( f"span {self.span_id}: ABORTED_LOCAL without local counter" ) # Input tokens are unmeasurable post-abort; record as unknown, not zero. self.attributes["gen_ai.usage.output_tokens"] = self.local_output_count self.attributes["gen_ai.usage.input_tokens"] = None # explicit unknown self.attributes["gen_ai.usage.provenance"] = "local_incremental" self.attributes["gen_ai.response.finish_reasons"] = ["aborted"] # Aborted stream is NOT OK: the invocation did not complete. self.attributes["otel.status_code"] = SpanStatus.ERROR.value return self if self.outcome is StreamOutcome.ABORTED_UNKNOWN: # Emit no usage attributes; mark provenance so pipeline sees typed absence. self.attributes["gen_ai.usage.provenance"] = "unavailable" self.attributes["gen_ai.response.finish_reasons"] = ["aborted"] self.attributes["otel.status_code"] = SpanStatus.ERROR.value return self raise UsageReconciliationError( f"span {self.span_id}: unhandled outcome {self.outcome!r}" ) def validate_accounting_unit(span: GenAIChatSpan) -> None: """Invariant: every OK chat span carries a provider-terminal usage record.""" status = span.attributes.get("otel.status_code") provenance = span.attributes.get("gen_ai.usage.provenance") if status == SpanStatus.OK.value: if provenance != "provider_terminal": raise UsageReconciliationError( f"span {span.span_id}: OK status with provenance {provenance!r}; " "an OK chat span must carry provider-terminal usage" ) if span.attributes.get("gen_ai.usage.output_tokens") is None: raise UsageReconciliationError( f"span {span.span_id}: OK status with null output_tokens" ) else: # Non-OK spans must carry an explicit provenance marker, never silent absence. if provenance is None: raise UsageReconciliationError( f"span {span.span_id}: non-OK status without usage provenance marker" ) def reconcile(session_spans: list[GenAIChatSpan], session_ceiling: int) -> int: """Recompute session consumption; refuse to admit if telemetry under-counts.""" total = 0 for span in session_spans: validate_accounting_unit(span) out = span.attributes.get("gen_ai.usage.output_tokens") if out is not None: total += out elif span.attributes.get("gen_ai.usage.provenance") == "unavailable": # Cannot cost this span; fail closed rather than under-count. raise UsageReconciliationError( f"span {span.span_id}: usage unavailable; session accounting incomplete" ) if total > session_ceiling: raise UsageReconciliationError( f"session over ceiling: {total} > {session_ceiling}" ) return total ```