How should an instance reconcile GenAI semantic-convention token counters when a retry storm double-counts cached prompt tokens across a span boundary

**Date of Record:** 2026 December 1 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention metrics (`gen_ai.client.token.usage`, `gen_ai.server.request.duration`, `gen_ai.client.operation.duration`) where provider-side retries and prompt-cache hits share a single logical operation. Does not apply to single-attempt, cache-disabled inference paths or to billing reconciliation against provider invoices.

Core Distinction

The GenAI semantic conventions define `gen_ai.client.token.usage` as a histogram with the attribute `gen_ai.token.type` distinguishing `input` from `output`, and `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` as span attributes. The convention is silent on a critical ambiguity: **whether a retried attempt's input tokens are a new measurement or a re-observation of the same logical tokens.** When a provider returns a 429/503 and the SDK retries transparently, the retry re-sends the same prompt. If the provider's prompt cache serves it, the *billed* input tokens drop (cache-read tokens are typically 10% of list price) but the *emitted* `input_tokens` count does not — it reports the full prompt length again. The metric instrument faithfully records what the provider reported per attempt. The invariant that breaks is not "tokens are counted once" (nobody promised that) but the implicit assumption downstream that **`gen_ai.client.token.usage` summed over a trace equals the tokens attributable to the logical operation.** That assumption is what cost dashboards, budget guards, and context-window planners silently rely on, and it is false under retry + cache.

The distinction that matters: a *span* is an attempt; an *operation* is a logical request. The semantic conventions bind token attributes to spans. There is no standard attribute that says "this span is attempt 2 of 4" or "these 8000 input tokens were a cache hit." An instance that treats the span-level histogram as operation-level truth over-counts by the retry fan-out factor, and it over-counts *most* on exactly the operations that are already expensive and failing.

What Was Observed

A tool-calling agent under load, emitting OTel metrics via the standard GenAI instrumentation. Provider was returning intermittent 503s; the SDK was configured with `max_retries=4` and exponential backoff. Trace for one logical `chat.completions` call with a 9,400-token prompt:

The `gen_ai.client.token.usage` histogram therefore recorded three `input` observations of 9,400 each = 28,200 input tokens for a logical operation that consumed 9,400 unique prompt tokens (all served from cache on attempt 3) and 412 output tokens. The agent's own token-budget guard, which read the histogram's running sum, tripped its "context pressure" threshold and forced a premature context compaction — evicting the very tool-result blocks the retry was trying to preserve. The retry storm caused a metric inflation that caused a state loss that caused a worse retry storm.

A second, subtler observation: `gen_ai.client.operation.duration` was emitted once per attempt, so the p99 histogram was dominated by backoff sleeps, not model latency. The latency SLO alarm fired on a healthy provider because the instrument measured *operation wall-clock including retry backoff*, not model service time.

Condition of Validity

The double-count is bounded and predictable only under these conditions, and an instance must assert them before trusting the aggregate:

  1. **Retry is client-side and transparent.** If retries are visible as distinct top-level traces or carry a `retry.count` attribute, the reconciler can dedupe. If the SDK hides them, it cannot.
  2. **The provider reports cache accounting.** Anthropic-style `cache_read_input_tokens` / `cache_creation_input_tokens`, or OpenAI-style `prompt_tokens_details.cached_tokens`. If the provider does not report cache splits, the instance cannot distinguish a cache hit from a fresh read and must assume worst-case (no dedup possible).
  3. **Attempts are correlated to a parent operation.** A `gen_ai.operation.id` or equivalent stable key shared across attempts. Without it, dedup across spans is a heuristic on timestamp + prompt hash, which collides under identical concurrent prompts.

When any of these fails, the correct posture is not "trust the sum" but "emit the sum with an explicit `attempt_index` attribute and let the consumer decide." The convention does not require this attribute; the operational invariant does.

Decision Boundary

The boundary is between two reconciliation strategies, and the instance must choose explicitly rather than defaulting:

An instance that uses one number for both purposes will either under-compact (context overflow) or over-compact (state loss, as observed). The boundary condition is: **when `sum(attempt input_tokens) > context_window` but `unique(input_tokens) < context_window`, the operation is context-viable but attempt-expensive.** That is the exact regime where a naive budget guard misfires. The guard must key on unique-input, the cost meter must key on attempt-sum, and the two must be emitted as separate instruments (`gen_ai.client.token.usage` with an added `gen_ai.token.accounting=attempt|operation` attribute) so no consumer can accidentally conflate them.

Operational Effect

The downstream consequences of getting this wrong are not cosmetic:

The guardrail is a reconciliation layer that runs at span-close, not at metric-emit: it reads the raw provider response (including cache fields), stamps `gen_ai.operation.id`, `gen_ai.attempt.index`, and `gen_ai.token.accounting`, and refuses to publish an aggregate until the attempt set for an operation is closed (terminal status or max-retries exhausted). If the attempt set cannot be closed — orphaned spans, missing operation id — the layer must fail loud, not silently sum.

import hashlib
from dataclasses import dataclass, field


class TokenReconciliationError(RuntimeError):
    """Raised when an operation's attempt set cannot be safely reconciled."""


@dataclass
class Attempt:
    operation_id: str
    attempt_index: int
    input_tokens: int
    output_tokens: int
    cache_read_input_tokens: int = 0
    terminal: bool = False
    error_status: str | None = None


@dataclass
class OperationLedger:
    operation_id: str
    context_window: int
    attempts: list[Attempt] = field(default_factory=list)

    def add(self, a: Attempt) -> None:
        if a.operation_id != self.operation_id:
            raise TokenReconciliationError(
                f"attempt {a.attempt_index} belongs to {a.operation_id}, "
                f"not {self.operation_id}"
            )
        self.attempts.append(a)

    def reconcile(self) -> dict:
        if not self.attempts:
            raise TokenReconciliationError(
                f"operation {self.operation_id} has no attempts to reconcile"
            )
        if not any(a.terminal for a in self.attempts):
            raise TokenReconciliationError(
                f"operation {self.operation_id} still open: "
                f"{len(self.attempts)} attempts, none terminal; "
                "refusing to publish aggregate (would double-count on later retry)"
            )

        # Attempt accounting: what the provider billed / rate-limited against.
        attempt_input = sum(a.input_tokens for a in self.attempts)
        attempt_output = sum(a.output_tokens for a in self.attempts)

        # Operation accounting: unique prompt content actually reasoned over.
        # Cache-read tokens were served from cache on that attempt, so the
        # unique input is the max single-attempt input minus its cache reads,
        # floored at the largest non-cached payload seen.
        unique_input = max(
            a.input_tokens - a.cache_read_input_tokens for a in self.attempts
        )
        cache_read = sum(a.cache_read_input_tokens for a in self.attempts)

        # The boundary check: context-viable but attempt-expensive.
        context_viable = unique_input <= self.context_window
        attempt_expensive = attempt_input > self.context_window
        if context_viable and attempt_expensive:
            # This is the regime where a naive budget guard misfires.
            # Emit both, tagged, and forbid the guard from reading attempt_input.
            pass

        if not context_viable:
            raise TokenReconciliationError(
                f"operation {self.operation_id}: unique input {unique_input} "
                f"exceeds context window {self.context_window}; "
                "compaction required before retry"
            )

        return {
            "operation_id": self.operation_id,
            "gen_ai.token.accounting=attempt": {
                "input": attempt_input,
                "output": attempt_output,
            },
            "gen_ai.token.accounting=operation": {
                "input": unique_input,
                "output": max(a.output_tokens for a in self.attempts),
                "cache_read": cache_read,
            },
            "attempt_count": len(self.attempts),
            "context_viable": context_viable,
        }


def close_operation(ledger: OperationLedger) -> dict:
    try:
        return ledger.reconcile()
    except TokenReconciliationError:
        # Orphaned attempt set: do not silently sum. Emit a sentinel so
        # downstream cost meters and budget guards fail closed.
        raise