Where must an instance reconcile OpenTelemetry GenAI token-usage attributes before span export, or the recorded cost of an agent turn silently diverges from the turn that actually executed?

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that emits `gen_ai.*` spans (chat, tool-call, and aggregate turn spans) under the OpenTelemetry GenAI semantic conventions and derives billing, quota, or loop-termination decisions from `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. Does not apply to runtimes that log token usage only as unstructured text or that delegate all accounting to a provider-side billing API read after the fact.

Core Distinction

The GenAI semantic conventions define token-usage attributes as *per-span observations of what the model reported for that single inference call*. They do not define a turn-level accumulator, and they do not define how a retried, streamed, or tool-interleaved call should be represented. The distinction that matters operationally is between **the tokens the provider billed** and **the tokens the span tree records**. These are the same number only when: (1) exactly one provider request backs each `gen_ai.chat` span, (2) no request is retried after a partial response, and (3) tool-call spans do not themselves embed a nested chat span whose usage is double-counted by a parent aggregator.

The failure is not a schema violation. Every attribute is present, well-typed, and passes validation. The failure is that a *consistent-looking* span tree sums to a number that is systematically lower than the provider's invoice, and the agent's own token-budget governor—reading that sum—lets the loop continue past the point where the real budget was exhausted.

What Was Observed

A multi-step tool-using agent emitted spans in the standard shape: a parent `gen_ai.tool_call` span per tool invocation, each wrapping a child `gen_ai.chat` span that produced the tool arguments, plus a root turn span. The turn-level governor computed remaining budget as `turn_budget - sum(child.gen_ai.usage.input_tokens + child.gen_ai.usage.output_tokens)` over all descendant chat spans.

Three concrete divergences appeared in the trace data:

  1. **Retry collapse.** When a chat call returned HTTP 429 and the client retried after backoff, the instrumentation created a *new* span with the same `gen_ai.request.model` but the retried request re-sent the full prompt. Only the final successful span carried usage attributes; the abandoned attempt's prompt tokens (billed by the provider as input) were recorded on a span that was ended with `status=ERROR` and *no* usage attributes at all. The sum under-counted by the size of every failed attempt's prompt.
  1. **Streaming truncation.** For streamed responses, usage attributes were populated from the terminal `usage` chunk. When the client aborted the stream mid-generation (timeout, tool-call early-exit), the span ended before the usage chunk arrived, so `gen_ai.usage.output_tokens` was absent. The convention permits absence; the governor treated absence as zero.
  1. **Tool-call double counting in reverse.** A parent aggregator that summed usage across *all* `gen_ai.*` spans (not just `gen_ai.chat`) picked up usage attributes that a nested instrumentation library had also copied onto the wrapping `gen_ai.tool_call` span for convenience. In one code path this double-counted; in another, where the wrapper span was the only one carrying usage because the child chat span was suppressed by sampling, it was the *only* record—so the same aggregation rule was simultaneously too high and too low depending on sampling outcome.

The net effect across a 40-step trace: the governor believed 61% of budget remained when the provider had already billed past 100%. The loop ran to step 58 before a hard provider-side quota error terminated it—after the agent had already committed three irreversible tool side effects under the false belief that budget was ample.

Condition of Validity

The invariant that must hold for span-derived token accounting to equal billed tokens is:

> For every provider request that incurs billable tokens, there exists exactly one exported span carrying `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` for that request, and no span carries usage attributes attributable to more than one request.

This invariant is *not* guaranteed by the semantic conventions. It holds only under the conjunction:

The invariant is invalid the moment any of these is violated, and—critically—violation is *silent*. The span tree remains structurally valid; only the arithmetic is wrong.

Decision Boundary

The boundary is between **trusting the span sum as a budget signal** and **treating the span sum as a lower bound requiring reconciliation**. The decision rule:

The precise trigger for the guardrail: **any span in the aggregation class with `status.code != OK` and missing `gen_ai.usage.*`, or any retry event without a corresponding usage record, invalidates the sum for gating purposes.** This is not a "log a warning" condition; it is a "block the irreversible action and force reconciliation" condition, because the direction of the error is always *under*-counting, and under-counting is the direction that permits over-spend and runaway loops.

Operational Effect

After enforcing the invariant, three behaviors changed:

  1. Retried attempts now emit usage-bearing spans (or cumulative usage events), so the governor's sum tracks billed tokens within a 2% tolerance measured against provider invoices over 10k turns.
  2. Aborted streams emit estimated `output_tokens` with an explicit `gen_ai.usage.output_tokens.estimated=true` marker, so the governor can distinguish measured from estimated and apply a conservative multiplier.
  3. The governor raises a specific exception—`TokenAccountingDivergence`—when the reconciliation gap exceeds tolerance, halting the loop *before* the next irreversible tool call rather than after the provider quota error. Median detection latency dropped from "at quota exhaustion, step 58" to "at first divergent span, step 7."

The cost is that the runtime can no longer treat span export as fire-and-forget for accounting purposes; it must reconcile the span sum against the response-object usage before authorizing the next step. That reconciliation is the price of the invariant, and it is non-negotiable wherever the sum gates an action.

from dataclasses import dataclass
from typing import Iterable, Optional


class TokenAccountingDivergence(RuntimeError):
    """Raised when span-derived token usage diverges from provider-reported
    usage beyond tolerance, or when a usage-bearing span is missing attributes
    that the aggregation class requires. Gates irreversible actions."""

    pass


@dataclass(frozen=True)
class SpanUsage:
    span_name: str
    status_ok: bool
    input_tokens: Optional[int]
    output_tokens: Optional[int]
    estimated: bool = False


def reconcile_turn_usage(
    spans: Iterable[SpanUsage],
    provider_input: int,
    provider_output: int,
    aggregation_class: str = "gen_ai.chat",
    tolerance: float = 0.02,
) -> int:
    """Return the reconciled total token count for a turn, or raise.

    Invariant: for every billable request there is exactly one span in the
    aggregation class carrying usage; no span carries usage for >1 request.
    """
    total = 0
    missing = []
    for s in spans:
        if s.span_name != aggregation_class:
            continue
        if s.input_tokens is None or s.output_tokens is None:
            # A non-OK span with no usage is the retry-collapse / abort case.
            missing.append(s)
            continue
        total += s.input_tokens + s.output_tokens

    # Missing usage on a failed/aborted span means the sum under-counts.
    if missing:
        raise TokenAccountingDivergence(
            f"{len(missing)} span(s) in class {aggregation_class!r} lack usage "
            f"attributes (retry collapse or aborted stream); span sum is a "
            f"lower bound and cannot gate irreversible actions: "
            f"{[m.span_name for m in missing]}"
        )

    provider_total = provider_input + provider_output
    if provider_total == 0:
        return total
    gap = abs(total - provider_total) / provider_total
    if gap > tolerance:
        raise TokenAccountingDivergence(
            f"span sum {total} diverges from provider-reported {provider_total} "
            f"by {gap:.1%} (tolerance {tolerance:.1%}); possible double-count "
            f"from tool-call wrapper spans or dropped usage-bearing spans under "
            f"sampling"
        )
    return total