Where must an instance reconcile OpenTelemetry GenAI token accounting when streaming tool-call spans and final usage records disagree

**Date of Record:** 2026 December 2 **Scope:** Applies to agent runtimes that emit `gen_ai.*` spans per model turn and per tool call, where streaming deltas are counted as they arrive and a terminal `usage` object is also received. Does not apply to non-streaming, single-shot inference calls that receive exactly one usage record.

Core Distinction

The GenAI semantic conventions treat token usage as a property of a *model turn*: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are set on the span that represents the inference request. The conventions do not specify how those attributes relate to *streamed* output, and they say nothing about tool-call spans, which carry `gen_ai.tool.name`, `gen_ai.tool.call.id`, and arguments but no token attributes at all.

This creates a silent fork. A streaming agent typically increments an internal counter per chunk (or per `tool_call` delta) to bound cost and context, then receives a final `usage` object from the provider at `finish_reason`. The two numbers are computed by different mechanisms — the client's incremental tally and the server's authoritative count — and they are allowed to differ. The boundary condition is not "which is right." It is: *at what point does the span, as emitted, become the record of truth, and what happens to the delta between the two counts at that moment?*

The non-obvious part: tool-call deltas are frequently *not* counted by the client at all, because the arguments stream as `tool_calls[].function.arguments` fragments that the client buffers rather than tokenizes. The server counts them. So the client's running total is systematically low on any turn that emits a tool call, and the gap is invisible until the final usage record arrives — by which time the span may already be closed.

What Was Observed

A single agent turn that streamed one tool call and then completed produced the following sequence:

  1. Client opens span `gen_ai.chat` with `gen_ai.operation.name=chat`.
  2. Stream begins. Client increments `output_tokens_local` on each `content` delta. Tool-call argument fragments arrive as `tool_calls` deltas and are appended to a buffer, **not** counted.
  3. `finish_reason=tool_calls`. Client emits a child span `gen_ai.tool` for the call, sets `gen_ai.tool.name` and `gen_ai.tool.call.id`, and ends it.
  4. Provider emits terminal `usage` with `completion_tokens=412`. Client's `output_tokens_local=287`. The 125-token gap is the serialized tool arguments plus the assistant's preamble.
  5. Client sets `gen_ai.usage.output_tokens` from the terminal usage (412) and ends the parent span.

The span is *correct*. The failure is downstream: any consumer that correlated the tool span to the model span and summed token attributes across the turn — a cost aggregator, a context-budget enforcer, a rate limiter keyed on `gen_ai.usage.output_tokens` — saw 412 on the parent and 0 on the child, and either double-counted nothing (fine) or, in the more damaging case, *re-derived* the per-tool cost by pro-rating the parent across children using a heuristic that assumed tool arguments were not counted. The re-derivation was wrong by exactly the argument-token gap, and it was wrong *silently*, because both spans validated against the schema.

A second, sharper observation: when the agent *aborted* the stream mid-tool-call (a timeout on the tool executor), the client closed the parent span with `gen_ai.usage.output_tokens=287` — its local tally — because no terminal usage ever arrived. The same span name, the same attributes, a different semantics for the same field. Consumers could not distinguish "authoritative count" from "lower-bound estimate" from the attribute alone.

Condition of Validity

The invariant holds only under these conditions:

When any condition fails — aborted stream, provider that omits usage, client that closes the span on `finish_reason` before the usage chunk arrives — the `gen_ai.usage.*` attributes become an *estimate* with no marker distinguishing them from an authoritative count.

Decision Boundary

The boundary is the moment the span ends relative to the moment the terminal usage record arrives. There are exactly two safe orderings:

The unsafe ordering — close the span, then set `gen_ai.usage.output_tokens` from the late usage chunk — produces a span whose attributes mutate after export in some SDKs and are dropped in others. The dropped case is the dangerous one: the span ships with the local estimate and no provenance, and the authoritative count is lost.

The decision rule: *if the stream can be aborted, you must emit provenance.* A span that can carry either an authoritative or an estimated count under the same attribute name is not a valid record.

Operational Effect

Without provenance, three concrete failures follow. First, cost attribution drifts low on every tool-using turn by the argument-token gap, and the drift is proportional to argument size — so agents that pass large payloads to tools are under-billed and, worse, under-*budgeted*, since a context-window enforcer reading `gen_ai.usage.output_tokens` will admit one more turn than it should. Second, aborted streams are indistinguishable from completed ones in the trace, so a post-hoc audit cannot tell a 287-token turn from a 412-token turn that was cut short. Third, replay-based verification — re-running the turn and comparing token counts — flags every tool-using turn as a discrepancy, because the replay's local tally and the original's authoritative count never matched to begin with.

The guardrail is a single invariant: **a `gen_ai.usage.*` attribute must never be written from two different sources under one name without a provenance marker, and the marker must be set at the same time as the value, before span end.** Everything else — reconcile-then-close, correction events, pro-rating heuristics — is downstream of honoring that.

from dataclasses import dataclass, field
from enum import Enum


class TokenAccountingError(RuntimeError):
    """Raised when a gen_ai.usage attribute would be written without provenance."""


class UsageSource(Enum):
    PROVIDER_REPORTED = "provider_reported"
    LOCAL_ESTIMATE = "local_estimate"


@dataclass
class GenAiChatSpan:
    name: str = "gen_ai.chat"
    attributes: dict = field(default_factory=dict)
    _closed: bool = False
    _usage_source: UsageSource | None = None

    def set_usage(self, input_tokens: int, output_tokens: int, source: UsageSource) -> None:
        if self._closed:
            # Writing usage after close loses the value in most exporters and,
            # worse, leaves the prior estimate in place with no marker.
            raise TokenAccountingError(
                f"span {self.name!r} already closed; cannot set usage from {source.value}"
            )
        if self._usage_source is not None and self._usage_source != source:
            raise TokenAccountingError(
                f"span {self.name!r} usage already set from {self._usage_source.value}, "
                f"refusing to overwrite from {source.value} without a correction event"
            )
        self.attributes["gen_ai.usage.input_tokens"] = input_tokens
        self.attributes["gen_ai.usage.output_tokens"] = output_tokens
        self.attributes["gen_ai.usage.source"] = source.value
        self._usage_source = source

    def close(self) -> None:
        if self._usage_source is None:
            # A closed span with no usage source is an unmarked estimate.
            raise TokenAccountingError(
                f"span {self.name!r} closed without a usage source marker"
            )
        self._closed = True


def finalize_streamed_turn(
    span: GenAiChatSpan,
    local_output_tokens: int,
    terminal_usage: dict | None,
    aborted: bool,
) -> GenAiChatSpan:
    if aborted or terminal_usage is None:
        # No authoritative count: record the estimate, but mark it as such.
        span.set_usage(
            input_tokens=terminal_usage["prompt_tokens"] if terminal_usage else 0,
            output_tokens=local_output_tokens,
            source=UsageSource.LOCAL_ESTIMATE,
        )
    else:
        # Reconcile-then-close: authoritative count wins, provenance recorded.
        span.set_usage(
            input_tokens=terminal_usage["prompt_tokens"],
            output_tokens=terminal_usage["completion_tokens"],
            source=UsageSource.PROVIDER_REPORTED,
        )
    span.close()
    return span