# Under what conditions must an instance refuse to emit a `gen_ai.usage.*` token count for a tool-call span whose payload it never fully observed? **Date of Record:** 2026 November 22 **Scope:** Applies to any agent runtime that wraps tool invocations in OpenTelemetry spans carrying `gen_ai.*` semantic conventions and derives `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` from provider-reported or locally-counted telemetry. Does not apply to spans where the runtime is the sole tokenizer of record and owns the full prompt/completion byte stream end-to-end. ## Core Distinction The failure here is not "wrong token count." It is the **silent substitution of a *measured* attribute with an *estimated* attribute under the same semantic key**, when the span's observation window did not cover the bytes being counted. OpenTelemetry's GenAI conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *reported* usage — the provider's authoritative accounting of the request/response it processed. They are not "an approximation of how big this span was." An agent that streams a tool call, truncates the model's output at a token budget, retries a provider call, or routes through a proxy that strips `usage` from the final chunk will frequently *not* possess the authoritative count. The boundary condition is: **the span exists and is exportable, but the usage payload that would populate it was never observed within the span's lifetime.** The tempting move is to fill the field with a local `tiktoken`-style estimate so the attribute is "present." That is the violation. The invariant is that the presence of `gen_ai.usage.*` asserts measurement provenance, and an unmeasured span must omit the attribute (or emit it with an explicit estimate marker) rather than forge a measured one. ## What Was Observed A multi-step agent performing a retrieval tool call over a streaming transport. The span lifecycle: 1. `tool_call` span opens with `gen_ai.operation.name = "execute_tool"`, `gen_ai.tool.name = "vector_search"`. 2. The runtime sends the prompt fragment to the provider via SSE streaming. The first chunk arrives with `prompt_tokens` in a `message_start` event; the runtime records `gen_ai.usage.input_tokens = 1841`. 3. Mid-stream, the agent's token-budget guard fires (`max_completion_tokens` reached). The runtime **cancels the stream** and closes the span. 4. Because the stream was cancelled, the terminal `message_delta` event — the *only* place the provider reports `output_tokens` — never arrives. 5. The span closes with `gen_ai.usage.input_tokens = 1841` and **no** `gen_ai.usage.output_tokens`. 6. A downstream cost-attribution pipeline, keyed on the assumption "if the span has input tokens it has output tokens," coalesces missing output to `0`. The observable defect surfaced three hops later: the tool-call span reported **zero output tokens** for a call that demonstrably produced 512 tokens of text before cancellation. The cost dashboard under-billed by a factor proportional to cancellation frequency, and — more insidiously — a downstream *auditor agent* reading these spans to reconstruct "how much did this step cost" concluded the step was nearly free, which biased its routing decisions toward the streaming path that cancelled most often. The telemetry error fed back into agent policy. The root distinction: `input_tokens` was **observed** (arrived in `message_start`), `output_tokens` was **not observed** (would have arrived in a `message_delta` that cancellation prevented). The two attributes share a prefix and a semantic family but have *different observation windows within the span*. Treating them as a unit is the bug. ## Condition of Validity The invariant holds — and the refusal to emit is mandatory — under the conjunction: - **C1 (partial observation):** The span's lifetime ended before the provider's terminal usage event was received. Detectable by tracking whether a `usage`-bearing terminal event was consumed before `span.end()`. - **C2 (no authoritative fallback):** No secondary authoritative source exists for the count — e.g., a provider `/usage` reconciliation endpoint, or a billing webhook keyed to the same request ID. If such a source exists, the span may be *retroactively amended* (see Decision Boundary). - **C3 (attribute would be read as measured):** Downstream consumers key on attribute *presence*, not on an accompanying provenance flag. If every consumer already checks a `gen_ai.usage.source = "estimated"` marker, the refusal can be relaxed to a *marked* estimate. If C1 fails (full observation), emit the reported value. If C2 fails (authoritative reconciliation available), defer and amend. If C3 fails (consumers are provenance-aware), emit marked estimates. The refusal is *required* only when all three hold — which is the common case for streaming agents behind cost dashboards. ## Decision Boundary The boundary is **observation completeness, not span success**. A span that ends in `ERROR` status can still carry a fully-observed usage count (the provider replied with an error body that included `usage`). Conversely, a span that ends in `OK` can be unmeasured (clean cancellation, budget exhaustion, client disconnect after partial success). Do not gate usage emission on `span.status`; gate it on whether the terminal usage event was *consumed*. Two architectural guardrails: 1. **Track usage-event consumption as a first-class span state.** The runtime must maintain a boolean `usage_terminal_seen` per span, flipped only when the specific event carrying authoritative counts is parsed. `span.end()` consults it. This is a *transport-layer* fact, not a model-layer guess. 2. **Never synthesize `gen_ai.usage.*` from a local tokenizer under the measured key.** If an estimate is operationally necessary (e.g., for real-time budget enforcement), emit it under a distinct key — `gen_ai.usage.estimated_output_tokens` or an explicit `gen_ai.usage.source = "local_tokenizer"` attribute — so that a consumer filtering on `gen_ai.usage.output_tokens` is structurally guaranteed to see only measured values. For the retroactive-amendment path (C2 fails), the span is held in a `PENDING_USAGE` state and amended out-of-band when reconciliation lands, with the amendment itself recorded as a linked span event so replay-based auditors can distinguish "measured at close" from "measured at reconcile." ## Operational Effect Enforcing the refusal converts a *silent under-count* into a *visible absence*, which is the only form a downstream agent can reason about correctly. The auditor agent that previously read `output_tokens = 0` and concluded "cheap" now sees the attribute *missing* and can apply a policy: "unmeasured spans are excluded from cost-weighted routing, or routed to the non-streaming path until reconciliation completes." Absence is a signal; zero is a lie. The secondary effect is on **replay determinism**. An agent that reconstructs its own history from exported spans — a common pattern for episodic-to-semantic distillation — will, under the old behavior, distill a memory that says the cancelled step was free, and will preferentially re-select the cancellation-prone path. Under the new behavior, the missing attribute propagates as "unknown cost," which the distillation step can correctly treat as a *gap* rather than a *datum*. This is the difference between a memory system that learns from its telemetry and one that is poisoned by it. The cost is that dashboards must handle `null` usage. That is a schema change, not a correctness regression — and it is the correct place to pay. ```python from dataclasses import dataclass, field from typing import Optional class UnmeasuredUsageError(RuntimeError): """Raised when a span attempts to emit a measured gen_ai.usage attribute without having consumed the provider's terminal usage event.""" pass @dataclass class GenAiSpan: name: str operation: str usage_terminal_seen: bool = False input_tokens: Optional[int] = None output_tokens: Optional[int] = None attributes: dict = field(default_factory=dict) def on_usage_event(self, kind: str, tokens: int) -> None: # 'message_start' carries input; 'message_delta' is the terminal output event. if kind == "message_start": self.input_tokens = tokens elif kind == "message_delta": self.output_tokens = tokens self.usage_terminal_seen = True else: raise UnmeasuredUsageError(f"unknown usage event kind: {kind}") def close(self, cancelled: bool) -> None: if self.input_tokens is not None: self.attributes["gen_ai.usage.input_tokens"] = self.input_tokens if self.output_tokens is not None and self.usage_terminal_seen: self.attributes["gen_ai.usage.output_tokens"] = self.output_tokens elif cancelled and not self.usage_terminal_seen: # Refuse to forge a measured output count. Emit a marked estimate # under a distinct key so measured-key consumers never see it. if self.output_tokens is not None: self.attributes["gen_ai.usage.estimated_output_tokens"] = self.output_tokens self.attributes["gen_ai.usage.source"] = "local_tokenizer" # Deliberately omit gen_ai.usage.output_tokens. else: raise UnmeasuredUsageError( f"span {self.name!r} closed without terminal usage event " f"and without a cancellation justification; cannot emit " f"measured output_tokens" ) def emit_span(span: GenAiSpan, *, cancelled: bool) -> dict: span.close(cancelled=cancelled) if "gen_ai.usage.output_tokens" in span.attributes and not span.usage_terminal_seen: # Defensive invariant check: measured key must imply measurement. raise UnmeasuredUsageError( f"invariant violated on span {span.name!r}: measured output_tokens " f"present without usage_terminal_seen" ) return span.attributes ```