# Why does an instance emit duplicate GenAI token-usage spans when a tool call is retried after a streaming partial failure **Date of Record:** 2026 November 28 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) that emit per-tool-call and per-inference spans while executing streaming model calls with retry logic. Does not apply to non-streaming synchronous completion paths, nor to providers that emit a single terminal usage record per request. ## Core Distinction The failure is not "the retry double-counts tokens." The retry is correct. The failure is that the *span lifecycle* and the *token accounting record* are decoupled across the retry boundary: a streaming inference span is opened once, the upstream stream fails mid-flight after emitting a partial `usage` chunk (or after the provider bills prompt tokens but no completion), the agent retries the tool call under the *same* logical operation, and the instrumentation emits a *second* span carrying the same `gen_ai.response.id` correlation key but a fresh `gen_ai.usage.input_tokens` count. Downstream aggregation sums both. The invariant that must hold is: **for a given `(trace_id, gen_ai.operation.name, gen_ai.response.id)` tuple, exactly one span may carry terminal usage attributes, and that span's counts must reflect the provider's billed total across all attempts.** The distinction matters because the obvious fix—deduplicating on `gen_ai.response.id`—is wrong. On retry, the provider issues a *new* response id. The duplicate is not a duplicate id; it is a duplicate *logical operation* that the conventions do not have a primitive to express. ## What Was Observed Trace from a tool-calling agent (model: a streaming chat completion endpoint, tool `search_index`). Timeline: 1. `t=0ms` — Span `chat` opened, `gen_ai.operation.name=chat`, `gen_ai.request.model=...`, no response id yet. 2. `t=340ms` — First stream chunk with `delta.content`. Agent begins buffering tool-call arguments. 3. `t=1180ms` — Stream emits a chunk containing `usage: {input_tokens: 2048, output_tokens: 0}` (some providers emit cumulative usage early). Agent records it into the span. 4. `t=1210ms` — Stream aborts with `upstream reset` after 40 tokens of a 900-token tool-call argument. No `finish_reason`. 5. `t=1215ms` — Agent's retry policy (max 3, backoff 200ms) re-invokes the same logical operation. **A new span is opened** because the instrumentation wraps the SDK call, not the logical operation. New `gen_ai.response.id`. New `usage: {input_tokens: 2048, output_tokens: 900}` on completion. 6. `t=3400ms` — Second attempt completes. Tool executes. Parent span closes. Aggregated `sum(gen_ai.usage.input_tokens)` for the trace = 4096. Provider billed 2048 (the first attempt's prompt was cached/billed once; the abort did not re-bill, but the second attempt did). The agent's cost dashboard reports 2x actual. Worse: the *first* span has `output_tokens: 0` and no `finish_reason`, so a naive consumer treats it as a completed zero-output inference and excludes it from latency percentiles—masking the 1.2s abort entirely. A second, subtler observation: the aborted span's `gen_ai.response.finish_reasons` attribute is *absent*, not set to `["error"]`. Per the conventions, `finish_reasons` is only populated on successful termination. Consumers that filter on `finish_reasons == ["stop"]` silently drop the aborted attempt from the retry count, so the retry *rate* metric underreports by exactly the abort rate. ## Condition of Validity This failure mode is valid (and the guardrail below is required) when *all* of the following hold: - The inference is **streaming** and usage is emitted **incrementally** (cumulative or per-chunk), not only on a terminal chunk. - The agent has **retry-on-stream-error** semantics that re-invoke the SDK call rather than resuming the stream. - Instrumentation wraps the **SDK call** (per-attempt) rather than the **logical operation** (per-intent). This is the default for auto-instrumentation libraries. - Downstream aggregation sums usage attributes **without** a per-operation dedup key, because the conventions provide none. If the agent uses a **resume-capable transport** (stream continuation with a cursor), the retry does not open a new span and the failure does not occur. If usage is emitted only on the terminal chunk, the aborted attempt carries no usage and the sum is correct—but the abort is still invisible in `finish_reasons`. The failure is *specifically* the intersection of incremental usage and per-attempt span wrapping. ## Decision Boundary The boundary is: **does the retry represent a new billable operation or a continuation of one?** The conventions have no attribute to express "this span is attempt 2 of logical operation X." The implementer must choose one of two disciplines: - **Attempt-scoped spans (convention-literal):** emit one span per attempt, set `gen_ai.response.finish_reasons=["error"]` on aborted attempts (do not leave it absent), and add a *non-standard* attribute `gen_ai.operation.retry_of=` linking the retry to its predecessor. Downstream must aggregate by following retry chains, not by summing. - **Operation-scoped spans (pragmatic):** open the span once per logical operation, record usage on the *terminal* attempt only, and attach `gen_ai.usage.retry_count` and `gen_ai.usage.aborted_attempts` as custom attributes. This preserves the sum invariant at the cost of per-attempt latency visibility. The decision boundary is crossed the moment an aborted attempt emits *any* usage attribute. Once it does, the sum invariant is broken and no downstream consumer can recover the correct total without a retry-chain join. The guardrail is therefore: **an aborted attempt must never emit terminal usage attributes; it must emit `finish_reasons=["error"]` and a retry-link, and usage accrues only on the attempt that terminates the logical operation.** ## Operational Effect Without the guardrail, three effects compound: 1. **Cost overcount** proportional to retry rate × mean prompt size. For a 2048-token prompt and 15% retry rate, reported cost is ~15% high—enough to misroute budget alerts. 2. **Latency undercount**: aborted spans with `output_tokens: 0` are filtered from p99 by consumers that require non-zero output, hiding the tail that the retry policy exists to handle. 3. **Retry-rate blindness**: absent `finish_reasons` on aborted spans means retry-rate metrics computed from `finish_reasons` underreport by the abort rate, so the SLO that should trigger a backoff-policy review never fires. The invariant to enforce at emission time: a span that does not carry a terminal `finish_reasons` value of `stop`/`length`/`tool_calls` must not carry `gen_ai.usage.*` terminal counts. Emit usage only on terminal spans; emit aborts as error spans with explicit `finish_reasons=["error"]` and a retry link. ```python from dataclasses import dataclass, field from typing import Optional TERMINAL_FINISH_REASONS = {"stop", "length", "tool_calls", "content_filter"} class GenAIUsageInvariantError(RuntimeError): """Raised when a span violates the terminal-usage / finish-reason invariant.""" pass @dataclass class GenAISpan: operation: str attempt: int response_id: Optional[str] = None finish_reasons: list[str] = field(default_factory=list) input_tokens: Optional[int] = None output_tokens: Optional[int] = None retry_of: Optional[str] = None aborted: bool = False def finalize_span(span: GenAISpan) -> GenAISpan: """Enforce: terminal usage only on terminal spans; aborts carry error + retry link.""" is_terminal = bool(span.finish_reasons) and set(span.finish_reasons).issubset(TERMINAL_FINISH_REASONS) if span.aborted: if span.input_tokens is not None or span.output_tokens is not None: raise GenAIUsageInvariantError( f"aborted attempt {span.attempt} of {span.operation} emitted usage " f"(in={span.input_tokens}, out={span.output_tokens}); " f"usage must accrue only on the terminal attempt" ) if span.finish_reasons != ["error"]: raise GenAIUsageInvariantError( f"aborted attempt {span.attempt} of {span.operation} must set " f"finish_reasons=['error'], got {span.finish_reasons!r}" ) if span.attempt > 1 and span.retry_of is None: raise GenAIUsageInvariantError( f"aborted attempt {span.attempt} of {span.operation} missing retry_of link; " f"downstream cannot join the retry chain" ) return span if is_terminal: if span.input_tokens is None or span.output_tokens is None: raise GenAIUsageInvariantError( f"terminal span for {span.operation} (attempt {span.attempt}) " f"missing usage attributes" ) return span # Non-terminal, non-aborted: mid-stream span must not carry terminal counts. if span.input_tokens is not None or span.output_tokens is not None: raise GenAIUsageInvariantError( f"non-terminal span for {span.operation} (attempt {span.attempt}) " f"carries usage but no terminal finish_reason" ) return span def record_attempt(span: GenAISpan, stream_error: bool) -> GenAISpan: if stream_error: span.aborted = True span.finish_reasons = ["error"] span.input_tokens = None span.output_tokens = None return finalize_span(span) ```