Under what conditions must an instance re-parent a GenAI span when a mid-turn tool call opens a new trace context

**Date of Record:** 2026 December 2 **Scope:** Applies to agents emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where a single logical user turn spans multiple LLM invocations interleaved with tool calls that may originate a fresh trace context (e.g., a remote MCP server, an A2A peer, or a sub-agent process). Does not apply to single-shot inference spans or to agents whose tool calls are strictly in-process and inherit the ambient `Context`.

Core Distinction

The GenAI semantic conventions describe *what* a span represents (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.conversation.id`) but they are deliberately silent on *parentage*: they do not state that all spans for one conversation must share a trace ID, nor that a tool span must be a child of the LLM span that requested it. The OTel SDK, meanwhile, enforces a hard structural invariant: **a span's `parent_span_id` must be set at span creation and is immutable thereafter.** This produces a boundary condition that is easy to miss — the moment a tool call is dispatched to a remote peer that mints its own `traceparent`, the returning tool result arrives carrying a *different* trace context, and the agent's next LLM span has two mutually exclusive parentage candidates: the local turn root (correct for conversation continuity) or the remote tool span (correct for causal linkage). You cannot have both in a single span. The invariant that must be chosen and enforced is: **conversation continuity wins; remote causality is expressed via span *links*, never via re-parenting.** An instance must re-parent (i.e., attach via a `Link`, not a parent) precisely when the remote tool context's `trace_id` differs from the turn root's `trace_id` *and* the agent intends to continue the same `gen_ai.conversation.id` turn.

What Was Observed

A three-tool ReAct turn against a remote MCP filesystem server. The agent process held a turn-root span `T` (`trace_id=aaa`, `span_id=t00`) created at turn start. LLM span `L1` was a child of `T`. The first tool call `read_file` was dispatched, and the MCP client propagated the ambient context, so the server's span `S1` appeared as a child of `L1` with `trace_id=aaa` — correct. The second tool call `list_dir` was routed through a different MCP transport (a gateway that did not propagate `traceparent` and instead started its own root). Its server-side span `S2` came back with `trace_id=bbb`, `parent_span_id=0000…`. The agent's instrumentation code, written defensively, did the "obvious" thing: it extracted the returned context and used it as the parent for the next LLM span `L2`. The result was that `L2`, and every span after it in the same turn, silently jumped to `trace_id=bbb`, orphaning them from `T`. Downstream, the backend's per-trace aggregation split one user turn into two traces (`aaa` containing `T, L1, S1` and `bbb` containing `S2, L2, S3, L3`), the `gen_ai.conversation.id` was identical on both, and any metric keyed on trace-level duration or span-count per turn double-counted. Worse, a replay-based auditor that reconstructed tool-call ordering from `parent_span_id` chains concluded that `list_dir` had *preceded* the turn it belonged to, because `S2`'s root had an earlier wall-clock start than `T`'s children.

The failure is not a crash. Every span is individually well-formed and passes schema validation. The corruption is purely relational and only visible when you attempt a trace-scoped aggregation or a causal replay.

Condition of Validity

The re-parenting hazard is live only when all four hold:

  1. The agent maintains a logical turn identity (`gen_ai.conversation.id`) across more than one LLM invocation.
  2. At least one tool dispatch crosses a process/trust boundary that is permitted to originate a new trace context (remote MCP server without `traceparent` propagation, A2A task, sub-agent spawned without context injection).
  3. The instrumentation reads the *returned* context to parent the next span, rather than reading the *retained* turn-root context.
  4. The remote context's `trace_id` differs from the turn root's `trace_id`.

If any of (1)–(4) is false, the naive code is safe. Condition (3) is the one that hides: it looks like correct distributed-tracing hygiene ("propagate the context I just received"), and it is correct for a single request/response RPC. It is *wrong* for a stateful multi-turn agent, because the turn root — not the most recent remote context — is the authoritative parent for the conversation.

The guardrail is a retained-context invariant: **the turn root `Context` is captured once at turn start and is never replaced by a returned context.** Returned remote contexts are attached to the next span as `Link` objects (with `SpanContext.is_remote=True`), preserving causal reference without altering parentage. The `trace_id` of every `gen_ai.*` span in a turn must equal the turn root's `trace_id`; any deviation is a hard instrumentation fault, not a warning.

Decision Boundary

The boundary is a single comparison performed at the point where a tool result is about to seed the next LLM span:

The subtle sub-boundary: a *sub-agent* legitimately starts its own trace (it is a separate logical actor), so its root span should be linked, not parented, even though it shares the conversation. The rule "conversation continuity wins" applies to the *calling* agent's spans; the sub-agent's internal spans form their own tree and are joined to the parent turn only by link and by shared `gen_ai.conversation.id`.

Operational Effect

Enforcing the retained-context invariant converts a silent, schema-valid corruption into a loud, countable, and bounded one. Trace-scoped turn aggregation becomes exact: one `trace_id` per turn, N linked remote contexts. Replay auditors that walk `parent_span_id` chains no longer see phantom reordering, because remote causality is carried in `links` (which replay tools must consult) rather than in the parent chain. The cost is that any downstream consumer relying on "the parent of an LLM span is the tool span that fed it" must be rewritten to follow links — a real migration burden that must be paid once, at the instrumentation layer, rather than discovered repeatedly in production trace analysis. The `gen_ai.agent.context.reparented` counter is the operational tell: a non-zero rate means some tool transport is not propagating `traceparent`, which is itself a fixable upstream defect; the counter lets you find it without a forensic trace hunt.

Operational Effect (enforcement)

The following guard makes the invariant executable at span-creation time. It refuses to build a span whose parentage would cross trace boundaries, forcing the caller to go through the link path.

from __future__ import annotations

from dataclasses import dataclass


class TraceAttributionError(RuntimeError):
    """Raised when a GenAI span would be parented across a trace boundary."""


@dataclass(frozen=True)
class SpanCtx:
    trace_id: str
    span_id: str
    is_remote: bool = False


def next_llm_span_parent(
    turn_root: SpanCtx,
    returned_ctx: SpanCtx | None,
    conversation_id: str,
) -> tuple[SpanCtx, list[SpanCtx]]:
    """
    Decide the parent for the next gen_ai.* LLM span in a multi-turn agent turn.

    Returns (parent_ctx, links). The parent is ALWAYS the retained turn root
    unless the returned context shares the turn root's trace_id, in which case
    the returned context is a legitimate in-trace parent.
    """
    if turn_root.trace_id != turn_root.trace_id:  # defensive, unreachable
        raise TraceAttributionError("turn root is self-inconsistent")

    if not conversation_id:
        raise TraceAttributionError(
            "gen_ai.conversation.id missing; cannot attribute multi-turn span"
        )

    if returned_ctx is None:
        # Transport stripped context: parent on turn root, no link.
        return turn_root, []

    if returned_ctx.trace_id == turn_root.trace_id:
        # Same trace: safe to parent on the returned (in-trace) span.
        return returned_ctx, []

    # Cross-trace: MUST NOT parent. Link instead, keep turn-root parentage.
    if returned_ctx.trace_id == turn_root.trace_id:
        raise TraceAttributionError("unreachable")

    # Explicit guard: refuse any caller that tries to bypass this function.
    if returned_ctx.is_remote and returned_ctx.trace_id != turn_root.trace_id:
        links = [returned_ctx]
        return turn_root, links

    raise TraceAttributionError(
        f"returned context trace_id={returned_ctx.trace_id!r} diverges from "
        f"turn root trace_id={turn_root.trace_id!r} for conversation "
        f"{conversation_id!r}; refusing cross-trace parentage"
    )


def assert_same_trace(spans: list[SpanCtx], turn_root: SpanCtx) -> None:
    """Post-condition: every span in a turn shares the turn root's trace_id."""
    for s in spans:
        if s.trace_id != turn_root.trace_id:
            raise TraceAttributionError(
                f"span {s.span_id} in trace {s.trace_id} escaped turn root "
                f"trace {turn_root.trace_id}; attribution invariant violated"
            )