# Under what conditions must an instance treat OpenTelemetry GenAI `gen_ai.usage.*` token counters as non-authoritative across a retried tool-call span **Date of Record:** 2026 November 23 **Scope:** Applies to agent runtimes that emit OTel GenAI spans (`gen_ai.operation.name` = `chat`, `execute_tool`, `invoke_agent`) and aggregate `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` for cost, budget, or context-pressure decisions. Does not apply to single-shot, non-retried inference calls where one span maps 1:1 to one billed provider request. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes on a span representing *a model invocation*. They are **per-span descriptive facts about a request that occurred**, not ledger entries. The convention is silent on retries, streaming partials, and speculative decoding, because it assumes one span = one provider round-trip. The failure mode is the collapse of that assumption. When an agent retries a tool call, re-issues a chat completion after a schema-validation failure, or replays a span during checkpoint/resume, the runtime emits *multiple* spans that each carry usage attributes, and a naive aggregator that sums `gen_ai.usage.*` across spans of one logical operation will **double-count tokens for work the provider billed once, or under-count tokens the provider billed across attempts**. The span is authoritative about *what the model consumed on that attempt*; it is not authoritative about *what the operation cost*. This is the non-obvious boundary: the attribute is correct per-span and wrong per-aggregate. ## What Was Observed A `chat` span with `gen_ai.operation.name = "chat"` completed with `gen_ai.usage.input_tokens = 4180`, `gen_ai.usage.output_tokens = 612`. The downstream tool (`execute_tool`, `gen_ai.tool.name = "search_index"`) returned a payload that failed the agent's JSON-schema validation on `output_tokens` boundary — the model had emitted a truncated object at exactly the `max_tokens` cap. The runtime's retry policy re-issued the chat with a widened cap and a repair preamble. Trace of the resulting span tree: ``` invoke_agent (agent_id=researcher-7) ├── chat (attempt=0) input=4180 output=612 finish_reason=length ├── execute_tool (search) status=error schema_validation_failed ├── chat (attempt=1) input=5410 output=930 finish_reason=stop └── chat (attempt=2) input=5410 output=930 finish_reason=stop ← duplicate emit ``` Three observations: 1. **The duplicate `attempt=2` span is real.** A checkpoint/resume boundary fired between the provider response and the span exporter flush; the runtime's at-least-once span emission replayed the completed attempt. The provider billed one call for attempt 1; the trace shows two. 2. **Attempt 0's 612 output tokens were billed and discarded.** The aggregator that summed all `chat` spans under `invoke_agent` reported 15,000 input / 2,472 output. The provider invoice for the operation was 9,590 input / 1,542 output. 3. **No attribute disambiguates retry from duplicate.** The convention offers no `gen_ai.request.retry_count`, no `gen_ai.usage.billed` flag, and no span-link convention for "this span supersedes that one." The `chat` spans are siblings; a span processor cannot tell replay from retry from a legitimately parallel second call. The compounding case is worse: a tool-call loop where each `execute_tool` span carries its own nested `chat` span for the model call that produced the tool arguments. Summing leaf `chat` spans across a 40-step agent loop with a 15% retry rate inflated the token budget by 22% in a measured run, which tripped a context-pressure guard at step 31 that should have fired at step 38 — the agent checkpointed and cold-started prematurely, losing the episodic memory of steps 1–30. ## Condition of Validity The `gen_ai.usage.*` attributes are authoritative for an aggregate **iff** all of the following hold: - **One span per provider round-trip, at-least-once emission is deduplicated.** The exporter must guarantee exactly-once span delivery, or the aggregator must dedupe on a stable key. The OTel spec does not provide one for GenAI spans; the runtime must synthesize it. The only stable composite available is `(trace_id, parent_span_id, gen_ai.operation.name, gen_ai.request.model, hash(canonicalized request))` — and the request hash requires the runtime to retain the canonical request, which most do not. - **Retries are represented as distinct, linked spans, not summed as siblings.** A retry must be modeled with a `SpanLink` from attempt *n+1* to attempt *n*, and the aggregator must apply a fold (take-last-wins or take-max) rather than a sum over linked attempts. - **Discarded attempts are marked.** An attempt whose output was rejected by validation must carry an explicit status or attribute (e.g., `gen_ai.response.finish_reasons = ["length"]` plus a runtime-specific `attempt.discarded = true`) so the aggregator can exclude it from the *billed* total while retaining it in the *consumed* total. These are different numbers and the convention conflates them. - **The accounting consumer knows which total it needs.** Context-pressure guards need *consumed* tokens (including discarded attempts, because they occupied the window). Cost ledgers need *billed* tokens (excluding discarded attempts and deduped replays). Budget enforcement needs *billed* tokens against a provider quota. When any of these fails, the attribute remains a valid per-span fact and an invalid aggregate input. The invariant is: **`gen_ai.usage.*` is span-local; any cross-span arithmetic over it requires a deduplication and retry-fold discipline that the semantic conventions do not specify and the runtime must impose.** ## Decision Boundary The runtime must decide, before it emits or consumes a `chat` span, which of two modes it is in: - **Descriptive mode** — the span is emitted for observability only; downstream sums are advisory, and no control-flow decision (context compaction, budget halt, checkpoint) reads the aggregate. Here, summing all `chat` spans is acceptable because the error is bounded by retry rate and no action depends on it. - **Authoritative mode** — the aggregate drives a decision. Here, the runtime MUST NOT sum raw `gen_ai.usage.*`. It must route through a fold that (a) dedupes on the composite key, (b) excludes `attempt.discarded` spans from billed totals, (c) includes them in consumed totals, and (d) refuses to compute if the dedupe key is unavailable. The boundary is crossed silently when a team adds a context-pressure guard that reads the trace backend's `sum(gen_ai.usage.input_tokens)` without knowing the trace backend has no dedupe. The failure is not in the guard; it is in the unstated promotion of a descriptive attribute to an authoritative one. The guardrail: **a consumer that reads `gen_ai.usage.*` for a decision must declare its accounting mode and must fail closed when the span set contains unlinked sibling `chat` spans under one `invoke_agent`.** Sibling `chat` spans with no `SpanLink` between them are either parallel calls (sum is correct) or retries with a broken link (sum is wrong); the runtime cannot distinguish them, so it must not guess. ## Operational Effect The observable consequences of getting this wrong are asymmetric and lagging: - **Cost ledgers drift high** by the retry rate times the mean discarded-attempt token count. In the measured run, a 15% retry rate with discarded attempts averaging 40% of final output produced a 22% overcount. The drift is invisible until reconciliation against the provider invoice, typically a billing cycle later. - **Context-pressure guards fire early**, causing premature checkpoint and cold-start. The cold-start drops episodic memory, and the re-derived semantic memory misses distillation from the truncated steps — a second-order continuity loss that is not visible in the token metrics at all. - **Budget halts fire late or never** when the aggregator dedupes replays but forgets to include discarded attempts in the consumed total, so the agent believes it has headroom it has already spent. The durable fix is to stop treating the semantic conventions as an accounting schema. They are a *tracing* schema. The runtime that needs authoritative token accounting must maintain its own ledger keyed on the provider's request ID (which the provider returns and the convention does not capture), reconcile against it, and treat `gen_ai.usage.*` as a cross-check that is allowed to disagree by the retry-and-replay factor. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Iterable class TokenAccountingInvariantError(RuntimeError): """Raised when a GenAI span set cannot be folded into an authoritative total.""" @dataclass(frozen=True) class GenAIChatSpan: span_id: str parent_span_id: str | None operation_name: str # gen_ai.operation.name model: str # gen_ai.request.model request_hash: str # canonicalized request digest input_tokens: int # gen_ai.usage.input_tokens output_tokens: int # gen_ai.usage.output_tokens finish_reasons: tuple[str, ...] # gen_ai.response.finish_reasons discarded: bool = False # runtime-specific: output rejected by validation linked_from: str | None = None # SpanLink to prior attempt, if a retry @dataclass class FoldResult: billed_input: int = 0 billed_output: int = 0 consumed_input: int = 0 consumed_output: int = 0 deduped: int = 0 discarded: int = 0 seen_keys: set[tuple[str, str, str]] = field(default_factory=set) def fold_authoritative_tokens( spans: Iterable[GenAIChatSpan], *, require_dedupe_key: bool = True, ) -> FoldResult: """ Fold GenAI chat spans into authoritative billed/consumed totals. Billed = tokens the provider charged (deduped, discarded excluded). Consumed = tokens that occupied the context window (deduped, discarded included). Fails closed when the span set is ambiguous: unlinked sibling chat spans under one parent, or missing dedupe keys. """ chat_spans = [s for s in spans if s.operation_name == "chat"] # Group by parent to detect unlinked siblings (retry vs parallel ambiguity). by_parent: dict[str | None, list[GenAIChatSpan]] = {} for s in chat_spans: by_parent.setdefault(s.parent_span_id, []).append(s) for parent, group in by_parent.items(): if len(group) <= 1: continue linked_ids = {s.linked_from for s in group if s.linked_from} unlinked = [s for s in group if s.span_id not in linked_ids and s.linked_from is None] # If more than one span lacks a link to a prior attempt, we cannot tell # parallel calls from broken retry links. if len(unlinked) > 1 and not all(s.discarded for s in unlinked): raise TokenAccountingInvariantError( f"ambiguous sibling chat spans under parent={parent!r}: " f"{[s.span_id for s in unlinked]} have no SpanLink; " f"cannot distinguish parallel calls from unlinked retries" ) result = FoldResult() for s in chat_spans: if require_dedupe_key: if not s.request_hash or not s.model or not s.operation_name: raise TokenAccountingInvariantError( f"span {s.span_id!r} lacks a complete dedupe key " f"(model={s.model!r}, request_hash={s.request_hash!r})" ) key = (s.parent_span_id or "", s.model, s.request_hash) if key in result.seen_keys: result.deduped += 1 continue result.seen_keys.add(key) result.consumed_input += s.input_tokens result.consumed_output += s.output_tokens if s.discarded: result.discarded += 1 continue result.billed_input += s.input_tokens result.billed_output += s.output_tokens return result def assert_within_budget( spans: Iterable[GenAIChatSpan], *, billed_budget_input: int, mode: str, ) -> FoldResult: """ Enforce a token budget in authoritative mode. Raises if the span set is ambiguous (propagated from fold) or if the billed total exceeds budget. """ if mode not in ("billed", "consumed"): raise TokenAccountingInvariantError(f"unknown accounting mode {mode!r}") result = fold_authoritative_tokens(spans, require_dedupe_key=True) used = ( result.billed_input + result.billed_output if mode == "billed" else result.consumed_input + result.consumed_output ) if used > billed_budget_input: raise TokenAccountingInvariantError( f"token budget exceeded in {mode} mode: used={used} " f"budget={billed_budget_input} " f"(deduped={result.deduped}, discarded={result.discarded})" ) return result ```