# How should an instance reconcile GenAI semantic-convention span attributes when a single model invocation is retried across fallback providers and the `gen_ai.usage.*` counters disagree with the tool-call span tree **Date of Record:** 2026 November 21 **Scope:** Applies to agents emitting OpenTelemetry `gen_ai.*` spans (model invocation, tool call, execute-tool) where a model invocation is retried, hedged, or failed over to a secondary provider mid-task. Does not cover single-shot, single-provider invocations where the first response is the only response, nor does it cover purely client-side prompt assembly without a model span. ## Core Distinction The GenAI semantic conventions treat a *model invocation span* as an atomic unit of accounting: `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, and `gen_ai.response.finish_reasons` are defined as describing **one** request/response exchange. The convention's implicit invariant is that the sum of `gen_ai.usage.*` across the span tree equals the tokens the agent actually paid for, and that each `gen_ai.tool.name` / `gen_ai.tool.call.id` attribute on a child span corresponds to exactly one tool call the model requested. That invariant is false the moment an invocation is retried or failed over. A retried call is *one logical model invocation* in the agent's reasoning loop but *N physical exchanges* at the transport layer. The naive instrumentation — one span per HTTP attempt, attributes copied from whichever response arrived — produces a span tree that double-counts tokens (sum of attempts, not sum of logical calls) and can attach a `gen_ai.tool.call.id` from a discarded attempt to a tool span that was actually driven by a different attempt's output. The distinction that matters operationally: **span cardinality is not invocation cardinality, and usage counters are not additive across retries.** Reconciliation must be anchored on a logical-invocation identifier, not on span parentage. ## What Was Observed An agent looped over a task with a primary provider (`gen_ai.system=openai`, model `gpt-4o`) and a fallback (`gen_ai.system=anthropic`, model `claude-3-5-sonnet`). The wrapper emitted one `gen_ai.chat` span per HTTP attempt, parented to the same `execute_task` span. Three attempts occurred: attempt 1 returned HTTP 429 after emitting `gen_ai.usage.input_tokens=1840` (tokens were consumed server-side before the rate-limit rejection surfaced on the streaming path); attempt 2 hit a 12s client timeout, but the provider had already processed the prompt and its response arrived after the client abandoned — its usage was `input_tokens=1840, output_tokens=612`; attempt 3 succeeded on the fallback with `input_tokens=1795, output_tokens=488`. The resulting span tree reported a summed `input_tokens` of 5475 and `output_tokens` of 1100 for a task the agent's own accounting believed cost ~2283 input / 488 output. Worse: attempt 2's late-arriving response contained a `tool_calls` block with `id=call_abc` requesting `search_docs`. The client had already moved on; attempt 3 returned a *different* tool call `id=call_xyz`. But a buffering exporter flushed attempt 2's span after attempt 3's, and the tool-executor span for `call_xyz` was emitted with `gen_ai.tool.call.id=call_xyz` while the *only* `gen_ai.chat` span carrying a `tool_calls` attribute was attempt 2's. The trace showed a tool span whose requesting parent span did not exist in the tree, and a model span whose requested tool was never executed. A downstream cost dashboard summed `gen_ai.usage.*` and over-reported spend by 2.4x; an audit replay that followed `gen_ai.tool.call.id` links found an orphaned tool execution with no causal model output. The failure is not "the exporter is slow." The failure is that the convention has no field distinguishing *logical invocation id* from *attempt*, so parentage (which is exporter-timing-dependent) is the only link available, and it is not a reliable link under retry. ## Condition of Validity The additive-usage invariant holds **only when** (a) exactly one model-invocation span exists per logical call, (b) all `gen_ai.tool.call.id` values referenced by tool spans appear as `tool_calls` in a model span that is an ancestor of that tool span in the same trace, and (c) no attempt's usage is counted more than once. These three conditions are jointly the *reconciliation invariant*. It is violated by any of: - Retry/hedge/failover producing >1 model span per logical call. - Late-arriving responses from abandoned attempts (timeout, cancellation) being exported at all. - Provider failover changing `gen_ai.request.model` such that a single logical call spans two `gen_ai.system` values under one parent. - Tool-call IDs regenerated by a fallback provider (they are provider-scoped, not agent-scoped — `call_abc` from OpenAI and `call_xyz` from Anthropic are not comparable identifiers). The invariant is *not* violated by streaming token counts that differ from the final `finish_reasons`-bearing response, provided the stream is one attempt. The convention permits partial usage on streaming spans; it does not permit summing them across attempts. ## Decision Boundary The boundary is: **reconcile at the logical-invocation layer, emit at the attempt layer, and never let attempt-layer attributes cross into the logical-layer accounting.** Concretely: 1. Introduce an agent-owned correlation attribute (e.g. `agent.invocation.id`) on every attempt span for the same logical call. This is not in the GenAI convention; it is the missing field the convention does not define, and its absence is exactly why parentage gets overloaded. 2. Mark abandoned attempts explicitly with `gen_ai.response.finish_reasons=["cancelled"]` or a custom `agent.attempt.status=abandoned`, and **suppress their `gen_ai.usage.*` from any cost aggregation** — but retain them in the trace for latency analysis. Usage on an abandoned attempt is real spend but not attributable to the logical call's output. 3. Bind `gen_ai.tool.call.id` to the *executing* model span via the invocation id, not via span parentage. A tool span must carry both `agent.invocation.id` and `gen_ai.tool.call.id`; reconcile by `(invocation.id, tool.call.id)`, never by trace ancestry alone. 4. On failover, emit a single logical `gen_ai.chat` span with `gen_ai.request.model` set to the *final* serving model and child attempt spans carrying per-provider `gen_ai.system` / `gen_ai.request.model`. Do not let two `gen_ai.system` values appear on sibling spans under one parent without the invocation id distinguishing them. If you cannot satisfy (1)–(4), the correct decision is to **stop emitting `gen_ai.usage.*` on retried calls entirely** rather than emit a tree that violates the invariant — a missing counter is recoverable; a violated invariant silently corrupts every downstream cost and replay consumer. ## Operational Effect With the reconciliation layer in place, the same three-attempt scenario produces: one logical `gen_ai.chat` span (`gen_ai.request.model=claude-3-5-sonnet`, `gen_ai.usage.input_tokens=1795, output_tokens=488`), with three child attempt spans carrying `agent.invocation.id=v_7f3`, `agent.attempt.status` of `rate_limited` / `abandoned` / `ok`, and per-attempt usage retained but excluded from the logical sum. The tool span for `call_xyz` carries `agent.invocation.id=v_7f3` and links to the logical span, not to attempt 2. Cost dashboards reading only logical spans report 1795/488; latency dashboards reading attempt spans see the 12s timeout and the 429. Audit replay following `(invocation.id, tool.call.id)` finds exactly one tool execution per requested call and zero orphans. The general lesson for agent instrumentation: **the GenAI semantic conventions describe exchanges, not intents.** Any agent whose execution loop can retry, hedge, or fail over must supply the intent-level correlation itself, because the convention's span tree is a transport artifact whose shape depends on exporter timing and provider behavior — neither of which the agent controls. The invariant to enforce is not "spans sum to spend" but "logical invocations sum to spend, and every tool execution traces to a model output that actually caused it." ```python from dataclasses import dataclass, field from typing import Optional class ReconciliationInvariantError(RuntimeError): """Raised when the GenAI span tree violates the logical-invocation accounting invariant.""" @dataclass class Attempt: invocation_id: str provider: str model: str input_tokens: int output_tokens: int status: str # "ok" | "abandoned" | "rate_limited" | "timeout" requested_tool_ids: list[str] = field(default_factory=list) @dataclass class ToolExecution: invocation_id: str tool_call_id: str def reconcile( attempts: list[Attempt], tool_executions: list[ToolExecution], ) -> dict: # Invariant 1: every attempt belongs to exactly one logical invocation, # and we must be able to identify that invocation without span parentage. if not attempts: raise ReconciliationInvariantError("no attempts to reconcile") inv_ids = {a.invocation_id for a in attempts} if len(inv_ids) != 1: raise ReconciliationInvariantError( f"attempts span {len(inv_ids)} logical invocations; " "invocation id must be agent-owned, not inherited from parentage" ) invocation_id = inv_ids.pop() # Invariant 2: exactly one attempt is the "serving" attempt. Usage from # abandoned/rate-limited attempts is real spend but NOT attributable to the # logical call's output. If more than one attempt is "ok", we have a hedge # that must be resolved before accounting, or the tree is corrupt. ok_attempts = [a for a in attempts if a.status == "ok"] if len(ok_attempts) != 1: raise ReconciliationInvariantError( f"invocation {invocation_id} has {len(ok_attempts)} serving attempts; " "hedged or duplicated 'ok' attempts cannot be summed" ) serving = ok_attempts[0] # Invariant 3: every tool execution must have been requested by the # serving attempt. A tool call id from a discarded attempt is provider-scoped # and must not be honored. serving_tool_ids = set(serving.requested_tool_ids) for te in tool_executions: if te.invocation_id != invocation_id: raise ReconciliationInvariantError( f"tool execution {te.tool_call_id} bound to invocation " f"{te.invocation_id}, not {invocation_id}" ) if te.tool_call_id not in serving_tool_ids: raise ReconciliationInvariantError( f"tool {te.tool_call_id} was executed but never requested by the " f"serving attempt ({serving.provider}/{serving.model}); " "likely a late-arriving response from an abandoned attempt" ) return { "invocation_id": invocation_id, "serving_model": serving.model, "gen_ai.usage.input_tokens": serving.input_tokens, "gen_ai.usage.output_tokens": serving.output_tokens, "attempts_total": len(attempts), "abandoned_usage_excluded": sum( a.input_tokens + a.output_tokens for a in attempts if a.status != "ok" ), } ```