# Which invariants prevent OTel GenAI token-accounting drift from silently corrupting agent turn-level cost attribution across retries and streaming partials **Date of Record:** 2026 November 23 **Scope:** Applies to agents that emit OpenTelemetry GenAI semantic-convention metrics (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.client.operation.duration`, tool-call spans) and reconcile them into per-turn cost ledgers. Does not apply to single-shot, non-retried, non-streamed inference where exactly one span per request is guaranteed. ## Core Distinction There are two ways an agent's cost ledger can be wrong, and they are not the same failure. The first is *missing* accounting: a span never gets emitted, and the turn is under-billed by a known, bounded amount. The second—the one that matters here—is *double-counted or non-idempotent* accounting: the same tokens are attributed to a turn more than once, or to the wrong turn, because the metrics pipeline treats retries, streaming partials, and mid-turn failovers as independent billable events. The distinction that operators miss is between the **request** (an HTTP call to a model provider, which may be retried) and the **turn** (a logical agent step, which must be billed exactly once). OTel GenAI metrics are emitted at the request/span layer. Cost attribution is computed at the turn layer. The invariant that binds them—one turn maps to a set of spans whose token counters sum to the turn's true cost, exactly once—is not enforced anywhere in the SDK, the exporter, or the collector by default. It must be reconstructed by the agent runtime, and it fails in a specific, reproducible way. ## What Was Observed A tool-using agent running a 6-step plan on a provider with a 4%-rate transient 529 (overloaded) response exhibited the following. Each model call was instrumented with a span carrying `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` and a `gen_ai.response.id`. The runtime retried failed calls with exponential backoff, up to 3 attempts, inside the same logical turn. On a turn where attempt 1 received a 529 *after* the provider had already begun billing (the provider counts input tokens on receipt, before rejecting), the retry emitted a second span. Both spans carried usage attributes. The turn ledger summed all spans sharing the turn ID and reported **1.97× the true input-token cost** for that turn. The provider's own billing showed 1.0×. The gap was invisible in dashboards because the sum was internally consistent—it summed what was emitted. A second, subtler variant appeared under streaming. When a stream was cut at a chunk boundary (client timeout at 30s) and resumed via a fresh request, the first stream's partial `output_tokens` (reported in a terminal `message_delta` event that arrived *after* the client had already abandoned the span) was emitted by a late-arriving span. The resumed request re-billed the full prompt. The ledger counted the abandoned partial output plus the full resumed output: output tokens were inflated by the abandoned prefix, and input tokens were double-counted for the re-sent context. A third variant: tool-call latency was recorded on the *tool span*, but the model's "thinking time" before the tool call—the tokens the model spent deciding to call the tool—landed on the *parent* inference span. When the parent span's duration was used as the tool-call latency for SLO purposes, tool latency was overstated by the model's decision latency, sometimes by 400ms per call. The metric was not wrong; it was measuring the wrong segment. ## Condition of Validity The exactly-once turn invariant holds only when all of the following are true: 1. **Retry attempts are nested, not siblings.** Every retry span must be a child of a single `turn` span (or carry a stable `turn.id` plus an `attempt` ordinal), so the ledger can deduplicate by selecting the *terminal successful attempt* rather than summing all attempts. 2. **Usage attributes are emitted only on terminal spans.** A span that ends in a retryable error must either omit usage or mark it `gen_ai.usage.retryable=true`, so the aggregator can exclude it. Providers that bill on receipt make "failed attempt = zero tokens" false; the aggregator must know the difference between "no tokens billed" and "tokens billed but attempt failed." 3. **Streaming partials are reconciled by response ID, not by span completion.** The terminal usage event for a stream must be attached to the span identified by `gen_ai.response.id`, regardless of whether the span's `end_time` precedes the event's arrival. Late-arriving usage must update the existing span, not create a new one. 4. **Tool-call latency is measured on the segment that excludes model decision time.** The tool span must start when the tool is actually invoked (post-decision), and the model's pre-tool reasoning must remain on the parent span. Mixing them makes the SLO metric measure a composite. When any of these is violated—and by default all four are—the ledger drifts. The drift is not random: it is systematically upward (double-counting) under retries, and systematically mis-segmented (latency inflation) under tool use. ## Decision Boundary The boundary is whether the agent runtime can *reconstruct* the request-to-turn mapping at aggregation time. If the runtime emits a stable `turn.id` and an `attempt` ordinal on every span, the collector can deduplicate with a `group by turn.id, max(attempt)` and sum only the terminal attempt. If it does not, the collector has no way to distinguish a legitimate multi-call turn (e.g., parallel tool calls) from a retried single call, and must either over-count (sum all) or under-count (take first). Neither is correct. The decision an operator must make: **is the cost ledger allowed to be approximate?** For per-turn attribution feeding a chargeback or a budget-enforcement gate, no—the invariant must be enforced at emission time, because the collector cannot recover information the runtime did not emit. For aggregate dashboards, approximate is acceptable, and the boundary shifts: you can tolerate 1.97× on individual turns if the aggregate over a large window converges, which it does only if retry rates are stationary. They are not stationary during provider incidents, which is exactly when cost spikes and the ledger is consulted. The second boundary is latency SLO scope. If the SLO is "time from user request to tool result," the composite (decision + tool) is correct. If the SLO is "tool execution time," the composite is wrong by the decision latency, which is unbounded (it scales with model reasoning length) and therefore cannot be corrected by a constant offset. ## Operational Effect The operational consequence is that token-accounting drift is *silent and self-consistent*. The ledger sums what was emitted; the sum is arithmetically correct; the dashboards agree with the ledger; and all three disagree with the provider invoice. The disagreement surfaces only at reconciliation—monthly, or during a budget breach—by which point the per-turn attribution that fed the budget gate has already admitted or rejected turns on wrong numbers. The guardrail is an emission-time invariant enforced by the agent runtime, not the collector: a turn-level span that owns exactly one terminal usage record, with retries nested beneath it and excluded from the sum, and streaming usage reconciled by response ID. The runtime must refuse to close a turn whose terminal usage record is missing or ambiguous, rather than emitting a span it cannot later reconcile. The following enforces that contract and raises when the invariant is violated. ```python from dataclasses import dataclass, field from typing import Optional class TurnAccountingInvariantError(RuntimeError): """Raised when a turn's terminal usage record cannot be reconciled exactly once.""" @dataclass class Attempt: attempt: int terminal: bool input_tokens: int = 0 output_tokens: int = 0 response_id: Optional[str] = None billed_on_receipt: bool = False # provider billed even though attempt failed @dataclass class TurnLedger: turn_id: str attempts: list[Attempt] = field(default_factory=list) def record(self, attempt: Attempt) -> None: self.attempts.append(attempt) def reconcile(self) -> tuple[int, int]: terminal = [a for a in self.attempts if a.terminal] if len(terminal) != 1: raise TurnAccountingInvariantError( f"turn {self.turn_id}: expected exactly 1 terminal attempt, " f"found {len(terminal)}; cannot attribute cost exactly once" ) win = terminal[0] # Failed attempts billed on receipt are real cost, but must be # attributed to the turn as 'wasted' not folded into the terminal sum. wasted_in = sum( a.input_tokens for a in self.attempts if not a.terminal and a.billed_on_receipt ) if win.response_id is None: raise TurnAccountingInvariantError( f"turn {self.turn_id}: terminal attempt missing response_id; " f"streaming partials cannot be reconciled" ) return win.input_tokens + wasted_in, win.output_tokens def attribute_turn(ledger: TurnLedger) -> dict: try: inp, out = ledger.reconcile() except TurnAccountingInvariantError: raise return {"turn_id": ledger.turn_id, "input_tokens": inp, "output_tokens": out} ```