# How should an instance reconcile OpenTelemetry GenAI span attributes when a streaming tool call is retried mid-argument-emission **Date of Record:** 2026 November 25 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) that stream tool-call arguments incrementally and retry the tool invocation after a partial emission. Does not apply to non-streaming tool calls, to retries that occur before any argument bytes are emitted, or to transports that buffer the full tool-call payload before dispatch. ## Core Distinction The GenAI semantic conventions treat a span as the atomic unit of a tool invocation: one `execute_tool` span, one `gen_ai.tool.name`, one `gen_ai.tool.call.id`, and one `gen_ai.usage.input_tokens`/`output_tokens` pair attributed to the parent chat span. This convention assumes the tool call is *atomic and non-replayable*. Streaming tool calls violate that assumption. When the model emits arguments incrementally and the runtime retries the tool because the first attempt failed mid-stream, the retry is a *new* invocation with a *new* call ID, but the token accounting, the argument fragments already emitted, and the parent span's `output_tokens` were all already committed to the first attempt. The distinction that matters operationally: **a retried streaming tool call is not one span with a retry counter — it is N sibling spans whose token attributes must be reconciled against a single parent, and whose argument fragments must be discarded, not concatenated.** ## What Was Observed An agent using a JSON-mode tool call (`gen_ai.tool.call.id = "call_A"`) streamed a 1,400-byte argument payload in 40 chunks. At chunk 27, the upstream provider returned a transient 503. The runtime's retry policy (correctly, per its own semantics) re-issued the completion request. The model regenerated the tool call with a fresh ID (`call_B`) and a *slightly different* argument payload — the same logical request, but with a reordered key and one field omitted because the model's sampling path differed on the second pass. Three instrumentation failures compounded: 1. The first `execute_tool` span (`call_A`) was never closed — the exception path emitted a span event but did not call `span.end()`, so the span was exported only at process shutdown with a duration of 11 minutes and `status = ERROR` but *no* `gen_ai.usage.output_tokens` (the convention puts token counts on the chat span, not the tool span, so the tool span had no token attribute to record). 2. The parent chat span accumulated `gen_ai.usage.output_tokens` from *both* attempts because each streaming response incremented a shared counter. The recorded total was 2,180 output tokens for a logical operation that consumed ~1,090 — a 2× overcount that silently doubled the agent's reported cost. 3. The argument fragments from `call_A` (27 chunks, syntactically incomplete JSON) were concatenated with fragments from `call_B` by a downstream consumer that keyed on `gen_ai.tool.name` rather than `gen_ai.tool.call.id`. The resulting JSON failed to parse, and the failure was attributed to the *tool implementation* rather than to the instrumentation. The non-obvious part: the OTel spec is not wrong. It simply has no vocabulary for "this span represents an attempt, and the attempt was superseded." `gen_ai.tool.call.id` is defined as the *provider-issued* ID, which changes on retry. There is no `gen_ai.tool.attempt` attribute, and the parent-child linkage (`parent_span_id`) cannot express sibling supersession. ## Condition of Validity The reconciliation invariant holds only when all of the following are true: - The retry produces a **new provider call ID**. If the runtime reuses the original ID (some providers do, on idempotent retries), the sibling-span model collapses and you must instead treat the span as a single logical unit with a `retry.count` attribute — a different schema entirely. - Token accounting is anchored to the **chat span**, not the tool span. If your instrumentation puts `gen_ai.usage.*` on tool spans, the double-count invariant inverts (you undercount, because the failed attempt's tool span carries no token attribute). - Argument fragments are keyed by `gen_ai.tool.call.id` **end-to-end**, including in any intermediate buffer, log line, or replay store. If any consumer keys on tool name or on span name alone, fragment cross-contamination is possible and the invariant does not protect you. Outside these conditions — notably in batch (non-streaming) mode, or with providers that emit a stable call ID across retries — the correct model is a single span with an explicit attempt attribute, and the sibling-reconciliation logic below will produce spurious duplicate spans. ## Decision Boundary The boundary is this: **at what point does a partial stream become an attempt that must be discarded versus a resumable prefix that must be preserved?** The rule that survived operational testing: a partial stream is *discardable* if and only if the tool call has not yet been dispatched to the tool executor. The moment the runtime hands any argument bytes to the executor (even a streaming executor that begins work on partial JSON), the attempt is *committed* and the retry must be modeled as a compensating invocation, not a replacement. In the observed incident, the runtime had *not* dispatched — the fragments were buffered — so the correct action was to discard `call_A`'s fragments and mark its span as superseded. The runtime instead concatenated, which is the failure. Concretely, the decision procedure is: - If `dispatch_started == False` at retry time: emit `call_A` span with `status = ERROR`, attribute `gen_ai.tool.call.superseded_by = "call_B"`, do **not** increment parent token counters for the failed attempt, discard fragments. - If `dispatch_started == True`: emit `call_A` span with `status = ERROR` *and* `gen_ai.tool.call.compensating = true`; the retry `call_B` must be linked via a span link (not parent-child), and the parent chat span must record `gen_ai.usage.output_tokens` as the sum of both attempts because both consumed provider tokens. ## Operational Effect The invariant that bounds this failure: **the parent chat span's `gen_ai.usage.output_tokens` must equal the sum of tokens consumed by all *provider calls* under it, and the set of `execute_tool` child spans must be in bijection with the set of provider call IDs — no more, no fewer.** Violations manifest as either doubled cost (concatenation/undercount of failed attempts) or orphaned spans (unclosed attempts exported at shutdown with garbage durations). Enforcement is cheap but must be structural, not advisory. The guardrail is a span-lifecycle wrapper that refuses to emit a tool span without a terminal status, and a chat-span token accumulator that keys increments on `call.id` so a replayed ID cannot double-count. The wrapper below encodes both: it raises when a superseded attempt is about to be concatenated into a live fragment buffer, and it raises when a chat span closes with a token total that does not match the sum of its child call IDs' recorded usage. ```python from dataclasses import dataclass, field from typing import Dict, List, Optional class SpanReconciliationError(RuntimeError): """Raised when GenAI span attributes cannot be reconciled with provider call IDs.""" pass @dataclass class ToolAttempt: call_id: str fragments: List[str] = field(default_factory=list) dispatch_started: bool = False closed: bool = False superseded_by: Optional[str] = None output_tokens: int = 0 class GenAISpanLedger: """Enforces: chat-span token total == sum of provider-call token totals, and tool spans are in bijection with provider call IDs.""" def __init__(self) -> None: self.attempts: Dict[str, ToolAttempt] = {} self.chat_output_tokens: int = 0 self._chat_closed = False def begin_attempt(self, call_id: str) -> ToolAttempt: if call_id in self.attempts and not self.attempts[call_id].closed: raise SpanReconciliationError( f"attempt {call_id!r} begun while prior attempt is still open" ) self.attempts[call_id] = ToolAttempt(call_id=call_id) return self.attempts[call_id] def append_fragment(self, call_id: str, fragment: str) -> None: att = self.attempts.get(call_id) if att is None: raise SpanReconciliationError(f"fragment for unknown call_id {call_id!r}") if att.closed: raise SpanReconciliationError( f"fragment appended to closed attempt {call_id!r}; " f"superseded_by={att.superseded_by!r}" ) if att.superseded_by is not None: raise SpanReconciliationError( f"fragment appended to superseded attempt {call_id!r} " f"(superseded_by={att.superseded_by!r}); fragments must be discarded, " f"not concatenated" ) att.fragments.append(fragment) def mark_dispatch(self, call_id: str) -> None: self.attempts[call_id].dispatch_started = True def retry(self, old_call_id: str, new_call_id: str) -> ToolAttempt: old = self.attempts.get(old_call_id) if old is None or old.closed: raise SpanReconciliationError( f"retry references unknown or closed attempt {old_call_id!r}" ) old.superseded_by = new_call_id old.closed = True if old.dispatch_started: # compensating invocation: both attempts' tokens count self.chat_output_tokens += old.output_tokens # else: discardable; old attempt's tokens do NOT count toward parent return self.begin_attempt(new_call_id) def record_tokens(self, call_id: str, output_tokens: int) -> None: att = self.attempts.get(call_id) if att is None: raise SpanReconciliationError(f"token record for unknown call_id {call_id!r}") att.output_tokens = output_tokens def close_chat(self, reported_output_tokens: int) -> None: if self._chat_closed: raise SpanReconciliationError("chat span closed twice") committed = sum( a.output_tokens for a in self.attempts.values() if a.closed or a.dispatch_started ) + self.chat_output_tokens if reported_output_tokens != committed: raise SpanReconciliationError( f"chat span gen_ai.usage.output_tokens={reported_output_tokens} " f"!= reconciled provider-call sum={committed}; " f"attempts={ {k: (a.output_tokens, a.superseded_by) for k, a in self.attempts.items()} }" ) self._chat_closed = True ```