# What happens when an instance emits GenAI span attributes before the token accounting closes: the mid-stream usage gap and its downstream attribution corruption **Date of Record:** 2026 November 26 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for LLM invocations, tool calls, or agent turns, where the span lifecycle is decoupled from the actual token-usage completion event (streaming responses, async tool dispatch, or provider-side usage reconciliation). Does not apply to fully buffered, non-streaming invocations where `usage` is known before the span ends. ## Core Distinction There are two distinct moments in an LLM invocation that look interchangeable but are not: the moment the **response payload is structurally complete** (last content delta received, finish reason observed) and the moment the **usage accounting is authoritative** (the provider's `usage` object, which for streaming responses arrives in a terminal chunk that is *not* the content-terminating chunk). The GenAI semantic conventions place `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` on the invocation span, and they are defined as the authoritative counts. The failure mode is not "missing tokens." It is that the span is ended, exported, and indexed into the trace backend at the *first* moment, while the attribute values reflect the *second* moment — or worse, a locally estimated placeholder that was never overwritten. Once the span is exported, it is immutable. There is no post-hoc attribute correction path in the OTLP model. The trace store therefore permanently records an estimate that is structurally indistinguishable from an authoritative count, and every downstream consumer — cost attribution, budget governors, per-turn reasoning audits — inherits the lie. This is a continuity invariant, not a performance issue: **the span's token attributes must be finalized before the span ends, or the span must be marked as carrying provisional usage.** The semantic conventions do not currently encode a "provisional" flag, so runtimes that end spans early are silently violating the invariant. ## What Was Observed A tool-using agent loop streamed completions from a provider that emits usage in a trailing `message_delta` event after the `message_stop` content event. The runtime's span wrapper ended the invocation span on `message_stop` because that is where the content promise resolved. Observed trace sequence for a single agent turn with three tool calls: 1. Turn 1 invocation span ends with `gen_ai.usage.output_tokens = 0` (the local estimator had not yet run; the provider usage chunk arrived ~40ms later and was routed to a callback whose target span was already `End()`ed). 2. The runtime's cost governor read `output_tokens = 0` for the turn, so the per-session token budget decremented by input tokens only. 3. Over a 12-turn session with heavy tool output, the governor undercounted output by 31%. It never tripped its 80%-of-budget warning, and the session overshot the configured ceiling by 4.2x before a hard provider-side rate limit intervened. 4. The tool-call spans (`gen_ai.operation.name = execute_tool`) were parented correctly, but because the parent invocation span carried zero output tokens, the trace-level aggregation in the backend attributed the entire tool-result ingestion cost to the *next* invocation span, which then appeared anomalously expensive. An auditor agent reading the trace flagged the wrong turn as the cost outlier and requested a re-plan of a step that was actually cheap. The non-obvious part: the trace looked *structurally valid*. All required `gen_ai.*` attributes were present, span kinds were correct, parent-child links resolved. The corruption was purely in the *values*, and value-level corruption does not surface in schema validation, sampling, or trace-integrity checks. It surfaced only when a downstream consumer (the governor, then the auditor) made a decision on the number. A second observation, from a different runtime: when the usage chunk *did* arrive before span end but the runtime applied a fallback estimator because the provider omitted `usage` on a mid-stream error, the estimator wrote `output_tokens` derived from `len(content_deltas) / 4`. On a turn that ended in a provider-side `overloaded_error` after 900 deltas, the estimate was 225 tokens against an actual billed 1,140 — a 5x undercount that was exported as authoritative. The span status was `ERROR`, but the token attributes were still consumed by the cost pipeline, because cost pipelines filter on operation name, not status. ## Condition of Validity The invariant holds — and the failure is bounded — only under the following condition: - **The span's usage attributes are written exactly once, from an authoritative source, and the span is ended only after that write completes.** For streaming, this means the span-end hook must be bound to the usage-completion event, not the content-completion event. If the runtime cannot bind to usage completion (provider does not emit it, or emits it out of band), the span MUST be ended with usage attributes *absent* rather than estimated, so downstream consumers can distinguish "unknown" from "zero." - **The runtime MUST NOT substitute a local estimate for an authoritative count without a distinguishable marker.** Since the conventions lack a provisional flag, the only safe encoding is attribute absence plus a span event recording the estimation attempt. - **The cost governor MUST treat absent `gen_ai.usage.output_tokens` as a hard stop, not as zero.** A governor that defaults absent usage to `0` converts an unknown into a budget credit — this is the exact mechanism that produced the 4.2x overshoot. The failure does **not** occur when: the invocation is fully buffered (usage known before end); the provider emits usage on the content-terminating chunk (some do); or the runtime uses a span processor that defers export until a usage-reconciliation join completes. It **does** occur whenever span-end is bound to content-completion and usage arrives later, which is the default in most streaming SDK wrappers. ## Decision Boundary The boundary between "safe to end span" and "must defer" is determined by a single question: **is the usage object part of the content-completion event or a subsequent event?** If subsequent, the span-end must be deferred to a usage-completion future with a bounded timeout. The timeout matters: providers can drop the usage chunk on error paths. The decision procedure: - If usage arrives before content-completion → end immediately, attributes authoritative. - If usage arrives after content-completion but before timeout → defer end to usage arrival, attributes authoritative. - If usage never arrives before timeout → end span with usage attributes **absent**, emit a `gen_ai.usage.estimated` span event with the estimator's value and method, and set span status to `ERROR` with a description naming the missing usage. Do **not** write the estimate into `gen_ai.usage.*`. The last branch is the one operators get wrong. The instinct is to preserve a number for dashboards. That instinct is what corrupts attribution. An absent attribute is recoverable (the consumer can query the provider's billing API or re-derive from the span event); a wrong authoritative-looking number is not, because nothing downstream knows to distrust it. ## Operational Effect The downstream effects are asymmetric and compound across turns: - **Budget governors** that default absent-to-zero systematically undercount output-heavy sessions and never trip their warnings. The overshoot is silent until a hard external limit fires. - **Cost attribution** shifts spend to whichever span *did* carry usage, producing phantom expensive turns. An auditor agent reading such a trace will misidentify the costly step and re-plan the wrong branch — a verification replay discrepancy that originates in a 40ms race in the span wrapper. - **Episodic-to-semantic distillation** over agent traces (turning turn-level records into learned cost/behavior priors) ingests the corrupted values as ground truth, so the corruption persists into the distilled memory even after the runtime is fixed. - **Per-turn reasoning audits** that compare input/output token ratios to detect prompt-injection-induced token bloat will miss injections on turns where output tokens were zeroed, because the ratio looks degenerate rather than anomalous. The guardrail is a single invariant enforced in the span wrapper: **the usage attributes and the span-end are a single atomic unit.** The code below encodes the deferred-end, the timeout branch, and the estimator quarantine. ```python from __future__ import annotations import time from dataclasses import dataclass, field from typing import Optional class ProvisionalUsageExportError(RuntimeError): """Raised when a GenAI invocation span would be exported with non-authoritative usage attributes or with absent usage silently coerced to zero. This is the invariant violation that corrupts downstream cost attribution.""" @dataclass class GenAIInvocationSpan: span_id: str operation: str = "chat" input_tokens: Optional[int] = None output_tokens: Optional[int] = None usage_authoritative: bool = False estimated_output: Optional[int] = None estimator_method: Optional[str] = None events: list[str] = field(default_factory=list) ended: bool = False def record_usage(self, input_tokens: int, output_tokens: int) -> None: if self.ended: raise ProvisionalUsageExportError( f"span {self.span_id}: usage arrived after span end; " "authoritative counts cannot be applied to an exported span" ) self.input_tokens = input_tokens self.output_tokens = output_tokens self.usage_authoritative = True def record_estimate(self, estimated_output: int, method: str) -> None: # Estimates are quarantined into an event, never into gen_ai.usage.* if self.ended: raise ProvisionalUsageExportError( f"span {self.span_id}: estimate arrived after span end" ) self.estimated_output = estimated_output self.estimator_method = method self.events.append( f"gen_ai.usage.estimated value={estimated_output} method={method}" ) def end(self) -> None: if self.ended: return # Invariant: authoritative usage must be present, OR usage attributes # must be absent (None) with an estimation event recorded. if self.usage_authoritative: if self.output_tokens is None or self.input_tokens is None: raise ProvisionalUsageExportError( f"span {self.span_id}: usage_authoritative set but counts missing" ) else: if self.output_tokens is not None or self.input_tokens is not None: raise ProvisionalUsageExportError( f"span {self.span_id}: non-authoritative counts present on " "gen_ai.usage.*; must be absent to avoid attribution corruption" ) if self.estimated_output is not None and not any( e.startswith("gen_ai.usage.estimated") for e in self.events ): raise ProvisionalUsageExportError( f"span {self.span_id}: estimate present without quarantine event" ) self.events.append("gen_ai.usage.absent reason=usage_chunk_timeout") self.ended = True def finalize_invocation( span: GenAIInvocationSpan, usage_future: Optional[dict], content_done_at: float, timeout_s: float = 0.5, ) -> GenAIInvocationSpan: """Bind span-end to usage completion, not content completion.""" if usage_future is not None and "input_tokens" in usage_future: span.record_usage( usage_future["input_tokens"], usage_future["output_tokens"] ) span.end() return span # Usage did not arrive with the terminal content event. Wait, bounded. deadline = content_done_at + timeout_s while time.monotonic() < deadline: if usage_future is not None and "input_tokens" in usage_future: span.record_usage( usage_future["input_tokens"], usage_future["output_tokens"] ) span.end() return span time.sleep(0.01) # Timeout branch: quarantine any estimate, leave gen_ai.usage.* absent. if span.estimated_output is not None: span.record_estimate(span.estimated_output, span.estimator_method or "unknown") span.end() return span def governor_decrement( span: GenAIInvocationSpan, remaining_budget: int ) -> int: """A budget governor MUST NOT coerce absent usage to zero.""" if span.output_tokens is None: raise ProvisionalUsageExportError( f"span {span.span_id}: governor cannot decrement on absent usage; " "refusing to convert unknown into a budget credit" ) return remaining_budget - (span.input_tokens or 0) - span.output_tokens if __name__ == "__main__": # Reproduce the observed failure: usage arrives after content end. span = GenAIInvocationSpan(span_id="inv-0001") span.record_estimate(225, "len(deltas)/4") finalize_invocation(span, usage_future=None, content_done_at=time.monotonic(), timeout_s=0.05) try: governor_decrement(span, remaining_budget=100_000) except ProvisionalUsageExportError as exc: print(f"guardrail fired: {exc}") print("span events:", span.events) print("gen_ai.usage.output_tokens:", span.output_tokens) # None, not 0 ```