# Why does an instance of an OpenTelemetry GenAI agent span silently under-report token usage when a tool call is retried after a partial stream flush? **Date of Record:** 2026 November 23 **Scope:** Applies to agent frameworks emitting OTel GenAI spans (`gen_ai.operation.name = "invoke_agent"` / `"execute_tool"`) where token usage is accumulated incrementally across streaming model responses and tool-call retries. Does not apply to non-streaming completions, nor to providers returning final usage only in a terminal event with no intermediate `usage` deltas. ## Core Distinction GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as **cumulative attributes of a single logical model invocation**, not per-chunk counters. The boundary failure occurs when an agent retries a tool call and the instrumentation *resets* or *double-counts* the accumulator depending on where the flush boundary landed. A partial stream that emitted usage deltas before the retry has already mutated the span's usage attributes. A naive retry handler that "starts fresh" either (a) overwrites accumulated attributes, losing tokens billed for the aborted attempt, or (b) appends the new attempt's usage on top of the aborted attempt's, inflating the span. Both produce internally consistent-looking but wrong attributes relative to the provider's billing record. The invariant violated: **sum of per-attempt usage deltas == final span usage attributes == provider-billed tokens for the logical invocation.** The boundary condition is the retry seam — the instant between the last `usage` delta of attempt *N* and the first of attempt *N+1*. ## What Was Observed In a LangGraph-style agent loop instrumented with a hand-rolled OTel exporter, tool calls to a flaky downstream service were retried up to 3 times. Traces showed `gen_ai.usage.output_tokens` values *lower* than the provider dashboard by ~15–40% on retried turns, and occasionally *higher* when the retry landed after a clean stream close. The discrepancy correlated exactly with whether the aborted attempt had emitted at least one `usage` chunk before the transport error. Two cases: 1. **Aborted mid-stream, usage already flushed.** Attempt 1 streamed a `usage` delta of 120 output tokens, then the connection reset. Retry handler constructed a fresh accumulator; attempt 2 succeeded with 80 tokens. Span reported 80. Provider billed 200. Under-report by 120. 2. **Aborted after terminal usage event, retry succeeded.** Attempt 1 delivered a terminal `usage` event (150 tokens) but the client failed to read the final `[DONE]` marker and treated it as retryable. Attempt 2 succeeded (150 tokens). Span reported 300. Provider billed 150. Over-report by 150. The failure is invisible in span-level assertions because the attribute is a well-formed integer either way. It only surfaces when reconciled against the provider's usage endpoint or a sibling `gen_ai.client.token.usage` histogram emitted per-attempt rather than per-span. ## Condition of Validity The under/over-reporting only manifests when **all** of the following hold: - The model response is streamed and the provider emits `usage` in intermediate or terminal stream events (Anthropic `message_delta`, OpenAI `stream_options.include_usage`, Gemini `usageMetadata`). - The agent framework retries at the *tool-call* or *model-invocation* layer, not at the transport layer beneath the instrumentation. - The span's usage attributes are set from an in-process accumulator rather than a single authoritative terminal event. - The retry policy does not distinguish "retryable transport error before any usage delta" from "retryable error after usage delta." If any one fails — e.g., usage is only read from the final event and the retry discards the whole attempt — the invariant holds vacuously and the bug is masked. This is why it reproduces in production but not in the happy-path integration test. ## Decision Boundary The correct rule: **usage accumulation is keyed to the logical `invoke_agent` span, and each attempt contributes a delta that is added, never assigned.** On retry, do not reset the accumulator; record the retry as a span event (`gen_ai.retry.attempt`) carrying the attempt's own delta, and add it to the span attributes. The decision boundary is whether the retry is *above* or *below* the usage-emitting layer: - Retry below instrumentation (transport-level reconnect replaying the same logical request): the provider may or may not re-bill; treat the terminal event as authoritative and *replace*, not add. - Retry above instrumentation (framework re-issues the invocation): each attempt is separately billed; *add* the deltas. Conflating these two is the root cause. The span must carry enough structure — attempt events with per-attempt usage — that a reconciler can decide which semantics applied, because the instrumentation itself often cannot tell. ## Operational Effect Downstream, this corrupts cost attribution and capacity planning: per-agent token budgets derived from these spans under-provision retry-heavy paths, and chargeback reports disagree with the provider invoice by an amount proportional to retry rate. The mitigation is to emit per-attempt usage as span events and reconcile the span total against the provider's usage API as a separate audit job; the span attribute is a convenience, not a source of truth. Alert on `abs(span_usage - provider_usage) / provider_usage > 0.01` per logical invocation. ```python class TokenAccountingInvariantError(RuntimeError): """Raised when a span's accumulated GenAI usage diverges from the sum of its per-attempt usage deltas, indicating a retry-seam double-count or reset.""" def reconcile_span_usage(span_attrs: dict, attempt_deltas: list[int]) -> int: """Validate that the span's reported output tokens equal the sum of per-attempt deltas. Returns the authoritative total on success.""" reported = int(span_attrs.get("gen_ai.usage.output_tokens", -1)) if reported < 0: raise TokenAccountingInvariantError( "span missing gen_ai.usage.output_tokens attribute" ) authoritative = sum(attempt_deltas) if reported != authoritative: raise TokenAccountingInvariantError( f"retry-seam accounting divergence: span reports {reported}, " f"attempt deltas sum to {authoritative} " f"(delta={reported - authoritative}); " f"likely accumulator reset or double-count across retry" ) return authoritative ```