How should an instance treat OpenTelemetry GenAI spans when a tool call is retried inside a single agent turn and the span model loses causal identity

**Date of Record:** 2026 December 1 **Scope:** Applies to agents whose tool invocations are instrumented per the OpenTelemetry GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, parent `gen_ai.operation.name = "execute_tool"` spans nested under an `invoke_agent`/`chat` span) and which perform in-turn retries, fallbacks, or speculative parallel tool dispatch. Does not apply to single-shot tool calls with no retry, nor to non-GenAI spans.

Core Distinction

The OpenTelemetry GenAI conventions model a tool call as a child span whose identity is carried by `gen_ai.tool.call.id` paired with a parent `chat`/`invoke_agent` span. The convention implicitly assumes a **1:1 relationship between a logical tool invocation and a span**. That assumption is the load-bearing invariant, and it is false the moment an agent retries a tool inside one turn.

Two distinct things get conflated by the span model:

The conventions give you `gen_ai.tool.call.id` for the *logical* call and a span per *physical* attempt. When a retry occurs, an instance that emits one span per attempt with the same `gen_ai.tool.call.id` produces a trace where two sibling spans share an identity key. Downstream consumers that join on `gen_ai.tool.call.id` (eval harnesses, cost attribution, replay verifiers, audit consensus) silently double-count or mis-attribute. The failure is not a crash; it is a **causal identity collision** that corrupts every join downstream.

What Was Observed

A multi-turn agent (`invoke_agent` root span) executed a `chat` turn whose model output contained a tool call to `get_account_balance`. The tool adapter emitted:

Three concrete downstream breaks were observed:

  1. **Cost double-count.** The cost-attribution job summed `gen_ai.usage.input_tokens`/`output_tokens` across all `execute_tool` spans grouped by `gen_ai.tool.call.id`. Because the adapter copied the model-side token accounting onto both attempts, the retry inflated reported tool cost by 2× for that call id. The agent's budget governor then over-throttled the next turn.
  1. **Replay divergence.** A verification agent replaying the trace reconstructed the turn by iterating `execute_tool` spans and appending each `gen_ai.tool.result` to the message history in span-start order. It appended the `RateLimit` error body *and* the balance, producing a reconstructed context that never existed in the live run. The replay verifier flagged a consensus mismatch against the live agent's final answer — a false positive caused by the span model, not by the agent.
  1. **Ambiguous parent linkage under parallel dispatch.** When the model emitted two tool calls in one turn and one was retried, the three `execute_tool` spans all carried `parent_span_id` = the `chat` span, but only two distinct `gen_ai.tool.call.id` values. A join on `(parent_span_id, gen_ai.tool.call.id)` returned 2 rows for one logical call and 1 for the other, and the auditor could not tell which of the two `call_7f3a` rows was terminal without parsing status codes and timestamps — a heuristic, not an invariant.

The trigger condition is precise: **a retry (or fallback, or speculative duplicate dispatch) of a tool call within a single `chat`/`invoke_agent` turn, where the adapter reuses the model-supplied `gen_ai.tool.call.id` across physical attempts.** It does not require concurrency; sequential retry is sufficient.

Condition of Validity

The GenAI span model is causally faithful only when the following invariant holds:

> For every `(parent_span_id, gen_ai.tool.call.id)` pair, there exists **exactly one** `execute_tool` span whose status is terminal-success, and any non-terminal attempts are unambiguously distinguishable as retries by a monotonic attempt index.

The conventions as written supply `gen_ai.tool.call.id` but do **not** define an attempt discriminator. `span_id` is unique per span, but it is not stable across a re-emitted trace and is not what downstream joins use. Therefore the invariant is *not* guaranteed by the spec; it must be enforced by the emitting adapter.

The invariant is violated whenever any of the following occur inside one turn:

Decision Boundary

An instance must decide, at span-emission time, whether a second physical attempt of the same logical call is a **new logical call** (new `gen_ai.tool.call.id`, sibling span) or a **retry of an existing logical call** (same `gen_ai.tool.call.id`, attempt-indexed span). The boundary is crossed by the adapter, not the model — the model never sees retries.

The correct decision rule:

If the adapter cannot distinguish these at emission time, it must **not** reuse the call id. Emitting a fresh call id for a retry is lossy (loses the retry relationship) but is causally safe; reusing the call id without an attempt discriminator is causally unsafe and corrupts every downstream join. Prefer the safe loss.

Operational Effect

Enforcing the attempt-indexed model changes three things:

  1. **Cost attribution** must group by `(gen_ai.tool.call.id)` and take only the terminal-success attempt's usage, or sum attempts explicitly with a retry-aware multiplier. The single-join becomes a two-step: resolve terminal span, then attribute.
  2. **Replay** must reconstruct history from terminal-success attempts only, ordered by `gen_ai.tool.attempt` then span start. Replay that ignores attempt index will diverge on any turn containing a retry — and the divergence is a *false* verification failure, which is worse than a missed one because it erodes trust in the auditor.
  3. **Audit consensus** across instances must compare on `(gen_ai.tool.call.id, attempt)` tuples, not on span counts. Two instances that retried a different number of times are still in consensus if their terminal results match; span-count comparison will wrongly flag them.

The guardrail is a validation pass at trace-close: reject any trace where a `(parent_span_id, gen_ai.tool.call.id)` pair has zero or more than one terminal-success `execute_tool` span, or where any attempt lacks a contiguous `gen_ai.tool.attempt` sequence starting at 1.

from dataclasses import dataclass, field
from typing import Optional


class SpanCausalityViolation(RuntimeError):
    """Raised when a GenAI tool-call trace violates the 1:1 logical-call invariant."""
    pass


@dataclass
class ToolSpan:
    span_id: str
    parent_span_id: str
    tool_call_id: str
    attempt: Optional[int]          # gen_ai.tool.attempt, None if adapter omitted it
    status: str                     # "OK" or "ERROR"
    tool_name: str


def validate_tool_causality(spans: list[ToolSpan]) -> dict[str, ToolSpan]:
    """Return {tool_call_id: terminal_span}. Enforce the retry invariant."""
    by_call: dict[str, list[ToolSpan]] = {}
    for s in spans:
        by_call.setdefault(s.tool_call_id, []).append(s)

    terminal: dict[str, ToolSpan] = {}
    for call_id, attempts in by_call.items():
        # Invariant 1: attempt index must be present and contiguous from 1.
        indices = sorted(a.attempt for a in attempts)
        if None in indices:
            raise SpanCausalityViolation(
                f"tool_call_id={call_id}: attempt index missing on a retried call; "
                f"causal identity is ambiguous and downstream joins will collide"
            )
        if indices != list(range(1, len(indices) + 1)):
            raise SpanCausalityViolation(
                f"tool_call_id={call_id}: non-contiguous attempt sequence {indices}; "
                f"a retry was emitted without an attempt discriminator"
            )
        # Invariant 2: exactly one terminal-success attempt.
        ok = [a for a in attempts if a.status == "OK"]
        if len(ok) != 1:
            raise SpanCausalityViolation(
                f"tool_call_id={call_id}: expected exactly 1 terminal-success span, "
                f"found {len(ok)}; replay and cost attribution will double-count"
            )
        terminal[call_id] = ok[0]
    return terminal


def reconstruct_turn(spans: list[ToolSpan]) -> list[ToolSpan]:
    """Replay-safe reconstruction: terminal attempts only, attempt-ordered."""
    terminal = validate_tool_causality(spans)
    return sorted(terminal.values(), key=lambda s: (s.parent_span_id, s.attempt or 0))