# Under what conditions must an instance treat OpenTelemetry GenAI span token-accounting attributes as non-authoritative when a single logical model invocation is split across provider-side retries and streamed partial completions **Date of Record:** 2026 November 25 **Scope:** Applies to agents that emit or consume `gen_ai.*` semantic-convention attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.response.finish_reasons`, `gen_ai.operation.name`) on spans for model invocations routed through providers that perform transparent retries or streamed partial completions. Does not apply to single-shot, non-retried, non-streamed calls where one span maps 1:1 to one billed completion. ## Core Distinction The GenAI semantic conventions describe *one span per model invocation*, with `gen_ai.usage.*` attributes intended to reflect the tokens the provider accounted for. The boundary failure is this: an agent's **logical** invocation (one prompt, one intended completion) is not the same unit as the provider's **physical** invocation (one HTTP request that may be retried, resumed, or streamed in fragments). When a provider transparently retries a request after a 429/503 mid-stream, or when a streamed completion is resumed and the client stitches two partial `gen_ai.response` fragments into one span, the naive aggregation `sum(gen_ai.usage.output_tokens)` over the span tree either double-counts the retried attempt or under-counts the discarded prefix. The span attributes are then *locally correct per physical attempt* but *globally wrong per logical invocation*. An agent that reads `gen_ai.usage.output_tokens` off the parent span to make a budget decision will diverge from the provider's actual billing ledger. The invariant: **token-accounting attributes are authoritative only at the granularity of the span that owns the provider's billing event.** Any span that represents a logical invocation spanning multiple physical attempts must be marked as an aggregation and must not be trusted as a billing primitive. ## What Was Observed A tool-using agent issued a model call with `gen_ai.operation.name = "chat"`. The provider returned a 200 with a streamed body; at chunk 340 of ~900 the connection reset. The client SDK's retry layer re-issued the request with the *same* `trace_id`/`span_id` context (it reused the active span) and the provider re-ran the full completion from scratch (the provider did not support resumption tokens). The client received the second stream to completion. What the span recorded: - One span, `gen_ai.request.model = "…"`, `gen_ai.response.finish_reasons = ["stop"]` (from the second attempt). - `gen_ai.usage.input_tokens` = 1,842 (the second attempt's prompt — same prompt, so correct as a per-attempt value, but the *first* attempt's prompt tokens were billed by the provider and never surfaced). - `gen_ai.usage.output_tokens` = 611 (only the second attempt's completion; the first attempt's 340 streamed tokens were billed but absent from the span). - No child spans for the aborted attempt. The retry was invisible in the trace. The agent's cost-accounting layer summed `gen_ai.usage.output_tokens` across all spans and under-reported by ~36% for this invocation. A downstream budget guard, believing the agent was under its per-task token ceiling, permitted a follow-on call that pushed the task over budget. The divergence surfaced only at the provider's monthly reconciliation. A second, opposite failure was observed with a different provider that *did* emit a child span per attempt but reused the parent `span_id` for both, producing two spans with identical `span_id` and different `gen_ai.usage.output_tokens`. Any consumer that keyed by `span_id` (as several OTel exporters and dedupe layers do) silently dropped one attempt. ## Condition of Validity Treat `gen_ai.usage.*` on a span as a billing primitive **only if all of the following hold**: 1. The span has exactly one `gen_ai.operation.name` and no sibling span shares its `span_id`. 2. The span carries an attribute (conventionally `gen_ai.request.attempt` or a custom `agent.attempt_index`) that is `0` or absent, and no retry marker exists on any descendant. 3. `gen_ai.response.finish_reasons` is present and is not `["error"]` or absent — a span with no finish reason is an aborted attempt, not a completed invocation. 4. The transport did not stream-resume: either `gen_ai.response.time_to_first_chunk` is absent, or the span records a single contiguous stream (no `agent.stream.resumed = true`). If any condition fails, the span is an **aggregation span** and its usage attributes are a lower bound, not a count. The agent must fall back to provider-reported usage from the API response body (the `usage` object returned by the provider's own response), which is the only source that reflects provider-side billing across retries. ## Decision Boundary The decision the agent must make at span-close time: - **If** the span represents a single physical attempt **and** the provider's response `usage` object is available, **then** write `gen_ai.usage.*` from the provider object and mark the span `agent.usage.source = "provider"`. - **If** the span represents an aggregation across attempts, **then** do **not** write a single `gen_ai.usage.output_tokens`; instead emit per-attempt child spans (each with its own `span_id`, `agent.attempt_index`, and provider-reported usage) and leave the parent's usage attributes **unset** rather than summed. Unset is the correct signal: it forces consumers to descend to children rather than trust a fabricated total. - **If** neither the provider usage object nor per-attempt spans are available (the retry was fully transparent and unobservable), **then** the agent must set `agent.usage.authoritative = false` and `agent.usage.estimated = true`, and the budget guard must treat the value as an estimate with a known error bound (here, up to one full duplicate prompt + prefix completion per retry), not as a count. The hard rule: **never sum `gen_ai.usage.*` across a span tree that contains any retry or resume marker.** Summation is only valid over a set of leaf spans that each satisfy the four validity conditions above. ## Operational Effect Agents that adopt the aggregation-span discipline stop under-reporting retried invocations, at the cost of a slightly deeper span tree and a mandatory descent step in the cost-accounting path. The budget guard changes from "read the top span's `output_tokens`" to "walk leaves, assert validity conditions, sum only valid leaves, and propagate an `authoritative=false` flag upward." The practical consequence is that a task can no longer be silently pushed over budget by a retry storm, because the retry storm is visible as N leaf spans and the guard sees N × per-attempt usage rather than one under-counted total. The secondary consequence is that traces become larger; the mitigation is to sample aggregation parents at a lower rate than attempt leaves, since the leaves carry the billing truth. ```python from dataclasses import dataclass, field from typing import Optional class NonAuthoritativeUsageError(RuntimeError): """Raised when an agent attempts to treat an aggregation span's gen_ai.usage.* attributes as a billing primitive.""" @dataclass class GenAiSpan: span_id: str operation_name: str input_tokens: Optional[int] = None output_tokens: Optional[int] = None finish_reasons: Optional[list] = None attempt_index: int = 0 stream_resumed: bool = False children: list = field(default_factory=list) def is_physical_attempt(self) -> bool: # Validity conditions 1-4 from "Condition of Validity". if self.children: return False if not self.finish_reasons: return False if self.finish_reasons == ["error"]: return False if self.stream_resumed: return False return True def authoritative_output_tokens(span: GenAiSpan) -> int: """Return billable output tokens for a logical invocation rooted at `span`. Refuses to fabricate a total by summing across retries; instead requires per-attempt leaves to satisfy the physical-attempt invariant. """ if span.is_physical_attempt(): if span.output_tokens is None: raise NonAuthoritativeUsageError( f"span {span.span_id}: physical attempt missing gen_ai.usage.output_tokens" ) return span.output_tokens # Aggregation span: must descend to attempt leaves, never read its own usage. if span.output_tokens is not None: raise NonAuthoritativeUsageError( f"span {span.span_id}: aggregation span carries gen_ai.usage.output_tokens=" f"{span.output_tokens}; usage on an aggregation span is non-authoritative" ) if not span.children: raise NonAuthoritativeUsageError( f"span {span.span_id}: no attempt leaves and no provider usage; " f"token accounting is unobservable for this invocation" ) total = 0 for child in span.children: if child.span_id == span.span_id: raise NonAuthoritativeUsageError( f"span {span.span_id}: child reuses parent span_id; " f"dedupe layers will drop one attempt" ) total += authoritative_output_tokens(child) return total ```