# What happens when an instance emits OpenTelemetry GenAI spans for a retried tool call without resetting the span's token and attempt attributes **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that instrument model invocations and tool calls with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) and that retry, fall back, or re-dispatch a single logical step across multiple physical attempts. Does not cover pure tracing of non-agent HTTP services or span export/collector configuration issues. ## Core Distinction The distinction that matters here is between a **logical step** and a **physical attempt**. An agent's planner reasons in terms of logical steps: "call `search_docs`", "invoke `gpt-4o` to summarize". The GenAI semantic conventions, however, describe **physical invocations**: each `gen_ai.client.inference.operation.details` / `gen_ai.chat` span and each `execute_tool` span carries `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and a single `gen_ai.response.id` / `gen_ai.tool.call.id`. When a runtime retries a tool call inside the *same* span—reusing the span object to avoid span proliferation—it collapses N physical attempts into one logical span, and every per-attempt attribute becomes ambiguous: which attempt's tokens? which attempt's response id? which attempt's error? The span's identity no longer maps to a single model invocation, and downstream token accounting and replay verification silently corrupt. The non-obvious invariant is this: **a GenAI span must be coextensive with exactly one physical invocation.** Retries, fallbacks, and re-dispatches are *new spans*, linked by `trace`/`span` parentage or by an explicit attempt attribute, never by mutation of the existing span's usage attributes. ## What Was Observed A tool-calling agent with a `execute_tool` span per logical tool step, instrumented with `gen_ai.operation.name = "execute_tool"`, `gen_ai.tool.name`, and `gen_ai.tool.call.id`. The transport layer wrapped the call in a retry decorator (3 attempts, exponential backoff) to absorb transient 429/503s from the tool backend. On a run where the first attempt returned HTTP 503 *after* the backend had already consumed the request (partial execution), the decorator retried. The instrumentation, written naively, did this on each attempt: 1. `span.set_attribute("gen_ai.tool.call.id", new_uuid)` — overwrote the previous attempt's call id. 2. `span.set_attribute("gen_ai.usage.input_tokens", ...)` and `output_tokens` — overwrote, not accumulated. 3. `span.set_attribute("error.type", "503")` on the failed attempt; on eventual success, `span.set_status(OK)` cleared status but **did not clear `error.type`**. The resulting span reported: success status, one `tool.call.id` (the successful attempt's), `input_tokens` equal to the *last* attempt only, and a stale `error.type=503` attribute. Three separate corruptions in one span: - **Token undercount.** The failed attempt's prompt tokens (the tool-call arguments were re-sent, and the model had already produced the call) were dropped. Aggregate `gen_ai.usage.*` sums across the trace now undercount the true cost of the step by the failed attempt's consumption. - **Identity collision.** The successful attempt's `tool.call.id` was reused as the span identity, but the backend had *also* executed the failed attempt under a different call id. Any auditor replaying `tool.call.id → backend log` finds one id with a success record and an orphaned id with a partial-execution record and no span pointing to it. - **Status/attribute contradiction.** `status = OK` with `error.type = 503` present. Consumers that filter on `error.type` (dashboards, retry-budget analyzers) count this as a failed step; consumers that filter on `status` count it as success. The two populations disagree on the same span. In a second observed variant, a *model* invocation span was retried across a fallback from `gpt-4o` to `gpt-4o-mini`. The span retained `gen_ai.request.model = "gpt-4o"` from the first attempt but `gen_ai.response.model = "gpt-4o-mini"` from the second, producing a request/response model mismatch that the cost-attribution pipeline resolved to the *expensive* model's price for the *cheap* model's tokens. ## Condition of Validity The invariant "one span = one physical invocation" holds only when the following conditions are jointly true: 1. **The retry decorator sits *outside* the span-creation boundary**, i.e., each attempt opens and closes its own span. If the decorator wraps the span (span created once, retried inside), the invariant is violated by construction. 2. **Usage attributes are treated as write-once per span.** `gen_ai.usage.input_tokens` / `output_tokens` and `gen_ai.tool.call.id` / `gen_ai.response.id` must be set exactly once, on the span that owns that invocation. Accumulation across attempts belongs on a *parent* logical-step span, not on the invocation span. 3. **Status and error attributes are co-set.** If a span ever had `error.type` set, its final status must be `ERROR`; success on a later attempt is expressed by a *sibling* span with `status = OK`, not by clearing the failed span's status. 4. **Attempt linkage is explicit.** When a logical step fans out to N attempt spans, the parent carries `gen_ai.attempt.index` (or an equivalent) and the children carry parent references; otherwise the N spans are indistinguishable from N independent tool calls. The invariant does *not* require abandoning retries—it requires that retries be **span-multiplying**, not span-mutating. ## Decision Boundary The boundary is drawn at the point where the runtime decides whether to reuse or re-create the span. The decision rule: - **Reuse the span** only for attributes that are genuinely attempt-invariant: `gen_ai.system`, `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.request.model` (the *intended* model). These are properties of the logical step. - **Create a new span** for anything that is attempt-specific: `gen_ai.usage.*`, `gen_ai.response.id`, `gen_ai.tool.call.id`, `gen_ai.response.model`, `error.type`, `status`, and any latency/duration measurement. - **Ambiguous middle ground** where the boundary is empirically contested: `gen_ai.request.model` during a fallback. The convention treats it as a request property, but a fallback makes it an attempt property. The safe resolution is to put the *intended* model on the parent logical span and the *actual* model on each attempt span; putting both on one span re-creates the request/response mismatch above. If the runtime cannot afford N spans (span-budget pressure in high-retry swarms), the fallback is a single span with **explicitly indexed attempt attributes** (`gen_ai.attempt.0.input_tokens`, `gen_ai.attempt.1.input_tokens`, ...) and a parent-level `gen_ai.usage.*` that is the sum. Never overwrite; only append with an index. ## Operational Effect The downstream consequences are concrete and measurable: - **Token accounting drift.** Aggregated `gen_ai.usage.*` undercounts by the sum of failed-attempt tokens. In a retry-heavy workload (say 8% of steps retry once), the billed-vs-traced delta is ~8% of step cost, which is large enough to invalidate per-agent budget enforcement that keys off trace-derived token counts. - **Replay divergence.** Auditors that reconstruct agent behavior from spans (span → tool.call.id → backend record) find orphaned backend records with no span, and spans whose recorded call id does not match the backend's record of the *same* logical step. Replay is non-deterministic across the same trace. - **Status/error contradiction poisoning filters.** Mixed `status=OK` + `error.type` spans split dashboards into disagreeing populations; SLOs computed on `status` and error budgets computed on `error.type` diverge, and neither is wrong—the span is. - **Cost attribution to the wrong model** in fallback cases, over- or under-charging per-model cost lines. The guardrail is a span-lifecycle assertion at instrumentation time: a GenAI span may be *finished* at most once, and once finished its usage/identity/status attributes are immutable. Enforce it by making the span wrapper refuse to re-set any attribute in the `write-once` set after the first write, and by making the retry decorator construct a fresh span per attempt. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Any class GenAISpanInvariantError(RuntimeError): """Raised when a GenAI span is mutated in a way that breaks the one-span-per-physical-invocation invariant.""" # Attributes that are attempt-specific and therefore write-once per span. WRITE_ONCE_ATTRIBUTES = frozenset( { "gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens", "gen_ai.response.id", "gen_ai.response.model", "gen_ai.tool.call.id", "error.type", "status", } ) @dataclass class GenAISpan: name: str attributes: dict[str, Any] = field(default_factory=dict) _finished: bool = False def set_attribute(self, key: str, value: Any) -> None: if self._finished: raise GenAISpanInvariantError( f"span {self.name!r} is finished; refusing to set {key!r}. " "Retries must open a new span, not mutate this one." ) if key in WRITE_ONCE_ATTRIBUTES and key in self.attributes: raise GenAISpanInvariantError( f"attempt-specific attribute {key!r} already set to " f"{self.attributes[key]!r}; overwriting with {value!r} would " "collapse two physical attempts into one span." ) self.attributes[key] = value def set_status(self, status: str, error_type: str | None = None) -> None: if status == "OK" and "error.type" in self.attributes: raise GenAISpanInvariantError( f"span {self.name!r} has error.type={self.attributes['error.type']!r} " "but is being marked OK; a successful retry belongs on a sibling span." ) self.set_attribute("status", status) if error_type is not None: self.set_attribute("error.type", error_type) def finish(self) -> None: self._finished = True def retried_tool_call( logical_span: GenAISpan, tool_name: str, attempts: list[dict[str, Any]], ) -> GenAISpan: """Execute a logical tool step across N physical attempts. Each attempt gets its own span. Usage is accumulated only on the parent logical span, never by overwriting a child's attributes. """ total_in = 0 total_out = 0 successful_span: GenAISpan | None = None for index, attempt in enumerate(attempts): span = GenAISpan(name=f"execute_tool {tool_name} [attempt {index}]") span.set_attribute("gen_ai.operation.name", "execute_tool") span.set_attribute("gen_ai.tool.name", tool_name) span.set_attribute("gen_ai.attempt.index", index) if attempt.get("ok"): span.set_attribute("gen_ai.tool.call.id", attempt["call_id"]) span.set_attribute("gen_ai.usage.input_tokens", attempt["in_tokens"]) span.set_attribute("gen_ai.usage.output_tokens", attempt["out_tokens"]) span.set_status("OK") successful_span = span else: span.set_attribute("gen_ai.tool.call.id", attempt["call_id"]) span.set_attribute("gen_ai.usage.input_tokens", attempt["in_tokens"]) span.set_attribute("gen_ai.usage.output_tokens", attempt["out_tokens"]) span.set_status("ERROR", error_type=attempt.get("error", "unknown")) total_in += attempt["in_tokens"] total_out += attempt["out_tokens"] span.finish() if successful_span is None: raise GenAISpanInvariantError( f"tool {tool_name!r} exhausted all {len(attempts)} attempts without " "success; logical span must be closed as ERROR with accumulated usage." ) # Accumulate on the parent only after children are finalized. logical_span.set_attribute("gen_ai.usage.input_tokens", total_in) logical_span.set_attribute("gen_ai.usage.output_tokens", total_out) logical_span.set_attribute("gen_ai.attempt.count", len(attempts)) return successful_span ```