# In what scenarios must an instance refuse to close a GenAI agent span when `gen_ai.usage.output_tokens` is unknown rather than emitting zero **Date of Record:** 2026 November 30 **Scope:** Applies to any instrumentation layer emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) for agent invocations and tool calls, where the span's end-of-life token accounting is derived from streaming or partial provider responses. Does not apply to batch/offline token reconciliation jobs that run after span export, nor to non-GenAI spans. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *optional* integer attributes. That optionality is a schema-level statement about presence, not a statement about *meaning*. The failure mode examined here is the conflation of "attribute absent" with "attribute is zero." An instrumentation layer that defaults a missing `output_tokens` to `0` produces a span that is syntactically valid, passes schema validation, exports cleanly, and is semantically false. Downstream cost attribution, budget enforcement, and anomaly detection all consume that `0` as a measurement, not as a null, and the error is silent because nothing in the OTel pipeline rejects a zero. The invariant that must hold: **a GenAI agent span may be closed with `output_tokens` absent (attribute not set), but must never be closed with `output_tokens = 0` unless the provider actually reported zero generated tokens.** Absence is recoverable; a false zero is not, because the distinction is destroyed at export time and cannot be reconstructed from the span alone. ## What Was Observed A streaming agent loop wraps each model call in a span. The provider streams deltas and, in the terminal chunk, emits a `usage` object with `completion_tokens`. Instrumentation accumulates deltas and, on stream end, reads `usage.completion_tokens` to populate `gen_ai.usage.output_tokens`. Three concrete triggers produce a missing terminal usage object: 1. **Client-side cancellation.** The agent's token-budget guard trips mid-stream and the consumer closes the HTTP response before the terminal chunk arrives. Deltas were received; no `usage` object ever arrives. 2. **Provider truncation on `finish_reason=length`.** Some providers omit the usage block when generation is cut by `max_tokens`, or emit it only on a subsequent non-streaming call. 3. **Streaming transport reset.** A connection reset after the last content delta but before the usage chunk. The agent has valid output text, an incomplete accounting record, and no signal distinguishing "zero tokens" from "unknown." In each case the naive instrumentation path is `span.set_attribute("gen_ai.usage.output_tokens", usage.get("completion_tokens", 0))`. The `.get(..., 0)` is the defect. It fabricates a measurement. Observed downstream consequence: a per-agent cost dashboard showed a subset of high-frequency, low-latency agent spans with `output_tokens = 0` but non-empty `gen_ai.completion` content and non-zero span duration. Budget enforcement, which summed `output_tokens` to gate the next call, under-counted spend and allowed the agent to exceed its token ceiling by a margin proportional to the number of cancelled/truncated streams. The spans were *valid*; the aggregate was *wrong*. ## Condition of Validity The guardrail is only correct under a precise condition, and stating it prevents over-correction: - **Valid to set `output_tokens = 0`:** the provider's terminal usage object was received *and* reported `completion_tokens == 0` (e.g., a tool-call-only turn with no text, or a refusal with empty completion). Here zero is a true measurement. - **Valid to omit `output_tokens`:** the terminal usage object was not received, was malformed, or the stream was cancelled/reset before it arrived. The attribute must be *absent*, and a companion attribute such as `gen_ai.usage.output_tokens.unknown = true` (or an OTel span event `usage_accounting_incomplete`) should record *why*. - **Invalid in all cases:** synthesizing `0` from a missing value, or estimating from delta count and presenting the estimate as `output_tokens` without a distinct attribute name (e.g., `gen_ai.usage.output_tokens.estimated`). The distinction is only preservable if the instrumentation tracks *provenance* of the usage value through the stream lifecycle. A single `.get(key, default)` collapses provenance and is therefore structurally incapable of honoring the invariant. ## Decision Boundary The boundary is whether the terminal usage record was *observed*. This is a three-state problem — `observed(value)`, `observed_zero`, `not_observed` — and the instrumentation must carry all three states to span close. Collapsing to two states (value / default) is the boundary violation. Operationally, at span end the instrumentation must branch: - `not_observed` **and** span is a model-call span → do **not** set `output_tokens`; set `gen_ai.usage.output_tokens.unknown = true`; do not raise (the agent should still complete). - `not_observed` **and** the caller declared a hard budget invariant requiring exact accounting → raise a specific error and fail the span with `status = ERROR` and an exception event, so the budget layer sees an accounting failure rather than a silent zero. - `observed_zero` → set `output_tokens = 0`; this is correct and must not be treated as unknown. The non-obvious part: the *same* missing-usage condition must be handled differently depending on whether the enclosing agent declared exact-accounting semantics. A best-effort analytics agent omits and continues; a metered agent that reconciles against a hard quota must fail closed, because a false zero there is a correctness bug in billing, not a cosmetic gap. ## Operational Effect Honoring the invariant changes three system behaviors: 1. **Cost and budget aggregates become conservative.** Sums over `output_tokens` now under-count only by *explicitly flagged* unknown spans, which can be counted and bounded (`count(unknown) / count(total)`), rather than by silently fabricated zeros that are invisible in aggregate. 2. **Anomaly detection regains a signal.** A spike in `output_tokens.unknown = true` is a real, actionable indicator of cancellation storms, provider truncation, or transport resets. The previous `0` default masked exactly this signal by making the failure look like normal low-cost traffic. 3. **The span becomes replayable for reconciliation.** Because absence is preserved, a later batch job can join the span to the provider's usage export by request ID and backfill the true value. A fabricated `0` destroys the join key's semantics — you cannot tell which zeros were real. The cost of the guardrail is that some dashboards must now handle a null rather than a zero, and a metered agent must be prepared to fail a span on accounting loss. Both are preferable to a valid-looking span that lies. ```python from __future__ import annotations from dataclasses import dataclass from enum import Enum class UsageAccountingError(RuntimeError): """Raised when an agent span cannot be closed with trustworthy token accounting.""" class UsageState(Enum): OBSERVED = "observed" # provider reported a concrete value (may be zero) NOT_OBSERVED = "not_observed" # terminal usage record never arrived @dataclass(frozen=True) class TerminalUsage: state: UsageState output_tokens: int | None # None iff state is NOT_OBSERVED def close_agent_span( span_attrs: dict, usage: TerminalUsage, requires_exact_accounting: bool, ) -> dict: """ Apply the accounting invariant at span close. - OBSERVED (including zero) -> set output_tokens verbatim. - NOT_OBSERVED + best-effort -> omit output_tokens, flag unknown. - NOT_OBSERVED + exact-accounting -> fail closed; never fabricate zero. """ if usage.state is UsageState.OBSERVED: if usage.output_tokens is None: raise UsageAccountingError( "OBSERVED usage state requires a concrete output_tokens value" ) span_attrs["gen_ai.usage.output_tokens"] = usage.output_tokens return span_attrs # NOT_OBSERVED: absence is the only honest representation. if requires_exact_accounting: raise UsageAccountingError( "terminal usage record missing under exact-accounting contract; " "refusing to emit gen_ai.usage.output_tokens=0" ) span_attrs.pop("gen_ai.usage.output_tokens", None) span_attrs["gen_ai.usage.output_tokens.unknown"] = True return span_attrs def _demo() -> None: # Truncated stream, metered agent: must fail closed, not emit zero. try: close_agent_span( span_attrs={}, usage=TerminalUsage(UsageState.NOT_OBSERVED, None), requires_exact_accounting=True, ) except UsageAccountingError: pass # span marked ERROR, accounting loss surfaced to budget layer # Genuine zero-token tool-call turn: zero is a real measurement. attrs = close_agent_span( span_attrs={}, usage=TerminalUsage(UsageState.OBSERVED, 0), requires_exact_accounting=True, ) assert attrs["gen_ai.usage.output_tokens"] == 0 if __name__ == "__main__": _demo() ```