Why does an instance lose the causal chain when OpenTelemetry GenAI spans are emitted per-turn but the agent loop re-enters a tool call after a retry?

**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*` attributes) across multi-turn loops with tool calls and retries. Does not apply to single-shot inference where one span equals one completion, nor to tracing systems that propagate context exclusively via W3C `traceparent` without any per-turn span re-parenting logic.

Core Distinction

The failure is not a missing span or a dropped attribute. It is a **causal-parent inversion** that occurs when an agent loop retries a tool invocation: the retried tool-call span is emitted as a *sibling* of the original attempt rather than a *child* of the turn that decided to retry. The trace remains structurally valid—every span has a `parent_span_id`, the `trace_id` is stable—so no validator flags it. But the GenAI semantic convention's implicit contract—that a `gen_ai.tool.call` span is a child of the `gen_ai.chat` span whose model output requested it—is silently violated. Downstream causal analysis (cost attribution per decision, failure replay, hallucination tracing) reads the wrong parent and attributes the retry's token cost and error to the wrong reasoning step.

The distinction that matters: **span existence is not span causality.** OpenTelemetry guarantees the former; the GenAI conventions *assume* the latter and never enforce it.

What Was Observed

An agent runtime (loop: `chat → tool_call → chat → …`) emitted the following on a flaky tool that failed once and succeeded on retry:

The trace tree rendered as: `S1` with three children `{S2, S3, S4}`. The retry (`S3`) and the *next reasoning turn* (`S4`) are indistinguishable siblings. The GenAI convention expects `S2` and `S3` to be children of the turn that requested the tool, and `S4` to be a child of the turn that consumed the result—i.e., `S4`'s parent should chain through the tool result, not fork from `S1`.

The concrete damage surfaced in three downstream queries:

  1. **Cost attribution per decision.** Token usage on `S4` (`gen_ai.usage.output_tokens`) was attributed to the root turn `S1` by a naive `parent_span_id` rollup, inflating the first decision's cost by the entire second turn.
  2. **Retry-rate computation.** A monitor counting `execute_tool` spans with `status=ERROR` as children of a `chat` span found *zero* retried failures—because the failed `S2` and the successful `S3` were siblings, the pairing logic that matched "error child followed by success sibling under same parent" never fired. The retry rate read 0% while the tool was failing 40% of attempts.
  3. **Replay divergence.** A verification agent replaying the trace reconstructed the conversation as `[chat, tool, tool]` (two tool results, no intervening chat) and flagged a protocol violation that never occurred.

The root cause: the retry wrapper re-entered the tool with the **turn's** OTel context (captured at loop-entry), not the **attempt's** context. Because OTel context propagation is immutable-by-convention (you `context.attach` a new context per attempt), the wrapper's captured context still pointed at `S1`. Every retry therefore forked from the turn, not from the prior attempt.

Condition of Validity

The invariant that must hold for GenAI spans to be causally sound is:

> For any `gen_ai.tool.call` span `T` and the `gen_ai.chat` span `C` whose model output named `T`'s tool, `T.parent_span_id == C.span_id`. For any retry `T'` of `T`, `T'.parent_span_id == C.span_id` **and** `T'` carries `gen_ai.tool.call.retry_count` (or equivalent) so it is distinguishable from a first attempt. For the consuming turn `C'`, `C'.parent_span_id == C.span_id` only if `C'` is a logical continuation; if `C'` consumes `T'`'s output, the causal edge must be represented explicitly (via a link, not a parent override).

This holds only when:

It does **not** hold—and the failure is not reachable—when the runtime uses a single long-lived span per conversation (no per-turn boundaries), or when retries are handled inside the model's own tool-call emission (no wrapper re-entry).

Decision Boundary

The boundary is: **does the retry wrapper own context creation, or does the turn loop?**

The decision an operator must make: either (a) push retry into the turn loop so context is turn-scoped, or (b) have the wrapper re-read `context.get_current()` *inside* each attempt and attach a child span explicitly, never relying on the captured parent. Option (b) is the minimum viable guardrail because it preserves the decorator abstraction while restoring causal edges.

A secondary boundary: **links vs. parents.** If a turn consumes a tool result, the causal relationship is *data dependency*, not *call nesting*. Representing it as `parent_span_id` (as `S4.parent = S1` does) is a category error. The convention should use `Span.add_link()` for data-dependency edges and reserve `parent_span_id` for call nesting. Runtimes that conflate the two produce traces that are structurally valid but semantically unqueryable.

Operational Effect

The observable consequence is a **silent degradation of every trace-derived metric that depends on causal edges**: per-decision cost, retry rate, tool-failure attribution, and replay fidelity all read from `parent_span_id`. Because the trace passes schema validation (all required `gen_ai.*` attributes present, parent IDs non-null, trace ID consistent), no alert fires. The corruption is only visible when a query *joins* on parent-child relationships and compares against ground-truth turn boundaries—which most dashboards do not.

The guardrail: instrument the retry wrapper to (1) attach a fresh context per attempt, (2) emit an explicit `gen_ai.tool.call.retry_count` attribute, and (3) emit a `link` to the failed prior attempt rather than re-parenting. Then add a trace-integrity assertion at export: every `execute_tool` span's parent must be a `chat` span, and any two `execute_tool` spans sharing a parent must differ in `retry_count` or `tool.call.id`. The assertion below raises on the exact inversion observed.

from dataclasses import dataclass
from typing import Optional


class CausalParentInversion(RuntimeError):
    """Raised when a GenAI tool-call span's parent is not the chat span that requested it,
    or when a retry is indistinguishable from a first attempt under the same parent."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    operation: str            # "chat" | "execute_tool"
    tool_name: Optional[str] = None
    retry_count: Optional[int] = None
    tool_call_id: Optional[str] = None


def assert_genai_causal_integrity(spans: list[Span]) -> None:
    by_id = {s.span_id: s for s in spans}
    # Rule 1: every execute_tool span's parent must be a chat span.
    for s in spans:
        if s.operation != "execute_tool":
            continue
        parent = by_id.get(s.parent_span_id)
        if parent is None:
            raise CausalParentInversion(
                f"tool span {s.span_id} has dangling parent {s.parent_span_id}"
            )
        if parent.operation != "chat":
            raise CausalParentInversion(
                f"tool span {s.span_id} (tool={s.tool_name}) parented to "
                f"{parent.operation} span {parent.span_id}; expected a chat span. "
                f"This is the retry-wrapper context-capture defect."
            )
    # Rule 2: siblings under one chat span must be distinguishable as retries.
    siblings: dict[str, list[Span]] = {}
    for s in spans:
        if s.operation == "execute_tool":
            siblings.setdefault(s.parent_span_id, []).append(s)
    for parent_id, group in siblings.items():
        if len(group) < 2:
            continue
        seen: set[tuple] = set()
        for s in group:
            key = (s.tool_name, s.retry_count, s.tool_call_id)
            if key in seen:
                raise CausalParentInversion(
                    f"two execute_tool spans under chat {parent_id} share "
                    f"identity {key}; retry_count/tool_call_id missing, so the "
                    f"retry is causally indistinguishable from a first attempt."
                )
            seen.add(key)


def emit_tool_span(turn_ctx_parent: str, attempt: int, tool: str,
                   tool_call_id: str, retry_ctx_parent: Optional[str]) -> Span:
    # Guardrail: never trust the wrapper's captured parent on retries.
    parent = retry_ctx_parent if retry_ctx_parent is not None else turn_ctx_parent
    if attempt > 0 and parent != turn_ctx_parent:
        raise CausalParentInversion(
            f"retry attempt {attempt} for {tool} re-parented away from turn "
            f"{turn_ctx_parent} to {parent}; retries must remain children of the "
            f"requesting chat span and carry retry_count."
        )
    return Span(
        span_id=f"{turn_ctx_parent}-{tool}-{attempt}",
        parent_span_id=parent,
        operation="execute_tool",
        tool_name=tool,
        retry_count=attempt if attempt > 0 else None,
        tool_call_id=tool_call_id,
    )