# Why does an instance lose parent-child span linkage when an agent span is exported after its tool-call children close under OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 November 25 **Scope:** Applies to single-process or sidecar-exported agent runtimes that emit `gen_ai.*` spans for agent turns and nested tool calls, where the span processor uses a batching exporter and the agent loop is resumable across checkpoint boundaries. Does not apply to synchronous in-memory span processors that flush before the parent span ends, nor to non-GenAI spans without tool-call attributes. ## Core Distinction The failure is not "missing spans" and not "wrong attribute values." It is a **linkage inversion**: a child `gen_ai.tool.call` span is exported with a `parent_span_id` that points to an agent span whose `span_id` was never committed to the exporter because the agent span is still open when the batch flush fires. The child is durable; the parent is not yet durable. Observability backends that reconstruct traces by joining on `parent_span_id` then orphan the child or, worse, attach it to a recycled `span_id` from a previous run. This is distinct from context propagation failure (where the trace context is lost entirely) and from sampling-induced drops (where both parent and child are dropped consistently). Here the child survives and the parent's identity is either delayed, mutated, or reused. ## What Was Observed A resumable agent runtime executed a turn that called three tools. Sequence: 1. Agent span `S_a` opened with `trace_id=T`, `span_id=A1`, `gen_ai.operation.name=invoke_agent`, `gen_ai.agent.name=planner`. 2. Tool span `S_t1` opened with `parent_span_id=A1`, `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=search`. Closed at t+40ms. 3. BatchSpanProcessor hit its `schedule_delay_millis=5000` deadline at t+5000ms. At that moment `S_a` was still open (the agent was awaiting a slow tool). The exporter serialized `S_t1` with `parent_span_id=A1`. `S_a` was not in the batch because it had not ended. 4. The agent checkpointed at t+6100ms, the process was killed by the orchestrator, and a new instance resumed from checkpoint. On resume the runtime re-opened the agent span as `S_a'` with a **new** `span_id=A2` (the previous `span_id` was not part of the checkpoint), still `trace_id=T`. 5. `S_t2` and `S_t3` were emitted with `parent_span_id=A2`. 6. `S_a'` ended and was exported with `span_id=A2`. Result in the backend: trace `T` contains `S_t1` (parent `A1`, dangling), `S_t2` and `S_t3` (parent `A2`), and `S_a'` (span `A2`). The trace is internally inconsistent: one tool call is orphaned, two are attached, and the agent span's `start_time` is later than `S_t1`'s `end_time` despite `S_t1` claiming to be its child. Dashboards computing "tool calls per agent turn" report 2, not 3. Latency attribution undercounts the turn by the pre-checkpoint duration. A second, sharper case: after ~14,000 turns the runtime's `span_id` generator (a 64-bit random per the OTel spec) produced a collision with a stale `A1` from a prior run still present in a 30-day retention window. `S_t1` from run N+1 was joined to `S_a` from run N. The trace appeared complete and plausible. No error was raised anywhere. ## Condition of Validity The invariant that must hold for trace reconstruction is: > For every exported span `c` with `parent_span_id = p`, there exists an exported span `s` with `span_id = p`, `s.start_time <= c.start_time`, `s.end_time >= c.end_time`, and `s.trace_id = c.trace_id`, and `p` is unique within the trace's retention horizon. This invariant is violated whenever any of the following hold: - **Asynchronous export with open parents.** BatchSpanProcessor (or any deferred exporter) can emit children before parents. OTel permits this; backends that require parent presence at ingest will drop or orphan. - **Checkpoint does not persist span identity.** If `span_id`, `trace_id`, and `start_time` of the open agent span are not part of the checkpoint record, resume necessarily mints a new identity, breaking the `parent_span_id` join for already-exported children. - **`span_id` reuse across runs.** 64-bit random IDs are not collision-free at scale; a 30-day window with high turn rates makes reuse non-negligible and silently mis-joins traces. The invariant *does* hold when the exporter flushes parents before children (synchronous processor), when checkpoints carry the full span context, or when the backend tolerates orphaned children and the agent span's identity is stable across resume. ## Decision Boundary The boundary is not "batch vs. simple processor." It is **whether span identity is part of the durable agent state**. Two admissible architectures: - **Identity-in-checkpoint.** Persist `(trace_id, span_id, start_time, attributes)` of every open span in the checkpoint. On resume, re-open the span with the *same* `span_id` and original `start_time`; the exporter treats it as a continuation. Children exported before the checkpoint join correctly. Requires the backend to accept a span whose `end_time` arrives in a later batch than its children's — most do, but some reject out-of-order ingest. - **Identity-fenced export.** Force a flush of the agent span's *start* record (a synthetic zero-duration "span-start" event or a `span_link` to a stable `run_id`) before any child is exported, and emit children as `span_link`-attached to `run_id` rather than `parent_span_id`-attached to a volatile `span_id`. The backend joins on `run_id`, which is checkpointed. This trades strict parent-child semantics for link semantics. The boundary decision: if the agent loop is resumable, **you cannot rely on `parent_span_id` alone**. Either checkpoint the span identity or move the join key to a durable `run_id` carried as a span attribute and `span_link`. ## Operational Effect With the naive configuration (batch exporter, no identity in checkpoint, random `span_id`): - Orphan rate rises with tool-call latency variance: turns with a tool call exceeding `schedule_delay_millis` orphan exactly that tool span. Measured ~0.7% of turns at p99 tool latency 6s and 5s batch delay. - Resume events multiply orphans by the number of pre-checkpoint tool calls (observed 1–3 per resume). - `span_id` collision produces silent mis-joins at a rate consistent with birthday bounds over the retention window; undetectable without a backend-side uniqueness check. - Downstream metrics (`gen_ai.tool.call` count per `invoke_agent`, turn latency, error attribution) drift low by the orphan fraction, and drift *high* on collision-affected traces where a stale parent's duration is inherited. Guardrail: a validator at export time that rejects (or flags) any `gen_ai.tool.call` span whose `parent_span_id` is not resolvable within the same trace and whose `start_time` precedes the parent's `start_time`. Combined with checkpointed span identity, this bounds the orphan rate to zero for resumable runtimes. ```python import time from dataclasses import dataclass, field from typing import Dict, Optional class SpanLinkageError(RuntimeError): """Raised when a GenAI span's parent linkage cannot be satisfied.""" pass @dataclass class Span: trace_id: str span_id: str parent_span_id: Optional[str] operation: str start_time: float end_time: Optional[float] = None attributes: Dict[str, str] = field(default_factory=dict) class TraceRegistry: """In-memory stand-in for a trace backend that joins on parent_span_id.""" def __init__(self) -> None: self._spans: Dict[str, Span] = {} def ingest(self, span: Span) -> None: if span.span_id in self._spans: raise SpanLinkageError( f"span_id collision: {span.span_id} already present in trace " f"{self._spans[span.span_id].trace_id}; refusing silent mis-join" ) self._spans[span.span_id] = span def validate_linkage(self, child: Span) -> None: if child.parent_span_id is None: return parent = self._spans.get(child.parent_span_id) if parent is None: raise SpanLinkageError( f"orphan: {child.operation} span {child.span_id} references " f"parent {child.parent_span_id} not present in trace {child.trace_id}" ) if parent.trace_id != child.trace_id: raise SpanLinkageError( f"cross-trace link: {child.span_id} -> {parent.span_id}" ) if parent.start_time > child.start_time: raise SpanLinkageError( f"temporal inversion: parent {parent.span_id} starts " f"{parent.start_time} after child {child.span_id} starts {child.start_time}" ) if parent.end_time is not None and parent.end_time < child.end_time: raise SpanLinkageError( f"parent {parent.span_id} ends before child {child.span_id}" ) def export_tool_call( registry: TraceRegistry, trace_id: str, parent_span_id: str, tool_name: str, duration_ms: int = 40, ) -> Span: now = time.monotonic() child = Span( trace_id=trace_id, span_id=f"t-{tool_name}-{int(now * 1000)}", parent_span_id=parent_span_id, operation="execute_tool", start_time=now, end_time=now + duration_ms / 1000.0, attributes={ "gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": tool_name, }, ) registry.ingest(child) registry.validate_linkage(child) return child def resume_agent_span( registry: TraceRegistry, trace_id: str, checkpointed_span_id: Optional[str], ) -> Span: if checkpointed_span_id is None: raise SpanLinkageError( "checkpoint did not persist open agent span_id; resume would mint a " "new identity and orphan previously-exported tool-call children" ) existing = registry._spans.get(checkpointed_span_id) if existing is not None: return existing span = Span( trace_id=trace_id, span_id=checkpointed_span_id, parent_span_id=None, operation="invoke_agent", start_time=time.monotonic(), attributes={"gen_ai.operation.name": "invoke_agent"}, ) registry.ingest(span) return span ```