Which invariants prevent tool-call span misattribution across multi-turn agent turns under OpenTelemetry GenAI semantic conventions

**Date of Record:** 2026 December 1

**Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.*`) for a multi-turn conversation where each assistant turn may contain zero or more tool calls, and where tool results are fed back into a subsequent LLM call. Does not apply to single-shot RAG pipelines or to agents that emit only a single span per session.

Core Distinction

A tool-call span is not a child of "the agent." It is a child of a *specific* LLM invocation that *requested* that tool call, and its result must be attributed back to exactly one subsequent LLM invocation that *consumed* it. The GenAI semantic conventions encode this contract through a small set of attributes — `gen_ai.operation.name`, `gen_ai.conversation.id`, `gen_ai.request.model`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, and the parent-child span linkage — but they do not enforce it. The boundary failure is subtle: when an agent runs multiple LLM invocations concurrently or retries a failed turn, the `gen_ai.tool.call.id` returned by the model in turn *N* is frequently reused or regenerated in turn *N+1*, and the tool-result span's parent pointer silently attaches to the wrong LLM span. The trace looks well-formed. The attribution is wrong.

The invariant that must hold is: **for every `gen_ai.tool.call.id`, there exists exactly one tool-execution span whose parent is the LLM span that emitted that id, and exactly one subsequent LLM span whose `gen_ai.prompt` contains the matching `tool_call_id` in its messages array.** Violating either half produces an orphan or a double-parented tool span, and downstream cost/latency analyzers will attribute tool time to the wrong turn.

What Was Observed

A planner agent (model `gpt-4o`, `gen_ai.operation.name=chat`) executed a 9-turn conversation. Turn 4 issued two parallel tool calls (`search`, `fetch_url`) with ids `call_a1` and `call_a2`. The tool executor ran them concurrently and emitted two `gen_ai.operation.name=execute_tool` spans. Both carried the correct `gen_ai.tool.call.id`. Both had `parent_span_id` set to the turn-4 chat span. So far, correct.

Turn 5's chat request failed with a 429 from the provider. The orchestrator retried. The retry re-sent the same message array — including the `tool_call_id: call_a1` and `call_a2` entries — but the retry was issued as a *new* LLM span (new `span_id`, same `gen_ai.conversation.id`). The model responded with a fresh tool call, and the model's SDK regenerated ids as `call_b1`. The tool executor, however, cached the prior result keyed by `gen_ai.tool.call.id` and re-emitted the turn-4 tool spans as children of the *retry* span, not the original turn-4 span. Because the retry span had a different `span_id`, the tool spans now had two distinct parents across the trace: the original turn-4 chat span and the turn-5 retry span both claimed `call_a1` as a child. The backend's span deduplication (which keys on `(trace_id, span_id)`) did not catch it because the span ids differed; only the `gen_ai.tool.call.id` collided. Result: the trace showed the `search` tool executing twice, once under turn 4 and once under turn 5, inflating measured tool latency by 2× and misattributing 1.4 s of `fetch_url` time to the retry.

A second, independent observation: in a different run, turn 7 emitted a tool call but the model's response was truncated at `max_tokens`, so the tool-call block was incomplete. The orchestrator parsed a partial `gen_ai.tool.call.id` (`call_c` instead of `call_c0ffee`), executed the tool anyway, and emitted a span. The subsequent turn-8 chat span's message array contained the *full* id `call_c0ffee`. The tool span and the consuming chat span disagreed on the id, and no analyzer could join them. The tool time became an orphan.

Condition of Validity

The invariant holds only when all of the following are true:

  1. `gen_ai.tool.call.id` is treated as a globally unique, immutable identifier scoped to `(gen_ai.conversation.id, gen_ai.tool.call.id)`, and the orchestrator refuses to emit a tool span whose id is not present verbatim in the *preceding* LLM span's `gen_ai.prompt` messages.
  2. Retries of an LLM invocation reuse the *same* `span_id` (i.e., the retry is modeled as an event on the original span, or the original span is marked failed and the retry is a sibling under a shared `gen_ai.conversation.id` with an explicit `retry.attempt` attribute), not as a fresh span that can re-parent tool spans.
  3. Tool results are keyed by the full `(conversation_id, tool_call_id, parent_llm_span_id)` tuple, not by `tool_call_id` alone.
  4. Truncated model responses are detected (`finish_reason=length` with an incomplete tool-call block) and the orchestrator aborts rather than executing a partial id.

Outside these conditions — for example, when the agent framework generates its own tool-call ids and never echoes the model's id back into the next prompt — the join is unrecoverable post hoc, and the semantic conventions provide no rescue.

Decision Boundary

The boundary is between *tracing as observation* and *tracing as control*. If spans are emitted purely for observability, a misattributed tool span is a data-quality defect: dashboards are wrong, but the agent still runs. If spans are consumed by the orchestrator itself — for example, a cost-budget guard that reads `gen_ai.usage.input_tokens` from the parent chat span before allowing the next tool call — then a mis-parented tool span breaks the budget check, because the tool span's parent reports zero tokens and the guard concludes the turn was free. The decision boundary is: **once any control-plane logic reads span attributes to make an execution decision, the attribution invariant becomes a safety invariant, not a telemetry nicety.** At that point the orchestrator must validate the parent-child linkage *before* the next LLM call, not after the trace is exported.

Operational Effect

Enforcing the invariant changes three things: (a) the tool executor must reject any tool call whose id is not a verbatim substring of the immediately preceding chat span's serialized prompt — a cheap check that catches truncation and id-regeneration; (b) retries must be modeled as `retry.attempt` events on the original span, preserving `span_id`, so that tool spans have exactly one parent; (c) tool-result caches must key on the triple `(conversation_id, tool_call_id, parent_llm_span_id)`. With these in place, the trace join is deterministic, and a cost guard reading parent spans sees the correct token attribution. The cost is that the orchestrator must hold the serialized prompt of the last chat span in memory until the tool result is consumed — a bounded buffer of one turn, not the whole conversation.

from dataclasses import dataclass
from typing import Optional


class ToolCallAttributionError(RuntimeError):
    """Raised when a tool-call span cannot be unambiguously attributed to an LLM span."""
    pass


@dataclass(frozen=True)
class ChatSpan:
    span_id: str
    conversation_id: str
    serialized_prompt: str          # full messages array as sent to the model
    finish_reason: str              # "stop", "tool_calls", "length", ...


@dataclass(frozen=True)
class ToolCall:
    tool_call_id: str
    tool_name: str
    parent_llm_span_id: str


def validate_tool_call_attribution(
    tool_call: ToolCall,
    preceding_chat: ChatSpan,
    conversation_id: str,
) -> None:
    if tool_call.parent_llm_span_id != preceding_chat.span_id:
        raise ToolCallAttributionError(
            f"tool call {tool_call.tool_call_id!r} claims parent "
            f"{tool_call.parent_llm_span_id!r} but the immediately preceding "
            f"chat span is {preceding_chat.span_id!r}"
        )
    if preceding_chat.conversation_id != conversation_id:
        raise ToolCallAttributionError(
            f"conversation mismatch: tool call in {conversation_id!r}, "
            f"chat span in {preceding_chat.conversation_id!r}"
        )
    if preceding_chat.finish_reason == "length":
        raise ToolCallAttributionError(
            f"preceding chat span {preceding_chat.span_id!r} was truncated "
            f"(finish_reason=length); tool_call_id {tool_call.tool_call_id!r} "
            f"may be partial and must not be executed"
        )
    if tool_call.tool_call_id not in preceding_chat.serialized_prompt:
        raise ToolCallAttributionError(
            f"tool_call_id {tool_call.tool_call_id!r} does not appear verbatim "
            f"in the preceding chat span's prompt; id was regenerated or "
            f"truncated and cannot be joined to a consuming LLM span"
        )


def emit_tool_span(
    tool_call: ToolCall,
    preceding_chat: Optional[ChatSpan],
    conversation_id: str,
) -> dict:
    if preceding_chat is None:
        raise ToolCallAttributionError(
            f"no preceding chat span recorded for tool call "
            f"{tool_call.tool_call_id!r}; refusing to emit orphan tool span"
        )
    validate_tool_call_attribution(tool_call, preceding_chat, conversation_id)
    return {
        "name": f"execute_tool {tool_call.tool_name}",
        "parent_span_id": preceding_chat.span_id,
        "attributes": {
            "gen_ai.operation.name": "execute_tool",
            "gen_ai.conversation.id": conversation_id,
            "gen_ai.tool.name": tool_call.tool_name,
            "gen_ai.tool.call.id": tool_call.tool_call_id,
        },
    }