In what scenarios must an instance reject OpenTelemetry GenAI spans whose `genai.usage.input_tokens` disagrees with the provider's billed prompt-token count, and how does the accounting divergence compound across agent tool-call chains

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (attributes `genai.operation.name`, `genai.usage.input_tokens`, `genai.usage.output_tokens`, `genai.response.finish_reasons`, and tool-call child spans) and reconciles them against a provider billing or usage endpoint. Does not apply to runtimes that treat GenAI spans as purely observational and never bind them to cost, quota, or context-budget decisions.

Core Distinction

The GenAI semantic conventions define `genai.usage.input_tokens` and `genai.usage.output_tokens` as *reported usage* — the number the model provider returned in its response payload. They do not define these as *billed tokens*, and they do not define a reconciliation rule when the two diverge. This is the boundary that breaks agent runtimes: a span attribute is a telemetry fact about what the client observed, while the billing ledger is a fact about what the provider charged. These are usually equal and occasionally, structurally, are not.

The non-obvious divergence is not rounding. It is that **tool-call chains re-inject conversation history into every subsequent request**, so a single logical agent task produces N provider calls whose prompt token counts each include the accumulated prefix. The span tree records each call's `input_tokens` correctly and independently. Any consumer that sums `input_tokens` across the span tree to estimate task cost is not wrong about the spans — it is wrong about what a sum of per-call prompt counts means. The prefix is counted once per call, not once per token, and the same context bytes are billed N times while appearing N times in the sum. Reconciliation against the provider's aggregate usage endpoint will therefore *agree* with the naive sum in the common case, which is precisely what makes the failure invisible until it isn't.

What Was Observed

A three-tool agent loop (search → fetch → summarize) executed against a provider that returns `usage.prompt_tokens` per call. The span tree emitted:

Naive sum = 13,600 input tokens. Provider aggregate endpoint for the same window reported 13,600 prompt tokens. Agreement. The runtime's per-task budget accountant, which had a hard ceiling of 12,000 prompt tokens per task, did not fire — it compared the *last* span's `input_tokens` (5,030) against the ceiling, because the accountant's contract was "the current context size," and the current context size is the last call's prompt. The task consumed 13,600 billed tokens against a 12,000 ceiling and the guardrail never tripped.

The second observation is the one that produces the reconciliation failure. When the same loop ran with a provider-side prompt cache enabled, call 3 and call 4 returned `usage.prompt_tokens` that *excluded* cached prefix tokens, while the spans faithfully recorded the reduced numbers. The naive sum across spans was now 9,870. The provider's aggregate endpoint reported 13,600 (it bills cache reads at a discount but reports them in prompt tokens). The spans were correct per-call. The sum was correct as a sum. The reconciliation delta was 3,730 tokens with no span-level anomaly to point at, because the divergence lived in the *definition* of `input_tokens` shifting between calls within a single trace.

Condition of Validity

The invariant that must hold for a span-derived token total to be reconcilable against a billing ledger is:

> For every call i in a trace, `genai.usage.input_tokens[i]` must be computed under the same accounting regime R, and the consumer must know R.

R has at minimum three axes that the semantic conventions do not pin: (a) whether cached prefix tokens are included, (b) whether system-prompt and tool-schema tokens are counted, and (c) whether the provider's tokenizer matches the one the client used for any pre-flight estimate. A trace is *reconcilable* only if all spans in it share R and the runtime records R somewhere durable — a resource attribute, a span event, or a sidecar — because the conventions give no field for it.

When R changes mid-trace (cache warms on call 3, or a provider silently switches tokenizer versions between calls), the trace is *internally inconsistent* even though every individual span is a truthful record of its own response. This is the condition under which an instance must reject the span for accounting purposes: not because the span is wrong, but because the trace it belongs to cannot support a sum.

The second validity condition is prefix multiplicity. A per-task budget must be computed as `sum(input_tokens)` only if the budget is defined as *billed prompt tokens*. If the budget is defined as *context window occupancy*, the correct reduction is `max(input_tokens)` over the trace, not the sum. Conflating these two reductions is the single most common defect: a guardrail built for context saturation is reused as a cost guardrail because both read the same attribute.

Decision Boundary

An instance must reject (raise, not clamp) a GenAI span from a cost or quota accounting pipeline when any of the following hold, and must accept it into the observability pipeline regardless:

  1. **Regime discontinuity.** Two spans in the same trace carry `input_tokens` values that cannot be explained by a monotonic prefix growth model — i.e., `input_tokens[i+1] < input_tokens[i]` without a corresponding context-truncation span event. This signals cache accounting or provider-side trimming. The span is valid telemetry; the trace is not summable.
  2. **Reduction mismatch.** The consumer's declared budget semantics (`billed` vs `occupancy`) do not match the reduction it applies (`sum` vs `max`). This is a configuration error, not a data error, but it must fail closed at the accounting boundary rather than silently under-count.
  3. **Reconciliation delta above tolerance with no span-level explanation.** If `provider_aggregate − sum(spans)` exceeds tolerance and no span in the window carries a regime marker, the trace set is unaccountable and must be quarantined rather than attributed to the nearest task.
  4. **Missing finish reason on a terminal span.** A span with `genai.usage.output_tokens > 0` but no `genai.response.finish_reasons` may represent a truncated response whose prompt was billed but whose completion was not recorded; summing it understates cost. Reject from accounting, retain for debugging.

The boundary is asymmetric on purpose. Observability must never drop a span because it is inconvenient to account for — that destroys the audit trail that makes the divergence diagnosable. Accounting must never accept a span whose trace-level invariants fail — that launders an error into a budget that then silently permits overspend.

Operational Effect

The practical consequence is that token accounting cannot be a pure function of the span tree. It requires a trace-level reducer that (a) reads a regime marker, (b) selects `sum` or `max` by declared budget semantics, and (c) emits a first-class `accounting_divergence` event when the reducer's output disagrees with the provider aggregate beyond tolerance, carrying the delta and the trace ID. The divergence event is the artifact that lets a downstream agent decide whether to halt, re-budget, or escalate — it is the only place where "the spans say X, the bill says Y" becomes actionable rather than a mystery in a dashboard.

Without this, the failure mode is quiet and directional: agent loops that lean on tool calls systematically under-account for cost (because per-call prompt counts look small and the sum is never taken) and systematically over-account for context headroom (because the last call's count is used as if it were the peak). Both errors push the same way — toward running longer, larger, and more expensive than the guardrail believes — and both are invisible in any per-span view.

from dataclasses import dataclass
from enum import Enum


class AccountingRegime(Enum):
    BILLED_PROMPT = "billed_prompt"      # includes cached prefix, sums across calls
    CONTEXT_OCCUPANCY = "occupancy"      # peak context, max across calls


class TokenAccountingError(RuntimeError):
    """Raised when a GenAI span trace cannot be reduced to a reconcilable total."""


@dataclass(frozen=True)
class GenAISpan:
    span_id: str
    input_tokens: int
    output_tokens: int
    finish_reasons: tuple[str, ...]
    regime_marker: str | None


def reduce_trace_tokens(
    spans: list[GenAISpan],
    regime: AccountingRegime,
    provider_aggregate: int,
    tolerance: int = 0,
) -> int:
    if not spans:
        raise TokenAccountingError("empty trace: nothing to reduce")

    markers = {s.regime_marker for s in spans}
    if len(markers) > 1:
        raise TokenAccountingError(
            f"regime discontinuity across trace: markers={markers}"
        )

    for prev, cur in zip(spans, spans[1:]):
        if cur.input_tokens < prev.input_tokens and not cur.finish_reasons:
            raise TokenAccountingError(
                f"non-monotonic prompt growth at {cur.span_id} "
                f"({prev.input_tokens} -> {cur.input_tokens}) with no truncation marker"
            )

    for s in spans:
        if s.output_tokens > 0 and not s.finish_reasons:
            raise TokenAccountingError(
                f"span {s.span_id} has output tokens but no finish reason; "
                "prompt may be billed without a recorded completion"
            )

    if regime is AccountingRegime.BILLED_PROMPT:
        total = sum(s.input_tokens for s in spans)
    elif regime is AccountingRegime.CONTEXT_OCCUPANCY:
        total = max(s.input_tokens for s in spans)
    else:
        raise TokenAccountingError(f"unknown regime {regime!r}")

    delta = provider_aggregate - total
    if abs(delta) > tolerance:
        raise TokenAccountingError(
            f"reconciliation delta {delta} exceeds tolerance {tolerance} "
            f"under regime {regime.value}; quarantine trace for audit"
        )

    return total