# What happens when an instance emits OpenTelemetry GenAI spans across a retried tool call and the usage counters double-count **Date of Record:** 2026 November 26 **Scope:** Applies to LLM agent runtimes that instrument model invocations and tool calls with the OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) and export usage/token telemetry to a backend that aggregates by `trace_id`/`span_id`. Does not cover pure application-level metrics that never cross a retry or handoff boundary, nor provider-side billing reconciliation that bypasses OTel entirely. ## Core Distinction There are two structurally different notions of "one model call" in a GenAI-instrumented agent: 1. **The logical invocation** — the single semantic unit the agent reasons about: "I asked the model to decide the next tool call." An agent may retry this logical invocation N times due to timeouts, 429s, malformed JSON, or a failed schema validation on the tool arguments. 2. **The physical span** — the OTel span that carries `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` and `gen_ai.response.finish_reasons`. Per the GenAI conventions, a span represents *one* request/response to the model endpoint. The boundary failure lives exactly where these two collapse: **a retry loop that re-emits a new physical span for each attempt but does not change the parent `trace_id`, the agent's logical operation id, or any retry-discriminator attribute.** Downstream aggregation that sums `gen_ai.usage.*` grouped by `trace_id` (a very common dashboard query) then reports token consumption that is a multiple of reality, and — worse — the agent's own budget-enforcement logic, if it reads from the same telemetry stream, will trip its token ceiling mid-task and abort a run that was actually well within budget. This is not a metrics-export bug in the generic sense. It is a semantic-convention ambiguity: the conventions define what a span *means* but not how retries of a logical invocation relate to each other, so every runtime invents its own (usually absent) convention. ## What Was Observed A tool-using agent loop with a 3-attempt retry wrapper around each model call. The wrapper retried on `finish_reason == "length"` truncation of the tool-call JSON, on HTTP 429, and on a local schema-validation failure of the emitted tool arguments. Trace excerpt (simplified, one logical invocation that succeeded on attempt 3): ``` trace_id=7f3a... span_id=a001 name=invoke_agent gen_ai.operation.name=invoke_agent trace_id=7f3a... span_id=b101 name=chat gen_ai.operation.name=chat gen_ai.usage.input_tokens=1840 gen_ai.usage.output_tokens=512 gen_ai.response.finish_reasons=["length"] # attempt 1, truncated trace_id=7f3a... span_id=b102 name=chat gen_ai.operation.name=chat gen_ai.usage.input_tokens=1840 gen_ai.usage.output_tokens=512 gen_ai.response.finish_reasons=["length"] # attempt 2, truncated trace_id=7f3a... span_id=b103 name=chat gen_ai.operation.name=chat gen_ai.usage.input_tokens=1840 gen_ai.usage.output_tokens=387 gen_ai.response.finish_reasons=["tool_calls"] # attempt 3, success ``` Three `chat` spans, all children of the same `invoke_agent` span, all sharing `trace_id`. The dashboard query `sum(gen_ai.usage.input_tokens) by trace_id` yields **5520 input tokens** for a logical invocation whose real cost is **1840 input + 1411 output across three billed attempts** — which is correct *billing* but wrong *semantics* for the agent's own budget gate, which the runtime also fed from this aggregate. The observed failure sequence: 1. Attempt 1 truncates at `max_tokens`. The runtime emits span `b101` with usage. Retry wrapper fires. 2. Attempt 2 truncates identically (the prompt was not shortened; the retry is naive). Span `b102` emitted, usage counted again. 3. Attempt 3 succeeds. Span `b103` emitted. 4. The agent's budget monitor, which reads `sum(gen_ai.usage.input_tokens)` for the current `trace_id` on each span end, sees 5520 and crosses a 5000-token soft ceiling. 5. The runtime raises a budget-exhaustion abort *after* the tool call already succeeded but *before* the result is committed to memory. The tool side effect (a database write via the tool) is now unrecorded in the agent's episodic store. The double-count is not the deepest problem. The deepest problem is the **commit/telemetry ordering race**: telemetry emission is treated as a pre-commit signal, but the token sum it produces is inflated by retries that the runtime did not model as retries. ## Condition of Validity The inflation is *only* observable as a bug — i.e., the aggregate is only misleading — under the conjunction of these conditions: - **C1: Retry re-spans without a discriminator.** Each attempt emits an independent `chat` span with no `gen_ai.request.retry_count`, no `retry.attempt`, and no shared `gen_ai.conversation.id`-style logical-operation key. (The conventions do not standardize a retry attribute; this is the gap.) - **C2: Aggregation key is `trace_id` (or parent span).** If the backend groups by `span_id`, no inflation. The failure requires a coarser key than the retry granularity. - **C3: A consumer reads the aggregate and acts on it.** A dashboard is harmless. A budget gate, a rate limiter, an autoscaler, or a "did this trace exceed context budget" evaluator is not. - **C4: The retry is *not* reflected in a reduced prompt.** If the runtime shortens the prompt on retry (dropping truncated output, compacting history), the input-token counts differ per attempt and the sum is at least *plausibly* the true spend — but it still overstates the logical invocation's footprint for any consumer asking "how big was this decision?" If C1 is false — the runtime stamps `retry.attempt` and a stable `gen_ai.operation.id` — the aggregate can be corrected by filtering `retry.attempt == 0` for "logical cost" and summing all for "billed cost." The two questions become separable. That separability is the invariant. ## Decision Boundary The architectural decision is: **does the retry wrapper own the span, or does the model client own the span?** - If the **model client** owns the span (one span per HTTP request), retries are invisible to the span tree and the runtime *must* inject a retry discriminator at the client boundary, because the client cannot know it is being retried. - If the **retry wrapper** owns the span (one span per logical invocation, with attempt-level events or child spans), the wrapper must emit usage as the sum of attempts on the parent and per-attempt usage on children, and must tag the parent with `gen_ai.usage.retry_attempts` so consumers can distinguish logical from billed cost. The boundary is crossed the moment a consumer treats a `trace_id`-aggregated `gen_ai.usage.*` sum as *either* "logical cost" *or* "billed cost" without knowing which ownership model produced it. The conventions are silent on this, so the consumer cannot tell. A second, subtler boundary: **`gen_ai.response.finish_reasons` is per-span, not per-logical-invocation.** A consumer that asserts "this trace's finish reason was `tool_calls`" by reading the *last* span is correct only if retries are ordered and the last span is the committed one. A consumer that reads *any* span may see `["length"]` from an abandoned attempt and misclassify a successful invocation as truncated. The guardrail: never read `finish_reasons` from an arbitrary span in a retried trace; read it from the span whose `gen_ai.operation.name` matches the committed operation and whose attempt index is maximal *and* whose result was actually committed. ## Operational Effect The downstream consequences, in order of severity: 1. **False budget aborts.** Agents that gate on trace-aggregated token sums abort mid-task on retried invocations. Because retries cluster on hard problems (truncation, schema failures), the aborts correlate with exactly the tasks that most need to complete. This is a silent quality regression: the agent appears to "give up" on hard tasks. 2. **Commit/telemetry inversion.** If the budget check runs on span-end and the tool side effect commits after, the abort can strand a side effect. The invariant required: **the budget gate must read a counter that is incremented only on committed logical invocations, not on every span end.** Telemetry is an observation channel; it must not be in the critical path of commit decisions unless it is monotonic and retry-aware. 3. **Cost dashboards that overstate by the retry factor.** For a runtime with a 3-attempt cap on a workload that retries 40% of invocations, dashboards overstate input spend by up to ~2.2×. Finance reconciliation against the provider invoice then "discovers" a discrepancy that is actually a semantics bug. 4. **Evaluator contamination.** Offline evaluators that replay traces and score "context efficiency" (tokens per decision) will penalize retried-but-successful traces, biasing the eval set toward easy tasks. The guardrail set that bounds all four: - Stamp every `chat` span with `gen_ai.operation.id` (stable across retries of one logical invocation) and `retry.attempt` (0-indexed). - Emit a parent span per logical invocation carrying `gen_ai.usage.input_tokens` = sum of committed attempt, plus `gen_ai.usage.retry_attempts` and `gen_ai.usage.total_billed_input_tokens` as a separate attribute. Never overload one attribute with two meanings. - Budget gates read `total_billed_*` for hard ceilings and `input_tokens` (committed) for context-window decisions. These are different questions and must not share a counter. - `finish_reasons` on the parent is the committed attempt's reason; abandoned attempts' reasons live on child spans only. - Tool side effects commit *before* the budget gate evaluates, or the gate is advisory only. Never let an observation channel veto a committed effect. The failure is not that OTel GenAI conventions are wrong. It is that they define the *atom* (one request/response span) and leave the *molecule* (a logical invocation with retries) undefined, so every runtime that aggregates at the molecule level silently sums atoms that were never meant to be summed. ```python from dataclasses import dataclass, field from typing import Optional class RetryTelemetryInvariantError(RuntimeError): """Raised when a logical invocation's telemetry cannot be reconciled against its retry structure without ambiguity.""" @dataclass class AttemptSpan: span_id: str operation_id: str # stable across retries of one logical invocation retry_attempt: int # 0-indexed; must be unique per operation_id input_tokens: int output_tokens: int finish_reason: str committed: bool = False @dataclass class LogicalInvocation: operation_id: str trace_id: str attempts: list[AttemptSpan] = field(default_factory=list) budget_ceiling_input_tokens: int = 5000 def record_attempt(self, span: AttemptSpan) -> None: if span.operation_id != self.operation_id: raise RetryTelemetryInvariantError( f"attempt {span.span_id} belongs to operation " f"{span.operation_id}, not {self.operation_id}" ) seen = {a.retry_attempt for a in self.attempts} if span.retry_attempt in seen: raise RetryTelemetryInvariantError( f"duplicate retry_attempt={span.retry_attempt} for " f"operation {self.operation_id}; retry discriminator is not " f"monotonic, trace-aggregated usage is now ambiguous" ) self.attempts.append(span) def committed_attempt(self) -> Optional[AttemptSpan]: committed = [a for a in self.attempts if a.committed] if len(committed) > 1: raise RetryTelemetryInvariantError( f"operation {self.operation_id} has {len(committed)} committed " f"attempts; commit boundary is not exclusive" ) return committed[0] if committed else None def billed_input_tokens(self) -> int: # Every attempt that reached the provider is billed, committed or not. return sum(a.input_tokens for a in self.attempts) def logical_input_tokens(self) -> int: # Only the committed attempt answers "how big was this decision?" c = self.committed_attempt() if c is None: raise RetryTelemetryInvariantError( f"operation {self.operation_id} has no committed attempt; " f"cannot compute logical cost" ) return c.input_tokens def assert_budget_gate_safe(self) -> None: """Budget gates MUST read billed tokens for hard ceilings and logical tokens for context-window decisions. Reading the raw trace-aggregated sum is the failure mode this guards against.""" billed = self.billed_input_tokens() logical = self.logical_input_tokens() if billed == logical: return # no retries; aggregation is unambiguous # A consumer reading the trace-aggregated sum would see `billed`. # If the gate is configured against a ceiling calibrated for # logical cost, it will falsely trip. if billed > self.budget_ceiling_input_tokens >= logical: raise RetryTelemetryInvariantError( f"operation {self.operation_id}: billed={billed} exceeds " f"ceiling={self.budget_ceiling_input_tokens} but logical=" f"{logical} does not; trace-aggregated budget gate would " f"falsely abort a committed invocation" ) def finalize_invocation(inv: LogicalInvocation) -> None: # Enforce the invariant at the commit boundary, before any effect is # acknowledged to the agent's episodic store. inv.assert_budget_gate_safe() c = inv.committed_attempt() if c is None: raise RetryTelemetryInvariantError( f"cannot finalize {inv.operation_id}: no attempt marked committed" ) if c.finish_reason != "tool_calls": raise RetryTelemetryInvariantError( f"committed attempt {c.span_id} has finish_reason=" f"{c.finish_reason!r}; tool effect must not be committed on a " f"non-tool-call finish" ) ```