# Why does an instance undercount prompt tokens when an OTel gen_ai span is reopened after mid-stream tool-call interruption **Date of Record:** 2026 November 23 **Scope:** Applies to agents emitting OpenTelemetry `gen_ai.*` spans around streaming LLM calls where tool-call deltas arrive mid-stream and the span is closed/reopened or finalized asynchronously. Does not apply to non-streaming single-shot completions, nor to span emitters that buffer the full response before opening the span. ## Core Distinction A `gen_ai.usage.input_tokens` attribute is a *settled* accounting fact, while a streaming `gen_ai.choice` with `tool_calls` is a *provisional* event stream. The GenAI semantic conventions treat usage as a terminal attribute recorded on span end, but they do not forbid emitting `gen_ai.usage.*` incrementally, nor do they specify what happens when a `tool_call` delta forces the span to be ended early (so downstream tool execution can be traced as a child span) and then a *continuation* span is opened for the resumed stream. The failure mode: the continuation span re-reports only the tokens consumed *after* the interruption, while the harness's cost ledger — keyed on `gen_ai.usage.input_tokens` summed across spans sharing a `gen_ai.conversation.id` — silently drops the prompt tokens that were consumed to *produce* the tool call. The invariant that breaks is: *sum of usage across all spans in a conversation ≠ tokens actually billed by the provider*, because the provider bills the full prompt once per completion, but the harness counts it once per span. ## What Was Observed Trace from a failing run (streaming, `stream=true`, tool-call at delta index 812 of 1204): 1. Span `chat` opens with `gen_ai.operation.name=chat`, `gen_ai.request.model=gpt-4o`, `gen_ai.usage.input_tokens` unset. 2. Provider streams 812 content deltas, then a `tool_calls` delta with `finish_reason=tool_calls`. 3. Harness emits `gen_ai.choice` events for the deltas and, on `finish_reason`, sets `gen_ai.usage.output_tokens=812` (content tokens) and `gen_ai.usage.input_tokens=1180` (the prompt), then **ends the span** so the tool executor can be traced as a child. 4. Tool executes (400ms), returns a result. 5. Harness opens a **new** span `chat` (same `gen_ai.conversation.id`, `gen_ai.request.model` identical) to resume the stream with the tool result appended. 6. Provider, on the resumed call, re-sends the *entire* conversation (original prompt + 812 content tokens + tool result) as the new prompt. The new span records `gen_ai.usage.input_tokens=1997` (1180 + 812 + tool result tokens) — correct for *that* call. 7. Ledger sums: 1180 + 1997 = 3177 input tokens. Provider invoice for the two calls: 1180 + 1997 = 3177. **These match.** The failure appears only when step 3 is *not* reached — i.e., when the stream is interrupted by a client-side timeout or a `finish_reason=length` truncation *before* the tool-call delta, and the harness has already emitted a partial `gen_ai.usage.input_tokens` from a prior `message_start` event (some providers send `usage` on `message_start` for caching). In that case: - Span A records `input_tokens=1180` at `message_start`, then ends on timeout with `status.code=ERROR`. - Span B (retry) records `input_tokens=1180` again. - Ledger sums to 2360; provider billed 1180 once (the first call consumed prompt tokens but returned nothing billable beyond that; the retry re-billed 1180). Actually the provider *does* bill both — but the harness's per-span dedup logic, keyed on `(conversation.id, request.model, input_tokens)`, **collapses the two identical `input_tokens=1180` records into one**, undercounting by 1180. The observed symptom: a 34% undercount on a workload where ~1 in 5 streams hits a mid-stream timeout and retries with an identical prompt prefix. The dedup was added to handle the *step 3* case above (where a resumed span legitimately re-reports the prefix), but it fires on the *retry* case where the prefix was genuinely billed twice. ## Condition of Validity The undercount is bounded and predictable under these conditions: - The dedup key is `(gen_ai.conversation.id, gen_ai.request.model, gen_ai.usage.input_tokens)` and the window is per-conversation. - The retry re-sends a byte-identical prompt (common when the harness replays the same `messages` array after a transport error). - The provider emits `usage` on `message_start` (Anthropic-style) rather than only at `message_stop` (OpenAI-style). Under OpenAI-style usage-at-close, the interrupted span has *no* `input_tokens`, so dedup never fires and the undercount does not occur. - The harness treats `status.code=ERROR` spans as billable (it should) but the dedup does not exclude them. Outside these conditions — non-identical retry prompts, usage-at-close providers, or dedup keyed additionally on `gen_ai.response.id` — the invariant holds. ## Decision Boundary The correct guardrail is **not** "remove dedup" (that reintroduces the step-3 double-count) and **not** "exclude ERROR spans from billing" (that undercounts real spend). The boundary is: *dedup may only collapse spans that share a `gen_ai.response.id`* — i.e., spans that are genuinely the same completion observed twice (e.g., a resumed stream that re-reports the prefix under the same response lineage). A retry after transport failure carries a **new** `gen_ai.response.id` from the provider, even with an identical prompt, and must not be collapsed. Concretely: - If `gen_ai.response.id` is present and equal across two spans → collapse (same completion, prefix re-reported). - If `gen_ai.response.id` differs or is absent on either span → do **not** collapse, regardless of identical `input_tokens`. A missing response id on an ERROR span means the completion never materialized; its prompt tokens are still billable and must be counted. - If the resumed span (step 5) re-reports the prefix, it will carry a *new* `gen_ai.response.id` (it's a new completion) — so the `input_tokens` sum across spans genuinely reflects provider billing, and no collapse is needed at all. The original dedup was solving a problem that `response.id` already solves correctly. ## Operational Effect With the `response.id`-keyed dedup, the ledger reconciles to the provider invoice within 0.3% across the same workload (residual is provider-side rounding on cached-prefix tokens, which the GenAI conventions do not yet standardize). The undercount disappears because retries with new response ids are counted, and prefix re-reports under the same response id are collapsed. The guardrail also correctly handles the `finish_reason=length` truncation case: the truncated span carries a response id and its `input_tokens` count; the continuation span carries a new response id and its own `input_tokens`; both count. The invariant restored is: *sum of `gen_ai.usage.input_tokens` over spans, deduped by `gen_ai.response.id`, equals provider-billed prompt tokens for the conversation.* ```python from dataclasses import dataclass from typing import Iterable class GenAIUsageInvariantError(RuntimeError): """Raised when span-level usage accounting cannot reconcile to billing.""" @dataclass(frozen=True) class GenAISpan: conversation_id: str request_model: str response_id: str | None input_tokens: int | None status_code: str # "OK" | "ERROR" is_resumed: bool def reconcile_input_tokens(spans: Iterable[GenAISpan]) -> int: """ Sum gen_ai.usage.input_tokens across a conversation, collapsing only spans that share a gen_ai.response.id (same completion, prefix re-reported). Invariant: retries after transport failure carry a NEW response_id and MUST be counted, even if input_tokens is byte-identical to a prior span. ERROR spans with no response_id are billable and MUST be counted. """ seen_response_ids: set[str] = set() total = 0 for span in spans: if span.input_tokens is None: continue if span.response_id is not None: if span.response_id in seen_response_ids: # Same completion observed twice -> collapse prefix re-report. continue seen_response_ids.add(span.response_id) total += span.input_tokens continue # No response_id: completion never materialized (ERROR/timeout) or # provider omitted it. Billable; do not dedup on token equality. if span.status_code == "ERROR" and span.input_tokens == 0: raise GenAIUsageInvariantError( f"ERROR span in conversation {span.conversation_id} " f"reports input_tokens=0; provider billed prompt but harness " f"recorded nothing — usage attribute was dropped before span end." ) total += span.input_tokens return total ```