Where must an instance draw the line between semantic-convention attribution and span-level truth when a tool call is retried under a new span?

**Date of Record:** 2026 December 1

**Scope:** Applies to any agent runtime that emits OpenTelemetry-style GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.*`, `gen_ai.response.id`, retrieval span attributes such as `gen_ai.data_source.id` and document IDs) and that also retries tool invocations or re-runs retrieval under a fresh span. Does not cover purely in-process logging without a span model, nor billing reconciliation that reads directly from provider invoices.

Core Distinction

The GenAI semantic conventions describe *what the model or tool did* at the level of a single logical operation. Spans describe *when and how many times the runtime attempted it*. These two axes are orthogonal, and the conventions deliberately do not define a retry-attribution rule: `gen_ai.tool.name` is a property of the invocation, not of the attempt, while `trace_id`/`span_id` and `gen_ai.response.id` are properties of the attempt. The boundary condition is this: **a retried tool call produces N spans but one logical attribution unit, and the conventions give no field to say "these N spans are the same call."** Any runtime that treats span count as call count, or that sums `gen_ai.usage.input_tokens`/`output_tokens` across retried spans into a per-tool attribution, will silently double- or triple-count. The invariant that must hold is: *attribution cardinality is keyed on a runtime-assigned logical-call identity, never on span identity, and every retried span must carry that identity in a non-standard-but-stable attribute so downstream consumers can collapse it.*

What Was Observed

A retrieval-augmented agent executing a `search_docs` tool against a flaky vector backend was instrumented with the GenAI conventions. On the happy path each call emitted one `execute_tool` span with `gen_ai.tool.name=search_docs`, `gen_ai.operation.name=execute_tool`, and a retrieval child span carrying `gen_ai.data_source.id` plus the returned document IDs. Under a 4xx-then-200 retry policy (retry on `503`, max 3 attempts), the observed trace for a single user turn contained three `execute_tool` spans sharing `gen_ai.tool.name`, each with its own `gen_ai.response.id` (attempt 1 and 2 had provider-generated error response IDs; attempt 3 succeeded). The retrieval child span existed only under attempt 3.

Two concrete failures followed:

  1. **Token double-counting.** The attribution dashboard summed `gen_ai.usage.input_tokens` over all spans with `gen_ai.tool.name=search_docs`. Attempts 1 and 2 had already consumed prompt tokens for the tool-selection reasoning that was re-sent on each attempt (the runtime re-serialized the full message history per attempt rather than caching the tool-call decision). The reported per-tool token cost was 2.7× the true cost, and the "expensive tool" ranking inverted: a cheap-but-flaky tool outranked an expensive-but-reliable one.
  1. **Retrieval provenance collapse.** A downstream grounding auditor joined retrieval document IDs to the *first* `execute_tool` span by `gen_ai.tool.name` ordering, not by trace-parent linkage. Because attempts 1 and 2 had no retrieval child span, the auditor recorded "retrieved 0 documents" for the call and flagged the final answer as ungrounded, even though attempt 3 returned three documents. The auditor's join key (`tool.name` + span order) was not the identity the runtime intended.

Neither failure is a bug in the conventions. Both are consequences of the runtime assuming that one `gen_ai.tool.name` span equals one logical call, which the conventions never promise.

Condition of Validity

The single-span-equals-single-call assumption is valid only when all of the following hold:

When any condition fails — and in practice the first fails whenever retries are implemented by re-entering the tool-execution function, which is the common case — the assumption is invalid and a logical-call identity must be introduced. The boundary is therefore not "retries are bad" but "the moment retry opens a new span, span-level attribution is no longer call-level attribution, and the runtime owes downstream consumers a collapse key."

Decision Boundary

The runtime must decide, per tool invocation, between two attribution regimes:

The decision boundary is crossed at the first retry. Before the first retry, the two regimes are indistinguishable and either is correct. After the first retry, only attempt-explicit attribution preserves the invariant. The guardrail is therefore: *the retry wrapper, not the tool implementation, must be the thing that stamps `gen_ai.call.id`, and any consumer that aggregates on `gen_ai.tool.name` alone must be treated as a known-defective join.*

Operational Effect

Adopting attempt-explicit attribution changes three operational behaviors:

  1. **Cost dashboards must `COUNT(DISTINCT gen_ai.call.id)` and `SUM` usage per call, not per span.** Per-tool cost becomes comparable across flaky and reliable tools, restoring the ranking that the naive sum inverted.
  2. **Provenance joins must key on `gen_ai.call.id`, not on `tool.name` + span order.** The grounding auditor's "0 documents" false negative disappears because it joins the terminal attempt's retrieval child span to the logical call, not to the first span bearing the tool name.
  3. **Retry-policy changes become observable without re-instrumenting the tool.** Because `gen_ai.call.id` is assigned by the wrapper, increasing `max_attempts` from 3 to 5 changes span count but not call count, so attribution series remain continuous across the policy change — a property the attempt-transparent regime cannot offer, since it hides retries inside a span and makes attempt count invisible.

The residual risk is that `gen_ai.call.id` is a non-standard attribute; consumers that validate strictly against the published conventions will drop it. The runtime must therefore emit it alongside, not instead of, the standard attributes, and must document that standard-only consumers are subject to the double-counting failure described above.

from dataclasses import dataclass, field
from typing import Optional


class AttributionInvariantError(RuntimeError):
    """Raised when a span-level attribution would violate call-level cardinality."""


@dataclass
class Attempt:
    span_id: str
    tool_name: str
    response_id: Optional[str]
    input_tokens: int
    has_retrieval_child: bool


@dataclass
class LogicalCall:
    call_id: str
    tool_name: str
    attempts: list = field(default_factory=list)

    def add_attempt(self, attempt: Attempt) -> None:
        if attempt.tool_name != self.tool_name:
            raise AttributionInvariantError(
                f"attempt {attempt.span_id} tool={attempt.tool_name} "
                f"does not match call {self.call_id} tool={self.tool_name}"
            )
        self.attempts.append(attempt)

    def attributed_tokens(self) -> int:
        # Only the terminal attempt's usage is attributable to the call;
        # earlier attempts re-incurred context that must not be summed.
        if not self.attempts:
            return 0
        return self.attempts[-1].input_tokens

    def terminal_retrieval_docs(self) -> int:
        terminal = self.attempts[-1] if self.attempts else None
        if terminal is None or not terminal.has_retrieval_child:
            raise AttributionInvariantError(
                f"call {self.call_id} terminal attempt has no retrieval child span; "
                "provenance join would yield a false-negative grounding result"
            )
        return 1


def attribute(spans: list[Attempt], call_id: str) -> LogicalCall:
    if not spans:
        raise AttributionInvariantError(f"call {call_id} has zero spans; cannot attribute")
    call = LogicalCall(call_id=call_id, tool_name=spans[0].tool_name)
    for s in spans:
        call.add_attempt(s)
    # Enforce the boundary: every attempt after the first must be identifiable
    # as the same logical call, which the wrapper guarantees via call_id.
    if len(call.attempts) > 1 and not call_id:
        raise AttributionInvariantError(
            f"multi-attempt call {call_id} lacks a logical-call identity; "
            "span-level attribution would double-count"
        )
    return call