# Which invariants prevent tool-call span attribute loss when an agent retries a failed tool invocation under OpenTelemetry GenAI semantics **Date of Record:** 2026 November 20 **Scope:** Applies to agents emitting OTel GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) where a single logical tool call is retried, replayed, or hedged across multiple physical attempts. Does not apply to single-shot tool calls with no retry loop, nor to pure LLM completion spans without tool execution. ## Core Distinction The GenAI semantic conventions define attributes on a **span**, but an agent's retry logic operates on a **logical call**. When a tool invocation fails and the agent retries, the naive mapping emits a *new sibling span per attempt* while the agent's internal bookkeeping treats them as *one call*. The distinction that matters: `gen_ai.usage.*_tokens` is defined as a **per-span monotonic counter of work performed**, not a per-logical-call total. An agent that sums token usage across retry spans to reconstruct "the cost of this tool call" double-counts; an agent that emits only the final attempt's span loses the tokens burned by failed attempts. Both are silent — the trace is structurally valid, spans nest correctly, and no validator fires. The non-obvious invariant: **span identity ≠ logical call identity**, and the GenAI conventions provide no first-class field to bind them. The only mechanism is `gen_ai.tool.call.id` (or the equivalent correlation attribute), which MUST be stable across retry attempts of the same logical call and MUST be unique across distinct calls. If the agent regenerates the call ID on each retry — which most retry wrappers do, because they treat each attempt as a fresh invocation — the binding is severed and downstream accounting collapses. ## What Was Observed An agent with a `retry(max=3, backoff=exponential)` wrapper around a `search_documents` tool. The tool returned HTTP 503 on attempt 1, a malformed JSON payload on attempt 2 (parse error inside the tool, surfaced as a tool-level exception), and succeeded on attempt 3. The agent's span emitter was called inside the tool wrapper, so three sibling spans were produced: - Attempt 1: `gen_ai.tool.name=search_documents`, `gen_ai.tool.call.id=call_7f3a`, status `ERROR`, `gen_ai.usage.input_tokens=412`, `output_tokens=0`. - Attempt 2: `gen_ai.tool.name=search_documents`, `gen_ai.tool.call.id=call_9b21`, status `ERROR`, `input_tokens=418`, `output_tokens=0`. - Attempt 3: `gen_ai.tool.name=search_documents`, `gen_ai.tool.call.id=call_c4e0`, status `OK`, `input_tokens=421`, `output_tokens=87`. Three observations, each a distinct failure surface: 1. **Call ID drift.** The retry wrapper constructed a fresh `call_id` per attempt (UUID generated at wrapper entry). The three spans are indistinguishable from three *separate* logical tool calls in the trace backend. Any downstream join on `call.id` to reconstruct "did this call eventually succeed?" returns three singleton groups, not one group of three. 2. **Token accounting ambiguity.** Summing `input_tokens` across the three spans yields 1251, but the logical call consumed 1251 input tokens only if the agent re-sent the full prompt on each retry (it did — the tool takes the query as input, and the retry re-serialized it). If the agent had cached the tool input, the true consumption would be 421. The trace cannot distinguish these; `gen_ai.usage.input_tokens` is defined per-span and the conventions say nothing about whether retried attempts share input. 3. **Status aggregation loss.** The parent agent span recorded `OK` (the logical call succeeded). The three child spans recorded `ERROR, ERROR, OK`. A naive error-rate metric over tool spans reports 66% failure for a call that succeeded. A naive error-rate metric over *logical calls* reports 0%. The two metrics are both "correct" and disagree by 66 points. The trace was accepted by the collector, passed schema validation, and rendered cleanly in the UI. The failure was invisible until a cost-attribution query joined tool spans to billing and produced a 3× overcount on retried calls. ## Condition of Validity The invariant `sum(gen_ai.usage.*_tokens over spans sharing gen_ai.tool.call.id) = logical call token cost` holds **only if**: - The agent emits exactly one span per physical attempt, and - `gen_ai.tool.call.id` is held constant across all attempts of the same logical call, and - The agent does **not** re-emit the input tokens as new consumption on retry when the input was cached or memoized (otherwise the sum overcounts), and - Retried attempts are not silently dropped by the span processor (e.g., a batching exporter that drops spans on shutdown mid-retry). The invariant fails the moment any of these is violated. The most common violation is the first combined with the second: retry wrappers are written generically (`for attempt in range(n): with span(f"attempt_{attempt}"): ...`) and generate the call ID inside the attempt scope rather than outside it. A second, subtler violation: **hedged requests**. An agent that fires two parallel attempts and takes the first to succeed emits two spans with `status=OK` if both eventually return. The `call.id` correlation now maps one logical call to two successful spans with overlapping token counts. The sum is correct only if the agent marks the losing hedge as `status=UNSET` or `CANCELLED` and excludes it from cost aggregation — but the GenAI conventions do not define a `CANCELLED` tool status, so the agent must invent one, and downstream consumers must know to exclude it. ## Decision Boundary The boundary is: **does the agent's retry layer own span emission, or does the tool-call layer own it?** - If the **retry layer** owns it (span created inside the retry loop), the agent MUST thread a stable `call.id` from outside the loop into each attempt, and MUST mark non-final attempts with an explicit attribute (e.g., `gen_ai.tool.retry.attempt=N`, `gen_ai.tool.retry.final=false`) so cost aggregation can choose sum-all (true consumption) vs. last-attempt (logical cost) semantics deliberately. - If the **tool-call layer** owns it (one span per logical call, retries recorded as span *events* or child spans of a single tool span), the agent MUST record each failed attempt as an event on the single span with its own token delta, because the top-level `gen_ai.usage.*_tokens` must reflect total consumption, not just the successful attempt. The wrong choice is the implicit one: retry layer owns span creation, no stable call ID, no retry attributes. This is the default of every generic retry decorator, and it is the failure mode this record documents. The guardrail: an agent MUST NOT emit a tool span without a `gen_ai.tool.call.id` that was assigned *before* entering the retry loop, and the span emitter MUST assert that no two spans with the same `call.id` both carry `status=OK` unless a hedge-exclusion attribute is present. ## Operational Effect Downstream, three things break simultaneously and silently: 1. **Cost attribution overcounts retried calls** by the ratio of attempts to successes, biased toward tools with high transient failure rates (network-bound search, rate-limited APIs). The bias is not uniform across tools, so per-tool cost comparisons are corrupted, not just scaled. 2. **Success-rate metrics undercount** because the denominator is spans, not logical calls. A tool with a 50% per-attempt failure rate and 3 retries shows ~87% span-level failure but ~12.5% logical-call failure. Dashboards built on span counts look alarming while the agent is healthy. 3. **Latency percentiles inflate** because each attempt contributes its own duration to the tool-span latency distribution, and failed attempts (timeouts, 503 backoff) are the slow tail. The p99 tool latency reflects retry backoff, not tool performance. The fix is a one-line change in the retry wrapper (hoist the call ID) plus a schema-level assertion at the emitter, but it must be applied at every tool boundary, and it must be paired with an explicit decision about whether `gen_ai.usage.*_tokens` on the span means "this attempt" or "this logical call to date." The GenAI conventions leave this open; the agent must close it, and must close it identically across every tool it invokes, or the trace becomes a mix of two incompatible accounting regimes. ```python import uuid from dataclasses import dataclass, field class ToolSpanInvariantError(RuntimeError): """Raised when a tool span violates the retry-correlation invariant.""" @dataclass class ToolAttempt: call_id: str attempt: int status: str # "OK" | "ERROR" | "CANCELLED" input_tokens: int output_tokens: int is_hedge_loser: bool = False @dataclass class LogicalToolCall: call_id: str = field(default_factory=lambda: str(uuid.uuid4())) attempts: list[ToolAttempt] = field(default_factory=list) def record(self, attempt: ToolAttempt) -> None: if attempt.call_id != self.call_id: raise ToolSpanInvariantError( f"attempt call_id {attempt.call_id!r} does not match " f"logical call_id {self.call_id!r}; retry wrapper regenerated ID" ) self.attempts.append(attempt) def validate(self) -> None: ok_attempts = [a for a in self.attempts if a.status == "OK"] non_hedge_ok = [a for a in ok_attempts if not a.is_hedge_loser] if len(non_hedge_ok) > 1: raise ToolSpanInvariantError( f"call {self.call_id!r} has {len(non_hedge_ok)} successful " f"non-hedge attempts; exactly one terminal success is required" ) if not self.attempts: raise ToolSpanInvariantError( f"call {self.call_id!r} emitted no spans; retry layer dropped them" ) def total_tokens(self) -> tuple[int, int]: """Sum across all attempts: true consumption, including failed retries.""" return ( sum(a.input_tokens for a in self.attempts if not a.is_hedge_loser), sum(a.output_tokens for a in self.attempts if not a.is_hedge_loser), ) def logical_tokens(self) -> tuple[int, int]: """Tokens of the terminal successful attempt only: logical call cost.""" terminal = [a for a in self.attempts if a.status == "OK" and not a.is_hedge_loser] if not terminal: return (0, 0) return (terminal[0].input_tokens, terminal[0].output_tokens) def emit_tool_call_span(call: LogicalToolCall) -> dict: call.validate() total_in, total_out = call.total_tokens() log_in, log_out = call.logical_tokens() if total_in < log_in or total_out < log_out: raise ToolSpanInvariantError( f"call {call.call_id!r}: total consumption ({total_in},{total_out}) " f"below logical cost ({log_in},{log_out}); impossible accounting" ) return { "gen_ai.tool.call.id": call.call_id, "gen_ai.tool.retry.attempts": len(call.attempts), "gen_ai.usage.input_tokens": total_in, "gen_ai.usage.output_tokens": total_out, "gen_ai.tool.logical.input_tokens": log_in, "gen_ai.tool.logical.output_tokens": log_out, } ```