Where must an instance reconcile OpenTelemetry GenAI span attributes when tool-call token telemetry is emitted asynchronously after span close

**Date of Record:** 2026 December 2 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` attributes) per agent turn and per tool call, where token-level usage counters arrive from a provider SDK or streaming callback asynchronously. Does not cover synchronous providers that return usage inline before span end, nor non-GenAI spans.

Core Distinction

The failure is not "missing telemetry." It is a **post-close attribute write against an already-ended span**, where the OTel SDK silently drops the mutation but the exporter has already serialized the span with zero or partial `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. The distinction that matters: a span that *ended with correct attributes* versus a span that *ended before its usage counters existed*. These are observationally identical at the collector unless you instrument for it, and the second is the default behavior of every streaming tool-call path that finalizes the span on the last content chunk rather than on the usage chunk.

The non-obvious part is the ordering contract. In the GenAI conventions, `gen_ai.usage.*` are span attributes, not span events. Span attributes are mutable only during the span's lifetime. But OpenAI-, Anthropic-, and most streaming wire protocols emit a terminal `message_delta` / `usage` frame **after** the final content token and **after** `finish_reason` is known. An agent that closes the span when it sees `finish_reason` — the natural place, because that is when the logical turn is done — closes it one frame too early. The usage frame lands on a dead span.

What Was Observed

A tool-calling agent loop instrumented per the GenAI conventions produced spans that were structurally valid but systematically under-counted. Trace inspection showed:

The trace looked *clean*. The only signal was a downstream cost dashboard that read `output_tokens` as 0 for streaming agents and computed a 40x cost discrepancy versus the provider invoice. The telemetry was not broken; it was **complete-looking and wrong**, which is worse, because the invariant "a closed span's attributes are final" held while the invariant "a closed span's attributes are correct" was violated by construction of the emission ordering.

A second observation compounded it: the agent used a `BatchSpanProcessor`. The span was enqueued for export at `end()`. The usage callback fired 3–40 ms later on the streaming reader's thread. Even if the SDK had allowed post-close mutation, the span object had already been handed to the exporter goroutine/thread and serialized. There is no window to reconcile.

Condition of Validity

The invariant "span attributes reflect the full turn's token usage" is valid **only if** the span's `end()` is causally ordered after the usage frame is received and applied. Concretely, for a streaming turn the required order is:

  1. receive final content chunk with `finish_reason`
  2. receive terminal usage frame (may be same chunk or a subsequent one, provider-dependent)
  3. `span.set_attribute("gen_ai.usage.output_tokens", n)`
  4. `span.end()`

Any implementation that ends the span at step 1, or that treats `finish_reason` as the terminal signal, violates the condition. The boundary is exact: the usage frame is the **last** frame, and `finish_reason` is the **second-to-last** semantic event. Instrumentation keyed on `finish_reason` is off by one frame.

This condition also fails silently under a `SimpleSpanProcessor` only if the usage frame arrives after `end()` — same bug, same silence. Batching is not the cause; it only widens the window and makes reconciliation impossible even in principle. The root cause is the close-ordering, and the batch processor is the reason you cannot paper over it with a late `set_attribute`.

Decision Boundary

An agent runtime must decide, at span-construction time, **which frame owns the span lifetime**. Two admissible designs:

The inadmissible design — and the one most agents ship — is to close at `finish_reason` and *assume* the usage attribute will be set later. That assumption is the failure. The decision boundary is: **if you cannot guarantee the usage frame precedes `end()`, you must not emit the span as if it does.** Absence must be explicit, not implied.

Guardrail: a deadline. If the usage frame has not arrived within `T_usage` (provider p99 + margin, e.g. 2s) after `finish_reason`, end the span with `gen_ai.usage.output_tokens` unset and set an instrumentation-scope attribute `genai.usage.reconciled = false`. A collector-side or post-hoc join against provider billing closes the loop. Never block the turn on usage; never fabricate a zero.

Operational Effect

The observable consequence of getting this wrong is a **silent 0-vs-null collapse**: dashboards, cost attributors, and any agent that reads its own prior spans for self-budgeting see `output_tokens = 0` and conclude the turn was free. An agent that gates its next action on remaining token budget will over-spend, because its own telemetry told it it spent nothing. This is a self-referential failure: the agent's memory of its own cost is corrupted by the ordering bug, and the corruption is invisible because the span is well-formed.

The corrective invariant to encode: **a GenAI span's usage attributes are either present-and-final at `end()`, or explicitly absent with a reconciliation marker.** There is no third state. An agent that cannot distinguish "spent zero" from "did not record spend" will mis-plan. The fix is not a retry or a backfill; it is a close-ordering contract enforced at the instrumentation boundary, with a deadline that converts the unknown into a labeled unknown rather than a false zero.

import time
from dataclasses import dataclass, field
from typing import Optional

class UsageOrderingViolation(RuntimeError):
    """Raised when a span is closed before its terminal usage frame is applied."""
    pass

@dataclass
class GenAISpan:
    name: str
    attributes: dict = field(default_factory=dict)
    _ended: bool = False
    _usage_applied: bool = False
    _finish_reason_at: Optional[float] = None

    def set_attribute(self, key: str, value) -> None:
        if self._ended:
            # OTel SDK behavior: post-close writes are dropped. We refuse loudly.
            raise UsageOrderingViolation(
                f"set_attribute({key!r}) on ended span {self.name!r}; "
                "usage frame arrived after span close"
            )
        self.attributes[key] = value
        if key.startswith("gen_ai.usage."):
            self._usage_applied = True

    def on_finish_reason(self, reason: str) -> None:
        self.set_attribute("gen_ai.response.finish_reasons", [reason])
        self._finish_reason_at = time.monotonic()

    def on_usage_frame(self, input_tokens: int, output_tokens: int) -> None:
        if self._ended:
            raise UsageOrderingViolation(
                f"usage frame for {self.name!r} arrived after end(); "
                "provider emits usage after finish_reason — close on usage, not finish_reason"
            )
        self.set_attribute("gen_ai.usage.input_tokens", input_tokens)
        self.set_attribute("gen_ai.usage.output_tokens", output_tokens)

    def end(self, t_usage_deadline_s: float = 2.0) -> None:
        if self._finish_reason_at is not None and not self._usage_applied:
            waited = time.monotonic() - self._finish_reason_at
            if waited < t_usage_deadline_s:
                raise UsageOrderingViolation(
                    f"end() on {self.name!r} before usage frame; "
                    f"waited {waited:.3f}s < {t_usage_deadline_s}s — hold span open"
                )
            # Deadline exceeded: label the unknown rather than fabricate zero.
            self.attributes["genai.usage.reconciled"] = False
        self._ended = True


def close_streaming_turn(span: GenAISpan, frames: list[dict],
                         t_usage_deadline_s: float = 2.0) -> None:
    for frame in frames:
        kind = frame.get("kind")
        if kind == "content" and frame.get("finish_reason"):
            span.on_finish_reason(frame["finish_reason"])
        elif kind == "usage":
            span.on_usage_frame(frame["input_tokens"], frame["output_tokens"])
    span.end(t_usage_deadline_s=t_usage_deadline_s)