# Under what conditions must an instance treat a GenAI token-accounting span as unclosed, and how does the `gen_ai.usage.*` attribute contract break at the tool-call boundary when streaming deltas are aggregated post-hoc? **Date of Record:** 2026 December 2 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) for LLM invocations and tool calls, where usage attributes are populated from streaming provider responses and tool-call events are nested inside the parent invocation span. Does not cover non-streaming batch inference, nor providers that emit final usage in a single terminal chunk with no delta aggregation. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as **terminal, immutable attributes fixed at span end**. They are not counters, not gauges, and not reconcilable mid-span. The convention's implicit invariant is: *the span that owns a token count owns a complete, single billable unit of work*. This invariant silently assumes a one-to-one mapping between an LLM invocation span and a single provider request. Agents violate that assumption constantly. A single logical "agent turn" fans out into: a streaming completion whose deltas arrive across many SSE frames, an interleaved tool-call block embedded in the same stream, and a *second* provider round-trip after the tool result is fed back. The runtime must decide which span owns which tokens — and the semantic conventions give no answer. The boundary failure lives precisely here: **the tool-call event is a child of the invocation span, but the tokens that produced the tool call are counted on the parent, while the tokens that consumed the tool result are counted on a sibling span that the runtime often forgets to open.** ## What Was Observed Trace from a production agent run, simplified: - Span `A` (`gen_ai.operation.name=chat`, `gen_ai.request.model=...`) opened at turn start. - Streaming deltas arrive. Provider sends `message_start` with `input_tokens=1840`, then `content_block_delta` frames, then a `content_block_start` of type `tool_use` carrying `id=toolu_01...`, then `message_delta` with `output_tokens=312`, then `message_stop`. - The runtime records `gen_ai.usage.input_tokens=1840` and `gen_ai.usage.output_tokens=312` on span `A`, emits a `gen_ai.tool.call` event with `gen_ai.tool.name` and `gen_ai.tool.call.id`, then ends span `A`. - Tool executes. Result is fed back. The runtime issues a **second** completion. Because the second completion reuses the same logical "agent step," the runtime reuses span `A`'s context via `contextvars` — but span `A` has already ended. The OTel SDK silently drops attributes set on an ended span. The second call's `input_tokens=2410` and `output_tokens=88` are **lost from the trace entirely**, though they were billed by the provider. - Downstream, the token-accounting aggregator sums `gen_ai.usage.*` across spans and reconciles against provider invoices. It finds a ~28% shortfall that is stable across runs and correlates with tool-call frequency. The failure is not an exception. No span is marked `status=ERROR`. The trace is structurally valid and semantically wrong. ## Condition of Validity The `gen_ai.usage.*` attributes are only valid as terminal attributes **if and only if** the following holds at the moment the span is ended: 1. The provider has emitted a terminal usage frame (or the runtime has a non-streaming response body) for *exactly this* provider request. 2. No further provider request will be attributed to this span's logical step. 3. The tool-call event, if present, is a *sibling* of the follow-up invocation span, not a child of a span that will be reused. Condition (2) is the one agents break. The convention assumes an invocation span is a leaf unit of billing. An agent turn is a *tree* of provider calls linked by tool results. The correct topology is: ``` span A (chat, usage=1840/312) ── event: tool.call ──▶ span B (chat, usage=2410/88) ``` not: ``` span A (chat, usage=1840/312, ends) ── event: tool.call ──▶ [attributes dropped on ended span A] ``` The invariant to enforce: **a span carrying `gen_ai.usage.*` MUST NOT be reactivated, and any provider request following a tool-call event MUST open a new invocation span with a fresh `gen_ai.usage.*` attribute set.** The runtime must treat span end as a hard barrier, not a soft checkpoint. ## Decision Boundary The boundary condition that triggers the failure is a specific ordering of three events: - `EndSpan(A)` has been called, **and** - a tool-call event was emitted on `A`, **and** - the runtime's continuation logic re-enters the same OTel `Context` (via `contextvars`, async-local storage, or a framework's "current span" pointer) rather than opening a new span. When all three hold, `set_attribute("gen_ai.usage.input_tokens", ...)` on the reused context is a **no-op against a non-recording span**. The OTel spec permits this silently; `Span.is_recording()` returns `False` and the SDK drops the write. There is no error to catch. The only signal is the accounting shortfall downstream. The decision boundary is therefore not "did the call succeed" but **"is the span that will receive the usage attribute still recording at the moment the terminal usage frame arrives?"** If the answer is no, the runtime must either (a) have opened a new span before issuing the follow-up request, or (b) buffer the usage and emit it on a span it *knows* is live. Reusing an ended span is never correct. A secondary boundary: when streaming, `message_delta` with `output_tokens` may arrive *after* `message_stop` in some provider SDKs due to buffering. If the runtime ends the span on `message_stop`, the terminal usage frame lands on a dead span. The invariant must be **end the span on the usage frame, not on the stop frame**, or buffer usage explicitly before ending. ## Operational Effect Consequences of violating the invariant: - **Silent undercounting.** Token reconciliation against provider billing drifts by a factor proportional to tool-call density. In the observed run, ~28%; in agents with tight tool loops, this can exceed 50% because the follow-up call after a tool result is often the *larger* prompt (tool output is appended). - **Cost attribution corruption.** Per-step cost dashboards attribute all tokens to the first invocation, making tool-heavy steps look cheap and final-answer steps look expensive, inverting the true cost profile. - **Latency/usage decoupling.** `gen_ai.usage.output_tokens / span_duration` becomes meaningless because the span's duration excludes the second provider round-trip, which was the actual latency contributor. - **Replay divergence.** A trace replay that reconstructs agent state from spans will reconstruct the wrong token budget, causing the replay to under-allocate context for the final step and diverge from the live run. Guardrails required: 1. **Span-end is a hard barrier.** Any code path that issues a provider request after a `gen_ai.tool.call` event must open a new `gen_ai.operation.name=chat` span. Assert `span.is_recording()` before every `set_attribute` on `gen_ai.usage.*`. 2. **Usage-frame-driven closure.** End the invocation span when the terminal usage frame is processed, not when the stream closes. 3. **Reconciliation assertion.** After each agent turn, assert `sum(gen_ai.usage.input_tokens over spans in turn) == provider_reported_input_tokens`. Fail the turn (and mark the trace) on mismatch. 4. **Tool-call events carry no usage.** `gen_ai.tool.call` events must not carry `gen_ai.usage.*` attributes; usage belongs to invocation spans only, and the convention's event schema does not define them there. ```python from dataclasses import dataclass, field from typing import Optional class GenAIUsageAccountingError(RuntimeError): """Raised when GenAI token-usage attributes are written to a span that cannot accept them, or when per-turn usage fails reconciliation against the provider's reported totals.""" @dataclass class InvocationSpan: name: str recording: bool = True attributes: dict = field(default_factory=dict) ended: bool = False def set_attribute(self, key: str, value) -> None: # Mirrors OTel: writes to a non-recording span are silently dropped. if not self.recording: return self.attributes[key] = value def end(self) -> None: self.ended = True self.recording = False @dataclass class AgentTurn: spans: list = field(default_factory=list) provider_input_tokens: int = 0 provider_output_tokens: int = 0 def record_usage(span: InvocationSpan, input_tokens: int, output_tokens: int) -> None: if not span.recording: raise GenAIUsageAccountingError( f"Cannot record gen_ai.usage.* on span {span.name!r}: " f"span is not recording (ended={span.ended}). " f"Open a new invocation span for the post-tool-call request." ) span.set_attribute("gen_ai.usage.input_tokens", input_tokens) span.set_attribute("gen_ai.usage.output_tokens", output_tokens) span.end() def assert_turn_reconciles(turn: AgentTurn) -> None: summed_in = sum(s.attributes.get("gen_ai.usage.input_tokens", 0) for s in turn.spans) summed_out = sum(s.attributes.get("gen_ai.usage.output_tokens", 0) for s in turn.spans) if summed_in != turn.provider_input_tokens or summed_out != turn.provider_output_tokens: raise GenAIUsageAccountingError( f"Turn usage reconciliation failed: spans report " f"in={summed_in} out={summed_out}, provider reports " f"in={turn.provider_input_tokens} out={turn.provider_output_tokens}. " f"Likely cause: usage written to an ended span after a tool-call event." ) # Failure trace: reuse of ended span after tool call. turn = AgentTurn(provider_input_tokens=1840 + 2410, provider_output_tokens=312 + 88) span_a = InvocationSpan("chat.turn.0") turn.spans.append(span_a) record_usage(span_a, 1840, 312) # span_a ends here # ... tool call emitted on span_a ... try: record_usage(span_a, 2410, 88) # BUG: reusing ended span except GenAIUsageAccountingError as e: # Correct recovery: open a new span instead. span_b = InvocationSpan("chat.turn.0.tool_result") turn.spans.append(span_b) record_usage(span_b, 2410, 88) assert_turn_reconciles(turn) # passes only because we opened span_b ```