What structural signals indicate an agent span has silently double-counted tokens across a retried model invocation

**Date of Record:** 2026 December 2 **Scope:** Applies to agents emitting OpenTelemetry GenAI spans (`gen_ai.*` attributes) where a single logical "model invocation" step is retried at the SDK, transport, or orchestration layer while the span lifecycle is not. Does not cover streaming-only token reconciliation or cost-accounting outside the OTel pipeline.

Core Distinction

The GenAI semantic conventions treat a model invocation as a *span* with `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` recorded as span attributes, and (in newer drafts) as discrete `gen_ai.client.inference.operation.details` events. The convention assumes a one-to-one mapping: one span, one billable invocation, one token count.

That assumption is false under retry. When a model call fails mid-generation and the retry logic re-issues the request *inside the same span scope*, the instrumentation typically **adds** the retry's usage to the existing attributes rather than replacing them. The result is a span that is structurally valid, passes schema validation, and reports a token total that no single invocation actually consumed. The distinction that matters: a *retried* invocation is not a *replayed* one. Replay semantics (last-write-wins) and accumulation semantics (sum) are both defensible in isolation, but the GenAI conventions do not specify which applies to `usage.*` on retry, so instrumentations diverge silently.

What Was Observed

A tool-using agent (planner → retrieval tool → synthesis model call) showed a 40% cost overrun against provider-side billing, with no error spans and no `status.code = ERROR`. Tracing the span tree revealed the mechanism:

  1. The synthesis step opened a span `gen_ai.client.inference` with `gen_ai.request.model = "..."` and `gen_ai.operation.name = "chat"`.
  2. The first HTTP attempt returned `429` after emitting 312 prompt tokens. The SDK retried transparently.
  3. The retry succeeded, emitting 1,204 prompt tokens and 480 completion tokens.
  4. The span closed with `gen_ai.usage.input_tokens = 1516` (312 + 1204) and `output_tokens = 480`.

The span *looked* correct. It was monotonic, positive, and internally consistent. But the 312 tokens from the aborted attempt were partially cached/billed differently and were never part of the successful response's accounting. Any downstream cost aggregation that trusted the span attribute overstated spend and, worse, mis-attributed cache-hit vs. cache-miss tokens because the retry's cached-prefix accounting was folded into a single scalar.

The tell was not in the span. It was in the **event stream**: the span carried one `gen_ai.client.inference.operation.details` event (from the successful attempt) but the `input_tokens` attribute reflected two attempts. Attribute/event cardinality mismatch is the structural signal.

Condition of Validity

The invariant — "sum of `gen_ai.usage.*` across a span equals the usage of exactly one provider invocation" — holds only when:

When any of these is violated, the attribute is an accumulator, not a measurement. Note this is orthogonal to whether the tokens were *billed* — a provider may bill for the aborted attempt; the failure is that the span cannot distinguish "billed tokens" from "tokens in the successful response," and downstream reasoning (e.g., an agent deciding whether to re-plan due to budget pressure) relies on the distinction.

Decision Boundary

An agent or telemetry auditor should treat a span's `gen_ai.usage.*` as **untrusted for cost decisions** and fall back to event-level accounting when it observes any of:

The boundary is asymmetric: absence of a retry attribute is *not* evidence of no retry. A single-attempt span and a silently-retried span are indistinguishable from attributes alone; only event cardinality disambiguates. Therefore the safe default is: reconcile against events, and emit a `retry.attempt` child span whenever the transport layer re-issues, so the invariant is structurally enforceable rather than inferred.

Operational Effect

Once an agent's budget governor starts reading double-counted spans, it trips its token ceiling early, truncates the plan, and escalates — producing a *functional* failure (premature re-planning) that looks like a reasoning failure but is a telemetry artifact. The fix is to make the invariant structural: one span per physical attempt, usage attributes scoped to that attempt, and the logical step represented by a parent span that carries *no* usage attributes of its own (only the sum, computed at aggregation time from events). This preserves both the retry's real cost and the successful attempt's response accounting without conflating them.

from dataclasses import dataclass
from typing import Optional


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a GenAI span's usage attributes cannot be reconciled
    to a single physical model invocation via its event stream."""


@dataclass
class InferenceEvent:
    attempt: int
    input_tokens: int
    output_tokens: int
    cached_input_tokens: int = 0


@dataclass
class GenAISpan:
    name: str
    input_tokens_attr: Optional[int]
    output_tokens_attr: Optional[int]
    events: list[InferenceEvent]
    retry_attempt_attr: Optional[int] = None


def reconcile_span(span: GenAISpan) -> dict:
    """Enforce: attribute usage == usage of exactly one physical attempt.

    The structural signal of silent double-counting is attribute/event
    cardinality mismatch: the scalar attribute sums multiple attempts
    while only one inference.operation.details event was emitted.
    """
    if span.input_tokens_attr is None or span.output_tokens_attr is None:
        raise TokenAccountingInvariantError(
            f"span {span.name!r} missing gen_ai.usage.* attributes; "
            "cannot reconcile against events"
        )

    if not span.events:
        raise TokenAccountingInvariantError(
            f"span {span.name!r} has usage attributes but zero "
            "gen_ai.client.inference.operation.details events; "
            "attribute is an accumulator, not a measurement"
        )

    event_input = sum(e.input_tokens for e in span.events)
    event_output = sum(e.output_tokens for e in span.events)

    if span.input_tokens_attr != event_input or span.output_tokens_attr != event_output:
        raise TokenAccountingInvariantError(
            f"span {span.name!r} attribute/event mismatch: "
            f"attr=({span.input_tokens_attr},{span.output_tokens_attr}) "
            f"events=({event_input},{event_output}) across "
            f"{len(span.events)} attempt(s); silent retry double-count suspected"
        )

    distinct_attempts = {e.attempt for e in span.events}
    if len(distinct_attempts) > 1 and span.retry_attempt_attr is None:
        raise TokenAccountingInvariantError(
            f"span {span.name!r} folded {len(distinct_attempts)} attempts "
            "into one span without retry.attempt attribute; "
            "retry boundary is unrecoverable downstream"
        )

    return {
        "logical_input_tokens": event_input,
        "logical_output_tokens": event_output,
        "physical_attempts": len(distinct_attempts),
        "billable_input_tokens": sum(e.input_tokens for e in span.events),
        "cache_hit_tokens": sum(e.cached_input_tokens for e in span.events),
    }