Where must an instance bound the GenAI span’s `gen_ai.usage.*` token counters when a streaming tool-call loop emits partial deltas before the model’s finish reason is known?

**Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) around streaming chat completions that interleave tool calls, and that finalizes token usage from streamed deltas rather than from a single terminal response object. Does not apply to non-streaming request/response completions where a single response envelope carries authoritative `usage`.

Core Distinction

The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *settled, monotonic, terminal* attributes of a span. The streaming transport, however, delivers usage as *incremental and often absent until the final chunk*. These two contracts are structurally incompatible at the boundary where a tool-call loop re-enters the model. The distinction that matters operationally is between **deltas observed on the wire** and **usage the span is allowed to assert as fact**. An agent that conflates the two will double-count, under-count, or finalize a span with a mid-stream partial that later contradicts the terminal chunk — and because span attributes are immutable after `End()`, the contradiction is unrecoverable in the trace.

What Was Observed

A planner agent runs a ReAct loop: `chat.completions` (stream) → parse `tool_calls` → invoke tool → re-enter model with tool result. The runtime opens one span per model invocation, tagged `gen_ai.operation.name=chat`, and a child span per tool call tagged `gen_ai.operation.name=execute_tool`. Usage is accumulated as follows: each stream chunk carrying a `usage` field is added to a running counter; on `finish_reason` the span is ended and the counter is written.

The failure trace:

  1. Provider streams `delta` chunks with `finish_reason=null` and **no** `usage` field (the common case — usage is withheld until the terminal chunk to avoid leaking billing mid-stream).
  2. The model emits a `tool_calls` delta. The runtime, eager to bound latency, ends the *model* span at the tool-call boundary and starts the *tool* span, writing `gen_ai.usage.output_tokens` = the count it has so far, which is **0** because no chunk ever carried usage.
  3. The tool executes. The loop re-enters the model for the next turn. A *new* span is opened.
  4. On the **final** turn, the terminal chunk arrives with `usage: {prompt_tokens: 4210, completion_tokens: 318}`. That usage reflects the *entire conversation*, including all prior tool-call turns — because the provider bills the full re-sent context each turn.
  5. The final span records 4210/318. The prior N spans record 0/0.

Result in the trace: total `gen_ai.usage.*` across spans ≈ the last turn only. The actual cost of the loop is `sum over turns of (full context each turn)`, which is superlinear in turns. Dashboards built on the convention report ~1/N of true spend, and the *direction* of the error is worst precisely for long tool loops — the agents that cost the most look the cheapest. A secondary failure: when the provider *does* emit per-chunk usage (some gateways do), the runtime adds each chunk's cumulative `usage` as if it were a delta, over-counting by a triangular factor.

Condition of Validity

The invariant that makes a span’s usage attributes trustworthy is:

> A span’s `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` are valid **iff** they are written exactly once, from a single authoritative terminal observation, and are never mutated after `End()`. Any accumulation across chunks must be proven to be *additive deltas*, not *cumulative snapshots*.

This holds only when one of two preconditions is met:

The failure above occurs because the runtime assumed (B) without proof, *and* because it closed the span at the tool-call boundary — violating the "write once at terminal" clause of (A). The tool-call boundary is not a completion boundary. `finish_reason=tool_calls` means *the model paused to delegate*, not *the turn’s accounting is complete*. The accounting completes only when `finish_reason` is one of the terminal set (`stop`, `length`, `content_filter`) **and** the usage-bearing chunk has arrived.

Decision Boundary

The runtime must decide, per span, between two mutually exclusive finalization rules, and must *refuse* to finalize otherwise:

The guardrail is a finalization gate: a function that takes the accumulated stream state and the finish reason and either returns a settled usage tuple or raises. It must never return `(0, 0)` as a default for "no usage seen."

Operational Effect

With the gate in place: long tool loops produce spans where early turns carry *no* usage attribute and the terminal turn carries full-context usage; a parent span or metric sums them correctly, and cost dashboards track true superlinear spend. The trace becomes honest about *where* accounting is unavailable instead of silently zeroing it. The cost is that per-span usage is no longer uniformly present — consumers must treat absence as "unknown," not "zero," which is the correct reading of the convention anyway. The failure mode this prevents — a loop whose reported cost is a fraction of actual and whose error grows with loop length — is exactly the class of silent divergence that makes agent cost attribution untrustworthy at scale.

from dataclasses import dataclass
from typing import Optional


class GenAIUsageFinalizationError(RuntimeError):
    """Raised when a GenAI span cannot settle gen_ai.usage.* truthfully."""


@dataclass
class StreamState:
    finish_reason: Optional[str] = None
    usage_chunk_seen: bool = False
    prompt_tokens: Optional[int] = None
    completion_tokens: Optional[int] = None
    saw_delta_usage: bool = False  # provider emitted per-chunk usage


TERMINAL_REASONS = {"stop", "length", "content_filter"}
TOOL_BOUNDARY_REASONS = {"tool_calls", "function_call"}


def finalize_genai_usage(state: StreamState, *, allow_unknown: bool) -> Optional[tuple[int, int]]:
    """
    Returns (input_tokens, output_tokens) to write ONCE onto the span, or None
    if usage is legitimately unknown (attribute must be omitted, not zeroed).

    Raises GenAIUsageFinalizationError when the state cannot be settled
    truthfully and allow_unknown is False (strict mode).
    """
    if state.finish_reason is None:
        raise GenAIUsageFinalizationError(
            "stream ended without finish_reason; usage cannot be settled"
        )

    if state.finish_reason in TOOL_BOUNDARY_REASONS:
        # Tool-call boundary is NOT a completion boundary.
        if state.usage_chunk_seen and state.prompt_tokens is not None:
            return (state.prompt_tokens, state.completion_tokens or 0)
        if allow_unknown:
            return None  # omit attribute; never write (0, 0)
        raise GenAIUsageFinalizationError(
            "tool_calls finish with no usage chunk; refusing to write 0/0"
        )

    if state.finish_reason in TERMINAL_REASONS:
        if state.usage_chunk_seen and state.prompt_tokens is not None:
            return (state.prompt_tokens, state.completion_tokens or 0)
        if allow_unknown:
            return None
        raise GenAIUsageFinalizationError(
            "terminal finish but usage chunk never arrived"
        )

    raise GenAIUsageFinalizationError(
        f"unhandled finish_reason={state.finish_reason!r}"
    )