What happens when an instance reconciles OpenTelemetry GenAI token accounting across retried tool-call spans that share a reused `gen_ai.response.id`

**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OTel GenAI spans per LLM invocation and per tool call, where a retry policy or provider-side idempotency causes two or more spans to carry the same `gen_ai.response.id` (or the same `gen_ai.conversation.id` + turn index) and a downstream collector/aggregator sums `gen_ai.usage.input_tokens`/`output_tokens`. Does not apply to single-shot non-retried calls or to backends that deduplicate on span identity rather than on response identity.

Core Distinction

The GenAI semantic conventions treat token usage as a **per-response attribute** (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) attached to a span, not as a **per-attempt delta**. This is correct for cost attribution of a single logical model call, but it silently assumes a one-to-one mapping between `gen_ai.response.id` and a span. When an agent retries a tool call whose downstream LLM invocation returns the *same* provider response id (because the provider deduplicated an idempotent request, or because the framework re-emits the cached completion), two spans now describe one billable response. The distinction that matters operationally is **span identity vs. response identity**: token accounting is only sound if the aggregator keys on the latter, while span-level tracing tools naturally key on the former. The failure lives exactly in that gap.

What Was Observed

An agent executing a multi-step plan issued a tool call (`gen_ai.operation.name="execute_tool"`, `gen_ai.tool.name="search_docs"`) whose handler internally called a model with a retry wrapper (max 3 attempts, exponential backoff). Attempt 1 timed out at the transport layer after the provider had already committed the completion. Attempt 2 carried the same idempotency key; the provider returned the stored response with identical `gen_ai.response.id="resp_8f2a..."` and identical `gen_ai.usage.input_tokens=1840`, `output_tokens=612`. Both attempts emitted spans. The trace showed:

The token aggregator summed to 3680 input / 1224 output. The provider billed 1840 / 612. The agent's budget governor — which reads the aggregate to decide whether to continue the plan — saw 50% of a turn budget consumed by a single billable call and aborted the plan prematurely, then re-planned from a checkpoint that had already advanced, producing a duplicate side effect. The root trace was internally consistent; the *derived* accounting was not.

Condition of Validity

Summing `gen_ai.usage.*` across spans is valid **iff** every span maps to a distinct billable response, i.e. the set of `gen_ai.response.id` values across the summed spans has cardinality equal to the span count. The invariant to enforce is:

> For any aggregation window, `sum(input_tokens) == sum over distinct gen_ai.response.id of the token count attributed to that response`, and spans with duplicate response ids must be collapsed to exactly one contribution — the one from the terminal attempt (status `OK`, or the last attempt if all failed).

This holds only when the provider surfaces a stable `gen_ai.response.id` on retries and when the agent's retry wrapper propagates it. If the provider mints a fresh response id per attempt (no idempotency), the invariant is vacuously satisfied but the *cost* is genuinely double — a different, correct outcome. The dangerous case is the middle: stable id, duplicated spans, un-collapsed sum.

Decision Boundary

The boundary is between **collapsing on response identity** and **counting on span identity**, and it must be decided before the data reaches any consumer that acts on it (budget governor, autoscaler, cost dashboard). Concretely:

The decision must be enforced at the aggregator, not at the span emitter: emitters are per-attempt and cannot see siblings.

Operational Effect

Without the collapse, the observable effects are: premature budget exhaustion (the governor sees phantom spend), false autoscaling on token throughput, and — most damaging for agents — **checkpoint divergence**, where the plan controller's notion of remaining budget disagrees with the provider's, causing re-planning against a state that already advanced. With the collapse keyed on `gen_ai.response.id` and a hard refusal to aggregate when the key is missing, the budget governor's view converges to the provider's bill, and retried tool calls become accounting-neutral. The guardrail is cheap: one dedupe pass over the span batch before any consumer reads it, plus a fail-closed path when identity is ambiguous.

from dataclasses import dataclass, field
from typing import Iterable


class TokenAccountingInvariantError(RuntimeError):
    """Raised when GenAI token aggregation cannot be reconciled safely."""


@dataclass
class GenAISpan:
    span_id: str
    response_id: str | None
    conversation_id: str
    status: str  # "OK" | "ERROR"
    input_tokens: int
    output_tokens: int
    attempt: int = 1


@dataclass
class ReconciledUsage:
    input_tokens: int = 0
    output_tokens: int = 0
    superseded_span_ids: list[str] = field(default_factory=list)


def reconcile_usage(spans: Iterable[GenAISpan]) -> ReconciledUsage:
    """
    Collapse retried spans sharing a gen_ai.response.id to a single
    contribution (the terminal attempt). Fail closed when identity is
    ambiguous, because feeding unverified numbers to a budget governor
    causes checkpoint divergence.
    """
    by_response: dict[str, list[GenAISpan]] = {}
    missing_identity: list[GenAISpan] = []

    for span in spans:
        if not span.response_id:
            missing_identity.append(span)
            continue
        by_response.setdefault(span.response_id, []).append(span)

    if missing_identity:
        raise TokenAccountingInvariantError(
            f"{len(missing_identity)} span(s) lack gen_ai.response.id and no "
            f"dedupe_key fallback was supplied; refusing to aggregate "
            f"(span_ids={[s.span_id for s in missing_identity]})"
        )

    result = ReconciledUsage()
    for response_id, group in by_response.items():
        conv_ids = {s.conversation_id for s in group}
        if len(conv_ids) > 1:
            raise TokenAccountingInvariantError(
                f"response_id={response_id} spans multiple conversations "
                f"{sorted(conv_ids)}; provider identity collision, "
                f"quarantine window instead of collapsing"
            )

        # Terminal attempt: prefer OK, else highest attempt number.
        terminal = max(group, key=lambda s: (s.status == "OK", s.attempt))
        result.input_tokens += terminal.input_tokens
        result.output_tokens += terminal.output_tokens
        result.superseded_span_ids.extend(
            s.span_id for s in group if s.span_id != terminal.span_id
        )

    return result


def assert_budget_consistent(
    reconciled: ReconciledUsage, provider_input: int, provider_output: int
) -> None:
    if (reconciled.input_tokens, reconciled.output_tokens) != (
        provider_input,
        provider_output,
    ):
        raise TokenAccountingInvariantError(
            f"reconciled usage ({reconciled.input_tokens},{reconciled.output_tokens}) "
            f"!= provider bill ({provider_input},{provider_output}); "
            f"budget governor must not proceed"
        )