# Where must an instance reconcile OpenTelemetry GenAI tool-call spans when token accounting diverges from the model's own usage report **Date of Record:** 2026 November 26 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.*` attributes) for tool calls and token usage, where the span's recorded token counts are derived from a provider response that may be streamed, cached, or split across retries. Does not apply to batch offline eval pipelines or to providers that return a single atomic usage object with no streaming or retry surface. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of the span that represents a model invocation. The convention is silent on *when* those attributes are set relative to the span's lifecycle, and it is silent on how to reconcile a span that was created, partially populated, and then re-driven by a retry or a stream continuation. This creates a distinction the convention does not draw: the difference between **an invocation span** (one span per logical model call) and **an attempt span** (one span per HTTP round-trip or stream segment). When an agent retries a tool call after a 429 or a truncated stream, a naive implementation either (a) mutates the original span's token attributes to the *last* attempt's usage, silently discarding earlier consumed tokens, or (b) emits a fresh span per attempt and lets the backend sum them, double-counting prompt tokens that were re-sent. Neither matches the model's own `usage` report, which is authoritative for billing and for the agent's internal token-budget accounting. The boundary is this: **the GenAI span is the only artifact that both the observability backend and the agent's budget governor read, and the two readers require different reconciliation semantics.** The backend wants per-attempt truth for latency attribution; the budget governor wants per-invocation truth for exhaustion. A single span cannot satisfy both without an explicit attempt/invocation split, and the convention does not mandate one. ## What Was Observed A tool-calling agent issued a `gen_ai.tool.call` for a search tool. The provider returned HTTP 200 with a streamed body; at token 1,847 of a 2,000-token cap the stream stalled and the client aborted at its 30s read timeout. The agent's retry wrapper re-issued the identical request (same `gen_ai.request.model`, same messages). The second attempt completed and reported `usage: {input_tokens: 1,912, output_tokens: 340}`. The instrumentation did the following, in order: 1. On attempt 1, created span `S1`, set `gen_ai.operation.name = "chat"`, `gen_ai.request.model`, and began streaming. No usage attributes were set because the stream never delivered a terminal usage chunk. 2. On abort, `S1` was ended with `status = ERROR` and **no** `gen_ai.usage.*` attributes. The 1,847 output tokens already billed by the provider were invisible to telemetry. 3. On attempt 2, created span `S2`, completed, and set `gen_ai.usage.input_tokens = 1912`, `gen_ai.usage.output_tokens = 340`. The backend's token dashboard showed 2,252 tokens for the invocation. The provider's billing report showed 1,847 (attempt 1, billed on abort) + 2,252 (attempt 2) = 4,099 tokens. The agent's budget governor, which read span attributes, decremented its remaining context budget by 2,252 and believed it had 1,748 tokens of headroom. It did not. The next call in the same task overflowed the provider's per-request cap and hard-failed with a 400, terminating the task. The failure was not the abort. The failure was that **the aborted attempt's partial usage was structurally unrepresentable in the span model the agent had adopted**, because the convention's usage attributes are defined on a span that the implementation chose to create only after a successful terminal chunk. ## Condition of Validity The invariant holds only under these conditions, and fails outside them: 1. **The provider bills on abort.** If the provider discards partial output on client abort and does not bill it, attempt-1 usage is genuinely zero and the naive reconciliation is correct. This must be verified per provider and per endpoint; it is not a property of the GenAI convention. 2. **Retries are byte-identical or semantically additive.** If the retry mutates the prompt (e.g., appends a "continue from here" instruction), the input-token counts are not comparable and summing is meaningless; the invocation-level total must be computed by the agent, not derived from span attributes. 3. **The budget governor and the backend read the same span set.** If the governor reads spans and the backend reads a separate billing export, divergence is expected and the governor must be reconciled against the export, not the spans. 4. **Streaming is in use.** For non-streaming calls, the usage object arrives atomically with the response and the attempt/invocation distinction collapses. The failure requires a stream that can terminate without a terminal usage chunk. Outside condition 1 (provider does not bill on abort) or condition 4 (non-streaming), the reconciliation described below is unnecessary overhead. ## Decision Boundary The agent must decide, per span, whether it is an **invocation span** (carries the reconciled total, is what the governor reads) or an **attempt span** (carries per-attempt truth, is what latency and error attribution read). The rule: - Emit one attempt span per round-trip. On a successful terminal chunk, set `gen_ai.usage.*` from the provider's usage object. On abort or error, set `gen_ai.usage.*` to the **best available estimate** — the count of tokens the client observed in the stream before abort — and mark the span with a custom attribute `gen_ai.usage.estimated = true`. The convention does not define this attribute; it is an extension, and it must be namespaced to avoid colliding with future convention additions. - Emit one invocation span as the parent. Its `gen_ai.usage.input_tokens` is the **sum over attempts of input tokens actually sent**, and its `gen_ai.usage.output_tokens` is the **sum over attempts of output tokens actually billed or estimated**. This is the number the budget governor reads. - The governor must read the invocation span, never the attempt spans. The backend's latency dashboards must read attempt spans, never the invocation span's duration (which is wall-clock across retries and is not a latency signal). The boundary condition that triggers the failure is precisely: **a stream terminates without a terminal usage chunk, and the agent's instrumentation creates the span only on the happy path.** The guardrail is to create the attempt span *before* the first byte is read and to populate usage incrementally, so that an abort leaves a span with partial usage rather than no span. ## Operational Effect Without the split, the agent's budget governor under-counts by the exact number of tokens consumed in aborted attempts. In the observed case that was 1,847 tokens — 82% of the per-request cap — which is enough to convert a recoverable retry into a task-terminating overflow. The error compounds: each subsequent task in the same session inherits the inflated headroom estimate, and the failure surfaces several calls later, far from the aborted attempt that caused it. This is the classic stale-state-drift pattern, but here the stale state is not in the agent's memory — it is in the telemetry the agent uses to govern itself. The correction is not to trust the provider's usage object more; it is to recognize that the usage object is per-attempt and the governor needs per-invocation, and that the GenAI convention's span model does not encode this distinction. The agent must impose it. The following guard enforces the invariant at span-close time: ```python import time from dataclasses import dataclass, field from typing import Optional class TokenAccountingDivergence(RuntimeError): """Raised when an invocation span's reconciled usage does not match the sum of its attempt spans.""" pass @dataclass class AttemptSpan: attempt_id: str input_tokens: int = 0 output_tokens: int = 0 estimated: bool = False ended_clean: bool = False @dataclass class InvocationSpan: invocation_id: str attempts: list = field(default_factory=list) aborted_billed_tokens: int = 0 def close_and_reconcile(self, provider_reported_total: Optional[int]) -> None: # Sum attempt truth, including estimated (aborted) usage. summed_input = sum(a.input_tokens for a in self.attempts) summed_output = sum(a.output_tokens for a in self.attempts) summed_total = summed_input + summed_output # Any attempt that ended without a terminal usage chunk contributes # estimated tokens that the provider may still bill. Those must be # carried into the invocation total, not dropped. estimated_total = sum( a.input_tokens + a.output_tokens for a in self.attempts if a.estimated ) if estimated_total > 0 and provider_reported_total is None: # No provider reconciliation available: trust the estimate, but # mark the invocation so the governor applies a safety margin. self.reconciled_total = summed_total self.reconciled_estimated = True elif provider_reported_total is not None: # Provider reports total billed across all attempts. If our sum # diverges by more than the estimated portion, the instrumentation # is missing an attempt span and the governor cannot be trusted. if abs(provider_reported_total - summed_total) > estimated_total: raise TokenAccountingDivergence( f"invocation {self.invocation_id}: span sum {summed_total} " f"diverges from provider total {provider_reported_total} " f"beyond estimated portion {estimated_total}" ) self.reconciled_total = provider_reported_total self.reconciled_estimated = estimated_total > 0 else: self.reconciled_total = summed_total self.reconciled_estimated = False if self.reconciled_estimated: # Governor must not treat an estimated total as authoritative # headroom; apply the documented safety margin before continuing. self.governor_headroom = max(0, self.reconciled_total - self.aborted_billed_tokens) else: self.governor_headroom = self.reconciled_total ``` The invariant this enforces: **the invocation span's token total is the sum of its attempt spans' totals, and any attempt that ended without a terminal usage chunk is represented as an attempt span with `estimated = true` rather than omitted.** The `TokenAccountingDivergence` raise is the boundary alarm — it fires exactly when the instrumentation has lost an attempt, which is the condition that produced the 1,847-token blind spot. An agent that treats this exception as a retryable telemetry warning rather than a budget-governor halt will re-enter the same failure on the next task.