How should an instance reconcile OpenTelemetry GenAI token-usage attributes when a streaming model invocation is retried mid-flight and the span is re-parented under a new attempt context?

**Date of Record:** 2026 December 2 **Scope:** Applies to agent runtimes that emit `gen_ai.*` OpenTelemetry spans around model invocations, especially streaming calls that are retried, hedged, or resumed after a transport interruption. Does not cover batch/offline inference that has no live span lifecycle, nor non-LLM tool spans.

Core Distinction

The failure here is not "missing telemetry." It is **double-counted and orphaned token accounting caused by span re-parenting across a retry boundary**. When a streaming invocation fails partway through, the runtime typically aborts the original span and opens a *new* attempt span. The subtlety: the aborted attempt already consumed tokens (prompt tokens were billed on request acceptance; partial completion tokens were generated before the stream broke). The retry attempt re-sends the same prompt and consumes prompt tokens *again*. If both spans carry `gen_ai.usage.input_tokens` and both are exported, the upstream aggregator sums them and the run's token ledger overstates cost — while the *semantic* record (which logical invocation this was) is fragmented across two span IDs with no shared correlation key.

The non-obvious boundary: **OpenTelemetry GenAI conventions define token attributes per span, but define no invariant for how token usage composes across attempt spans that belong to one logical model call.** The spec assumes one span ≈ one billable invocation. Retries violate that assumption silently.

What Was Observed

A streaming agent invocation with a 90-second server-side timeout was interrupted at ~62 seconds by a TCP reset from the inference gateway. The runtime's retry policy (3 attempts, exponential backoff) fired.

Trace of the two spans:

Three defects surfaced together:

  1. **Ledger overstatement.** Aggregating `input_tokens` across both spans yields 3680 for a logical call whose true prompt cost is 1840 (the prompt was billed twice, but the *semantic* input is one prompt). Output aggregation yields 2623, but the client only ever *used* 2011 tokens of that output — the 612 from attempt 1 were discarded at the application layer yet still exported as consumed.
  2. **Orphaned partial output.** Span `a1`'s 612 output tokens have no parent linkage to `a2`. A downstream auditor reconstructing "what did the model actually produce for this request" sees two disconnected completions and cannot tell which is authoritative.
  3. **Re-parenting broke the trace tree.** The retry wrapper opened `a2` under the *retry loop's* span, not under the original invocation span. `a1` and `a2` became siblings, not parent/child, so a trace-based cost rollup that sums leaf spans double-counts, and a rollup that takes the last leaf undercounts (it drops `a1`'s real spend).

The root trigger: the retry boundary and the span boundary were coupled to the same event. The runtime treated "stream broke" as "span ends, new span starts," when the correct model is "logical invocation persists across transport attempts; each attempt is an *event*, not a new logical unit."

Condition of Validity

The invariant that must hold: **for any logical model invocation, the sum of committed token usage across all attempt spans equals the true billable consumption, and exactly one attempt span is designated authoritative for semantic output.**

This holds only when the runtime distinguishes three token classes and attributes them correctly:

The invariant is violated whenever a span is emitted with `gen_ai.usage.*` set but without an attempt-role marker distinguishing committed vs. aborted, or without a shared `gen_ai.invocation.id` (a logical-call correlation attribute) that survives re-parenting. Without that correlation key, no downstream consumer can reconstruct the invariant — the information is not in the trace.

Decision Boundary

The decision is *where to draw the span boundary relative to the retry boundary*, and it is a genuine fork:

The boundary condition that forces the choice: **does the backend's rollup logic know about retries?** If it does not (most do not), Option A is the only safe default, because it makes the correct number the *only* number present on the span. Option B is defensible only when the consuming pipeline is co-versioned with the emitter and enforces the `invocation.id` grouping contract.

The failure mode is choosing Option B without enforcing the contract — which is exactly what the observed runtime did. It emitted per-attempt spans (Option B shape) but no correlation key and no role marker, so it got the worst of both: fragmented semantics and un-dedupable cost.

Operational Effect

Downstream, the overstatement propagated into the agent's own budgeting loop: the runtime's token-budget guard read the aggregated `input_tokens` after the retry and concluded the run had consumed 3680 of a 4096 prompt-token budget, throttling the next turn to a truncated context. The agent then produced a degraded answer — not because of the model, but because **telemetry double-counting fed back into the control loop as a false resource-exhaustion signal.** This is the compounding hazard: token telemetry is not passive observability when an agent uses it to gate its own behavior. A 2× overstatement on a retried call becomes a premature context truncation, which becomes a reasoning divergence.

The guardrail that bounds it: the budget controller must consume *reconciled* usage (grouped by `invocation.id`, committed-only for semantic totals, all-attempts for cost), never raw span sums. And the emitter must guarantee that any span carrying `gen_ai.usage.*` also carries the invocation correlation key and attempt role — enforced at span-close time, not at export time, so a malformed span fails the invocation rather than silently poisoning the ledger.

from dataclasses import dataclass, field
from typing import Literal


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a logical model invocation's telemetry violates the
    committed-vs-billed token reconciliation invariant."""


@dataclass
class AttemptSpan:
    span_id: str
    invocation_id: str | None
    role: Literal["committed", "aborted", "unknown"]
    input_tokens: int
    output_tokens: int


@dataclass
class ReconciledUsage:
    semantic_input_tokens: int
    semantic_output_tokens: int
    billed_input_tokens: int
    billed_output_tokens: int


def reconcile_invocation(spans: list[AttemptSpan]) -> ReconciledUsage:
    if not spans:
        raise TokenAccountingInvariantError("no attempt spans for invocation")

    # Invariant 1: every span must carry a correlation key.
    missing = [s.span_id for s in spans if not s.invocation_id]
    if missing:
        raise TokenAccountingInvariantError(
            f"attempt spans missing gen_ai.invocation.id: {missing}; "
            "cannot dedupe retried usage"
        )

    # Invariant 2: all spans must belong to the same logical invocation.
    ids = {s.invocation_id for s in spans}
    if len(ids) != 1:
        raise TokenAccountingInvariantError(
            f"spans span multiple invocations {ids}; refusing to reconcile"
        )

    # Invariant 3: exactly one committed attempt, or none (total failure).
    committed = [s for s in spans if s.role == "committed"]
    if len(committed) > 1:
        raise TokenAccountingInvariantError(
            f"multiple committed attempts {[s.span_id for s in committed]}; "
            "semantic output is ambiguous"
        )

    # Invariant 4: no span may have unknown role — role is required to
    # distinguish billed-but-discarded from billed-and-committed tokens.
    unknown = [s.span_id for s in spans if s.role == "unknown"]
    if unknown:
        raise TokenAccountingInvariantError(
            f"attempt spans with unresolved role: {unknown}; "
            "aborted output tokens would silently roll into semantic totals"
        )

    # Billed cost sums across ALL attempts (money was spent).
    billed_in = sum(s.input_tokens for s in spans)
    billed_out = sum(s.output_tokens for s in spans)

    # Semantic totals come from the committed attempt only.
    if committed:
        semantic_in = committed[0].input_tokens
        semantic_out = committed[0].output_tokens
    else:
        semantic_in = 0
        semantic_out = 0

    return ReconciledUsage(
        semantic_input_tokens=semantic_in,
        semantic_output_tokens=semantic_out,
        billed_input_tokens=billed_in,
        billed_output_tokens=billed_out,
    )


# Reproduces the observed failure: two sibling spans, no correlation key,
# roles unresolved. The reconciler must refuse rather than double-count.
observed = [
    AttemptSpan("a1", None, "unknown", 1840, 612),
    AttemptSpan("a2", None, "unknown", 1840, 2011),
]
try:
    reconcile_invocation(observed)
except TokenAccountingInvariantError as e:
    print(f"BLOCKED: {e}")

# Corrected emission: shared invocation id, explicit roles.
corrected = [
    AttemptSpan("a1", "inv-7f3a", "aborted", 1840, 612),
    AttemptSpan("a2", "inv-7f3a", "committed", 1840, 2011),
]
usage = reconcile_invocation(corrected)
assert usage.semantic_output_tokens == 2011   # what the agent actually used
assert usage.billed_output_tokens == 2623     # what the provider billed
assert usage.semantic_input_tokens == 1840    # one logical prompt
assert usage.billed_input_tokens == 3680      # prompt billed twice
print(usage)