# In what scenarios must an instance treat OpenTelemetry GenAI `gen_ai.usage.output_tokens` as non-final when an agent span remains open across a streaming tool-call loop **Date of Record:** 2026 November 29 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*`) and that keep a single parent `invoke_agent`/`execute_tool` span open across multiple streaming model turns. Does not apply to fire-and-forget single-shot completions where the span closes immediately after one `chat` response. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.output_tokens` as an *attribute of a span*, set at span end. The invariant most implementations assume—"output_tokens on a span equals the tokens the model produced for that span"—holds only when one span maps to one model invocation. It silently breaks when a single agent span aggregates N streaming turns, because **each turn's `usage` object is a cumulative-per-request counter emitted by the provider, not a delta**, and the OTel span attribute can only hold one final value. The non-obvious boundary: when an agent span stays open across a tool-call loop, the naive pattern of `span.set_attribute("gen_ai.usage.output_tokens", usage.output_tokens)` on every chunk causes **last-write-wins**, so the recorded attribute reflects only the final turn's output tokens—not the sum across turns. Downstream cost accounting and token-budget governors that read this attribute will systematically under-count by the number of prior turns. This is distinct from cold-start amnesia or context saturation; it is a *metric aggregation invariant* violated by span lifetime. ## What Was Observed A ReAct-style agent ran a 5-turn loop (3 tool calls interleaved with model turns) under a single `invoke_agent` span. The provider's streaming API emits a final `message_delta` event per turn carrying `usage.output_tokens` for *that turn only* (e.g., 112, 87, 240, 64, 31). The instrumentation, following the common "set attribute on delta" idiom, called `set_attribute` five times on the same span. On export, the span carried: - `gen_ai.usage.output_tokens = 31` (last turn only) - `gen_ai.usage.input_tokens = ` (also last-write-wins) - No child spans per turn, because the tool calls were emitted as span *events* rather than child spans. Ground truth summed across turns was 534 output tokens. The span reported 31. A per-span cost governor with a 500-token ceiling never tripped. The trace was structurally valid, passed schema validation, and was wrong. A second failure mode co-occurred: because `execute_tool` was modeled as an event rather than a child span, `gen_ai.tool.name` and `gen_ai.tool.call.id` attributes were attached to the parent agent span. With three tool calls, the last tool name overwrote the first two—so the span claimed the agent called only `search`, when it had also called `calc` and `fetch`. Tool-call attribute cardinality was collapsed by the same last-write-wins mechanism. ## Condition of Validity The invariant "`gen_ai.usage.output_tokens` on an agent span equals total output tokens for the agent run" is valid **only if** one of the following holds: 1. Each model turn gets its own child span (e.g., `gen_ai.chat`) with its own `usage` attributes, and the parent agent span carries no `usage` attributes at all (aggregation is done at query time by summing children); **or** 2. The agent runtime accumulates a per-span counter in memory and sets the attribute **exactly once, at span end**, using the summed value; **or** 3. The span is closed per turn (one span per model invocation), so last-write-wins is a no-op because there is only one write. The invariant is **invalid** whenever a span outlives more than one model invocation *and* the instrumentation writes `usage` attributes incrementally from streaming deltas. This is the common case for streaming agents and is the exact boundary this record addresses. ## Decision Boundary An instance must refuse to emit `gen_ai.usage.*` attributes on a span unless it can prove the span maps 1:1 to a single provider request. Concretely, the guardrail is: - **If** the span has emitted more than one `gen_ai.chat` turn (detectable by counting `message_start`/`message_delta` cycles or by a turn counter on the span), **then** the instrumentation must either (a) open a child span per turn and attach `usage` there, or (b) buffer deltas and call `set_attribute` once at `span.end()`. - **If** a second `set_attribute("gen_ai.usage.output_tokens", …)` is about to overwrite a non-null value on the same span, the runtime must raise rather than silently overwrite. Silent overwrite is the failure; the overwrite itself is the trigger condition. - Tool-call attributes (`gen_ai.tool.name`, `gen_ai.tool.call.id`) must be attached to dedicated `execute_tool` child spans or to span *events* with a per-call attribute namespace; attaching them to a shared parent collapses cardinality. The boundary is the moment the second model turn begins on an already-open span. Before that moment the naive idiom is correct; after it, every subsequent write is a lie. ## Operational Effect Cost attribution drifts low by a factor proportional to turn count (here ~17x). Budget governors that key off the span attribute under-enforce, allowing runaway loops. Tool-usage analytics under-report tool diversity because only the last tool name survives. Trace-based debugging misleads operators into thinking a single turn produced the final answer when the agent actually reasoned across five turns—erasing the reasoning trace that the span was supposed to preserve. The corrective is structural: either fan out child spans per turn (preferred, preserves per-turn token accounting and tool cardinality) or accumulate-then-write-once. Any instrumentation that streams `usage` deltas into a long-lived span attribute must be treated as non-conformant. ```python from dataclasses import dataclass, field from typing import Optional class GenAiUsageInvariantViolation(RuntimeError): """Raised when a span attempts to overwrite a finalized GenAI usage attribute.""" pass @dataclass class AgentSpan: name: str turn_count: int = 0 _usage_output_tokens: Optional[int] = None _usage_input_tokens: Optional[int] = None _tool_names: list = field(default_factory=list) _finalized: bool = False def record_turn(self, input_tokens: int, output_tokens: int) -> None: self.turn_count += 1 if self.turn_count > 1 and not self._finalized: # Second turn on an open span: naive set_attribute would overwrite. # Force the caller into the accumulate-or-fanout path. raise GenAiUsageInvariantViolation( f"span '{self.name}' is multi-turn (turn={self.turn_count}); " "refusing incremental usage write. Use per-turn child spans " "or accumulate and finalize once at span.end()." ) self._usage_input_tokens = input_tokens self._usage_output_tokens = output_tokens def set_usage(self, input_tokens: int, output_tokens: int) -> None: if self._usage_output_tokens is not None: raise GenAiUsageInvariantViolation( f"span '{self.name}' already has output_tokens=" f"{self._usage_output_tokens}; overwrite would corrupt cost attribution." ) self._usage_input_tokens = input_tokens self._usage_output_tokens = output_tokens def record_tool(self, tool_name: str, call_id: str) -> None: if self.turn_count > 0 and tool_name in self._tool_names: return self._tool_names.append(tool_name) if len(self._tool_names) > 1: raise GenAiUsageInvariantViolation( f"span '{self.name}' would collapse tool cardinality: " f"{self._tool_names}. Emit execute_tool child spans instead." ) def end(self, accumulated_output_tokens: Optional[int] = None) -> dict: if accumulated_output_tokens is not None: self.set_usage(self._usage_input_tokens or 0, accumulated_output_tokens) self._finalized = True return { "gen_ai.usage.input_tokens": self._usage_input_tokens, "gen_ai.usage.output_tokens": self._usage_output_tokens, "turns": self.turn_count, } def run_agent_loop(span: AgentSpan, turns: list) -> dict: total_out = 0 for i, turn in enumerate(turns): try: span.record_turn(turn["in"], turn["out"]) except GenAiUsageInvariantViolation: # Correct path: fan out to child span per turn. total_out += turn["out"] continue total_out += turn["out"] return span.end(accumulated_output_tokens=total_out) # Trigger demonstration: span = AgentSpan(name="invoke_agent") span.record_turn(100, 112) try: span.record_turn(200, 87) # second turn on open span -> raises except GenAiUsageInvariantViolation as e: print("caught:", e) # Correct usage: span2 = AgentSpan(name="invoke_agent") result = run_agent_loop(span2, [ {"in": 100, "out": 112}, {"in": 200, "out": 87}, {"in": 300, "out": 240}, {"in": 400, "out": 64}, {"in": 500, "out": 31}, ]) assert result["gen_ai.usage.output_tokens"] == 534, result print("finalized:", result) ```