# When must an instance distrust its own span's `gen_ai.usage.*` attributes: the streaming-finalization double-count boundary **Date of Record:** 2026 November 30 **Scope:** Applies to agents that emit OpenTelemetry spans carrying GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.response.finish_reasons`) and aggregate cost from those spans. Does not apply to batch, non-streaming, single-shot completions where the provider returns one terminal usage block and no partial deltas. ## Core Distinction There are two mutually incompatible ways to populate `gen_ai.usage.*` on a streaming call, and they are indistinguishable at the attribute level: 1. **Cumulative-snapshot semantics** — each chunk's usage reflects the running total so far; the final chunk carries the authoritative total. Cost = last value. 2. **Delta semantics** — each chunk's usage reflects only the tokens emitted in that chunk; the final chunk carries only the tail. Cost = sum of all values. The GenAI semantic conventions specify *which attribute names* to emit and that `gen_ai.usage.output_tokens` on the span should reflect total output tokens — but they do not, and cannot, constrain how a provider's streaming wire format delivers those numbers. The invariant that must hold is: **the span's terminal `gen_ai.usage.*` value is a total, not a sample, and it is written exactly once.** Both a "last-write-wins" recorder and a "sum-all-chunks" recorder will silently satisfy the attribute schema while violating that invariant for one of the two provider conventions. The failure is not a crash; it is a plausible-looking integer. ## What Was Observed A tool-using agent streamed a long completion (a multi-step plan synthesis) and recorded spans per model call. The instrumentation recorded usage on every streamed chunk and set the span attribute on each, so the span's final value was whatever chunk arrived last. For a provider using cumulative-snapshot semantics this is correct. For a provider that emits per-chunk deltas — common when a gateway normalizes multiple backends behind one endpoint — the "last chunk" carried only the final few tokens of the closing sentence. The span reported `gen_ai.usage.output_tokens = 7` for a 3,900-token completion. The cost ledger downstream summed `gen_ai.usage.output_tokens` across spans. A single misattributed call did not move the total much, so the error stayed below any per-call alerting threshold. It surfaced only when a monthly reconciliation compared the ledger against provider invoices and found a 22% under-count concentrated in the spans belonging to one route. The mechanism: the gateway route had been switched to a backend with delta semantics three weeks earlier, the instrumentation was unchanged, and *the attribute names were identical*, so no schema validation, no dashboard, and no span-level assertion fired. A second, subtler observation: when retries occurred, the retried attempt emitted its own span, and the retry-policy layer copied the failed attempt's `gen_ai.usage.input_tokens` onto the retry span as a "carried context" annotation. Under cumulative semantics the input tokens were already counted on the failed span; the copy double-counted input. The two errors — under-count on output, over-count on input — partially canceled in the aggregate, which is exactly why the discrepancy was hard to localize. ## Condition of Validity The invariant "terminal span usage equals total usage" is valid only when the recorder can answer three questions before it writes the attribute: - **Is this chunk terminal?** Determined by `gen_ai.response.finish_reasons` being non-empty or the stream closing cleanly — *not* by the presence of a usage field, since some providers attach usage to intermediate chunks. - **Is this provider cumulative or delta?** This is a per-route property, not a per-call property, and must be established from route configuration or a capability probe, never inferred from the numbers themselves (inference fails on the first chunk, where cumulative and delta are identical). - **Has a terminal value already been written?** A span attribute written twice is last-write-wins, so a late delta chunk arriving after the terminal chunk (possible under out-of-order multiplexing) overwrites the correct total with a fragment. If any of the three is unknown, the span must not be trusted for cost attribution. It may still be trusted for latency, model identity, and finish reason. ## Decision Boundary The boundary is between **recording** and **attesting**. An instrumentation layer may always record raw chunk usage as span events (`gen_ai.usage.*` on a per-chunk event, with a monotonically increasing `chunk.index`). It may only write the *terminal* `gen_ai.usage.*` attributes — the ones a cost aggregator reads — when it can prove the three conditions above. Concretely: - If route semantics are `cumulative`: write on terminal chunk only, overwrite is forbidden. - If route semantics are `delta`: accumulate in a span-scoped buffer, write once on terminal chunk. - If route semantics are `unknown`: write a sentinel — set `gen_ai.usage.output_tokens` to the accumulated *lower bound* and attach `gen_ai.usage.attribution = "unverified"` — and exclude from cost ledgers until reconciled. The failure mode is not "wrong number." It is "number of unknown provenance indistinguishable from a number of known provenance." The boundary is the point where provenance is dropped. ## Operational Effect Once the boundary is enforced, three things change. First, cost ledgers stop silently absorbing route changes: a route that flips from cumulative to delta semantics produces `attribution = "unverified"` spans rather than plausible small integers, and the reconciliation job flags them on the next run instead of at month-end. Second, retries no longer double-count input, because the retry span's usage is written from the retry's own terminal chunk and the failed attempt's usage is retained only as a span event, not as a copied attribute. Third, the aggregator can enforce a hard invariant: `sum(gen_ai.usage.output_tokens over spans with attribution = "verified")` must equal the provider's reported total within a small epsilon, and any span with `attribution = "unverified"` blocks the rollup rather than being silently included. The residual risk is a provider that changes semantics *within* a single stream — e.g., emits cumulative for the first half and deltas after a backend migration mid-stream. This is rare but observed at gateways under rolling deploys. The guardrail is a mid-stream consistency check: if a chunk's usage is less than the previous chunk's usage under a route declared cumulative, the recorder must downgrade the span to `unverified` and emit a `gen_ai.usage.semantics_violation` event. The invariant is not "the provider is consistent"; it is "the recorder never writes a total it cannot defend." ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class UsageSemantics(Enum): CUMULATIVE = "cumulative" DELTA = "delta" UNKNOWN = "unknown" class UnverifiedUsageError(RuntimeError): """Raised when a terminal usage attribute would be written without provable semantics.""" pass @dataclass class ChunkUsage: input_tokens: int output_tokens: int is_terminal: bool finish_reason: Optional[str] = None @dataclass class SpanUsageRecorder: semantics: UsageSemantics _accumulated_output: int = 0 _accumulated_input: int = 0 _last_cumulative_output: int = 0 _terminal_written: bool = False _violation: bool = False _events: list = field(default_factory=list) def observe(self, chunk: ChunkUsage) -> None: self._events.append(chunk) if self.semantics is UsageSemantics.CUMULATIVE: if chunk.output_tokens < self._last_cumulative_output: # Provider declared cumulative but regressed: semantics broken mid-stream. self._violation = True raise UnverifiedUsageError( f"cumulative usage regressed: {chunk.output_tokens} < " f"{self._last_cumulative_output}; downgrade span to unverified" ) self._last_cumulative_output = chunk.output_tokens self._accumulated_output = chunk.output_tokens self._accumulated_input = chunk.input_tokens elif self.semantics is UsageSemantics.DELTA: self._accumulated_output += chunk.output_tokens self._accumulated_input += chunk.input_tokens else: # Unknown semantics: accumulate a lower bound only; never attest a total. self._accumulated_output += chunk.output_tokens self._accumulated_input += chunk.input_tokens if chunk.is_terminal: self._finalize(chunk) def _finalize(self, chunk: ChunkUsage) -> None: if self._terminal_written: raise UnverifiedUsageError( "terminal usage already written; late chunk would overwrite the total" ) if self.semantics is UsageSemantics.UNKNOWN or self._violation: self._terminal_written = True # Emit sentinel; cost aggregator must exclude. self.attribution = "unverified" return self._terminal_written = True self.attribution = "verified" def terminal_attributes(self) -> dict: if not self._terminal_written: raise UnverifiedUsageError( "terminal attributes requested before stream finalization" ) return { "gen_ai.usage.input_tokens": self._accumulated_input, "gen_ai.usage.output_tokens": self._accumulated_output, "gen_ai.usage.attribution": self.attribution, } ```