Where must an instance reconcile span-parentage when a tool-call graph is re-entered after a mid-trajectory resume, and why the GenAI semantic conventions silently permit a fork

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that emit OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) and that support checkpoint/resume or replay of a multi-turn trajectory. Does not apply to single-shot, non-resumable inference calls, nor to spans emitted by a stateless gateway that never re-enters a trajectory.

Core Distinction

The distinction that matters is between **span identity** (the `trace_id`/`span_id` pair, immutable once emitted) and **span parentage** (the `parent_span_id` reference that defines the causal graph). The GenAI semantic conventions specify attribute names for a *single* model invocation or tool execution—`gen_ai.operation.name`, `gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`—but they do **not** define a normative rule for how a resumed trajectory must re-attach to the span tree of the trajectory it is continuing. Parentage is left to the generic OTel context-propagation mechanism, which assumes a live in-process context. A resume is precisely the case where that assumption is false.

The failure is not "spans are missing." It is that a resumed agent emits a *second, well-formed, schema-valid* subtree whose root has no `parent_span_id` linking it to the pre-checkpoint subtree, while both subtrees carry the same logical trajectory identity (same conversation, same `gen_ai.conversation.id`, same tool-call sequence). The trace backend sees two valid roots. Nothing in the convention flags it.

What Was Observed

A three-turn agent trajectory: turn 1 invokes `search` (tool call id `tc_001`), turn 2 invokes `fetch` (`tc_002`) using turn 1's output, turn 3 synthesizes. The agent checkpoints after turn 2's tool result is persisted, then the process is evicted (OOM, pod reschedule, or token-budget-triggered handoff to a fresh worker).

On resume, the new process rehydrates the message history from the checkpoint store. It reconstructs *messages* faithfully—the `tool_call_id` references in the assistant/tool message pairs are intact, so the LLM sees a coherent conversation. But the OTel `Context` object that carried the pre-eviction span was never serialized into the checkpoint. The new process starts with a root `Context`. The resumed turn-3 span is emitted with:

The result in the trace store: two traces sharing one `gen_ai.conversation.id`. The turn-2 `fetch` span appears **twice**—once under the pre-eviction trace (with a real duration and status) and once under the post-resume trace (re-emitted during history replay, near-zero duration, `status=UNSET`). Downstream trajectory evaluators that sum `gen_ai.usage.input_tokens` across the conversation double-count turn 2's prompt tokens. Evaluators that reconstruct the tool-invocation graph by following `parent_span_id` from the final span see a graph of depth 1 that omits both prior tool calls entirely—the causal chain `tc_001 → tc_002 → synthesis` collapses to `synthesis`.

The subtle part: **every span validates against the semantic conventions.** Attribute presence, types, and required-key rules all pass. The break is purely topological.

Condition of Validity

The invariant that must hold is:

> For any trajectory identified by a stable `gen_ai.conversation.id`, the union of all spans carrying that id must form a single weakly-connected causal component, and no `(gen_ai.tool.call.id, gen_ai.operation.name=execute_tool)` pair may appear more than once with `status != UNSET` in that component.

This invariant is *not* enforced by the convention; it must be enforced by the emitter. It is valid only when the checkpoint carries enough information to reconstruct parentage. Concretely, the checkpoint must persist, per pending span boundary, at minimum: the `trace_id`, the `span_id` of the span that was open at checkpoint time (the reattachment point), and a monotonic trajectory sequence number so that replayed tool spans can be distinguished from live ones.

The condition fails silently whenever any of the following hold, and these are the common cases, not the exotic ones:

  1. The checkpoint serializes *messages* but not the OTel `Context` (the default in most agent frameworks, because messages are the LLM-visible state and spans are treated as telemetry side-channel).
  2. The resume path replays history through the same code that emits spans, so replayed turns re-emit tool spans. This is the fork source: replay is treated as re-execution.
  3. The worker that resumes is a *different* instance (handoff, scale-out, A2A transfer) and thus has no in-memory link to the prior `trace_id`—`trace_id` is generated fresh per process unless explicitly propagated.

Decision Boundary

The boundary is between **replay-for-context** and **re-execution**. When a resumed agent reconstructs prior turns, it must decide for each prior turn: does this turn's span get *re-emitted* (treated as a new execution) or *referenced* (treated as already-executed history)?

The decision is per-turn and depends on whether the tool result is in the checkpoint. An emitter that makes this decision uniformly—"always re-emit" or "never re-emit"—is wrong in one direction or the other. Always-re-emit produces the double-count fork. Never-re-emit produces an orphaned trajectory with no post-resume spans at all when the checkpoint landed mid-call.

The reattachment point must be the *last* span that was open at checkpoint time, not the trajectory root. Reattaching to the root flattens the graph and loses the inter-tool causal edges; the resumed subtree must hang off the specific span whose work was in flight.

Operational Effect

Downstream consumers that assume single-component trajectories break in three specific ways, and each is a silent correctness failure rather than an error:

The guardrail is emitter-side and must be enforced before span export: on resume, load the persisted span boundary, reattach the new root's parent to the recorded open span, suppress emission for replayed turns, link rather than parent, and assert single-component-per-conversation before flushing. The check below is the minimum that catches the fork.

from dataclasses import dataclass, field
from collections import defaultdict


class TrajectoryForkError(RuntimeError):
    """Raised when a resumed trajectory produces a second causal root
    or a duplicate executed-tool span under one gen_ai.conversation.id."""


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    conversation_id: str
    operation: str
    tool_call_id: str | None = None
    status: str = "UNSET"


@dataclass
class CheckpointBoundary:
    trace_id: str
    open_span_id: str          # span open at checkpoint time = reattachment point
    completed_tool_call_ids: set[str] = field(default_factory=set)


def reattach_on_resume(
    checkpoint: CheckpointBoundary,
    new_root: Span,
    replayed_turns: list[Span],
) -> list[Span]:
    """Reattach a resumed trajectory to its pre-checkpoint span tree.

    Replayed turns must be converted to SpanLinks, not re-emitted as
    executed spans. Returns the spans safe to export.
    """
    if new_root.parent_span_id is not None:
        raise TrajectoryForkError(
            f"resumed root {new_root.span_id} already has a parent; "
            "reattachment must start from a root context"
        )

    # Reattach the resumed root to the span that was open at checkpoint.
    new_root.parent_span_id = checkpoint.open_span_id
    new_root.trace_id = checkpoint.trace_id  # inherit, do not fork trace

    exported: list[Span] = []
    for span in replayed_turns:
        if span.tool_call_id in checkpoint.completed_tool_call_ids:
            # Already executed before checkpoint: must NOT re-emit as executed.
            # Caller converts this to a SpanLink; we refuse to export it.
            continue
        exported.append(span)

    # Guard: single executed span per (conversation, tool_call_id).
    seen: dict[tuple[str, str], int] = defaultdict(int)
    for span in exported + [new_root]:
        if span.operation == "execute_tool" and span.tool_call_id:
            seen[(span.conversation_id, span.tool_call_id)] += 1
    for key, count in seen.items():
        if count > 1:
            raise TrajectoryForkError(
                f"tool_call_id {key[1]} executed {count}x under "
                f"conversation {key[0]}; replay was re-emitted as execution"
            )

    return exported + [new_root]