# How should an instance reconcile orphaned child spans when an agent's parent context is evicted mid-trajectory **Date of Record:** 2026 November 30 **Scope:** Applies to agents emitting OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.agent.*`, `invoke_agent`, `execute_tool`, `chat`) across multi-step trajectories where the parent span context may be garbage-collected, evicted, or lost before children close. Does not apply to single-shot inference calls with a single root span, nor to trace backends that reconstruct parentage server-side from span IDs alone without requiring context propagation. ## Core Distinction There are two structurally different ways a child span can lose its parent, and only one of them is a bug in the agent: - **Propagation loss** — the parent `SpanContext` (trace_id, span_id, trace_flags) failed to reach the child because the child ran in a separate process, thread pool, or MCP subprocess without the context being injected. This is a transport defect; the parent span still exists and closes normally. - **Parent eviction / early close** — the parent span was ended (or its in-process context dropped) *while children were still open*, because the agent's orchestration loop checkpointed, the trajectory was truncated by a token-budget cutoff, or a supervisor evicted the parent's context to reclaim memory. Here the parent span *did* exist and *did* close, but closed before its children. The second is the non-obvious failure. The OpenTelemetry GenAI conventions assume a span tree closes bottom-up: `execute_tool` children end before the enclosing `invoke_agent` span, which ends before the root `chat` span. When an agent's execution loop violates this ordering — because it checkpoints and resumes, because a sub-agent is reaped, or because the parent context is dropped at a token-budget boundary — the emitted spans are *structurally valid individually* but form a trace where children reference a parent that closed at a timestamp earlier than the children's own end times. Backends that compute span duration from parent-child containment will report negative or zero-duration parents, and waterfall views will render children hanging off a closed parent. ## What Was Observed A planner agent (`invoke_agent`, span A) spawns three `execute_tool` children (spans B, C, D) for parallel retrieval. Mid-trajectory, the agent hits its context-window ceiling and triggers a checkpoint-and-resume: the orchestration loop serializes state, ends span A to flush the partial trajectory to the exporter, and starts a new `invoke_agent` span A' for the resumed segment. Spans B, C, D were still open at the moment A closed — they finish 400–900 ms later and export with `parent_span_id = A.span_id`. Observed at the collector: 1. Span A exports with `end_time` = T. Spans B, C, D export with `start_time` < T but `end_time` > T. The trace assembler sees children that outlive their parent. 2. The resumed span A' carries the *same* `gen_ai.conversation.id` but a new `span_id`, and its children (B', C', D') attach to A'. The trace now has two roots for one conversation: A and A'. Backends that key on `trace_id` alone merge them into one malformed tree; backends that key on `conversation.id` see two disjoint trees. 3. The GenAI attribute `gen_ai.agent.name` is identical across A and A', so any aggregation grouping by agent name double-counts the invocation and splits the tool-call counts across two parents. 4. Because span A ended before B/C/D, the exporter's batch processor — which flushes on span end in completion order — emitted A *before* its children, so any streaming consumer that assumes parent-before-child ordering received the parent first and had to buffer children indefinitely or drop them. The failure is silent: no span is marked error, no exception is raised, `trace_flags` are unchanged. A naive dashboard shows a healthy 100% sampled trace with a slightly odd waterfall. ## Condition of Validity The reconciliation rule below is valid only under these conditions, and must not be generalized past them: - The agent emits GenAI semantic-convention spans with explicit `parent_span_id` set at child creation time, not inferred by the backend. - A checkpoint/resume boundary is identifiable in-band — e.g., a `gen_ai.agent.checkpoint` event or a monotonic `gen_ai.conversation.turn` attribute — so the resumed span can be linked to its predecessor. Without an in-band link, A and A' are genuinely indistinguishable from two independent invocations and must be treated as such. - The exporter is configured for ordered or parent-aware export (e.g., `BatchSpanProcessor` with a parent-completion gate, or an OTLP pipeline that buffers orphans). If the pipeline is fire-and-forget with no ordering guarantee, the orphan window is unbounded and this rule cannot bound it. Outside these conditions — particularly if the backend reconstructs parentage from span IDs and tolerates out-of-order arrival — the correct action is to emit the orphaned children as-is and let the backend stitch, not to rewrite parentage at the agent. ## Decision Boundary The invariant an agent must enforce is **span-tree closure ordering**: a parent span may not end while any child span it created is still open, *unless* the parent explicitly transfers its children to a successor span before ending. The decision boundary is whether the checkpoint is *within* a span's lifetime or *at* its boundary. - If the context cutoff falls strictly between tool calls (no open children), ending A and starting A' is correct and produces a clean two-tree trace linked by `conversation.id`. - If the cutoff falls while children are open, the agent has two lawful options and one unlawful one: - **Lawful: drain.** Block the checkpoint until open children close or hit their own timeout, then end A. Bounds the orphan window to the child timeout. - **Lawful: adopt.** Before ending A, re-parent the still-open children to A' (mutate their `parent_span_id` to A'.span_id and record A as an `gen_ai.agent.predecessor_span_id` attribute). This preserves closure ordering at the cost of mutating a span ID that may already be referenced downstream. - **Unlawful: end-and-orphan.** End A with children open and let them export against a closed parent. This is the observed failure and must be rejected at the emit boundary. The guardrail is a parent-completion gate on the span processor: a span that has registered open children cannot be ended until those children either end or are explicitly adopted. The gate is the architectural invariant; the drain-vs-adopt choice is policy. ## Operational Effect Enforcing the closure-ordering invariant changes three observable properties of the trace: 1. **No negative-duration parents.** Every parent's `end_time` is ≥ the maximum `end_time` of its children, so waterfall and duration aggregations are monotone. This eliminates the class of dashboards that silently drop or clamp negative-duration spans. 2. **Bounded orphan latency.** With the drain policy, the orphan window is at most the child timeout (e.g., 30 s for a tool call); with adopt, it is zero but at the cost of a re-parenting mutation that downstream caches must invalidate. The choice is a latency-vs-mutability trade, not a correctness one. 3. **Deterministic conversation reconstruction.** Because A and A' are linked by `conversation.id` and `predecessor_span_id`, a consumer can reconstruct the full trajectory (A → B,C,D → A' → B',C',D') without guessing from timestamps. Aggregations by `gen_ai.agent.name` must group by `conversation.id` first, then sum across predecessor chains, to avoid double-counting the invocation. The cost of the gate is that a checkpoint can be delayed by up to the child timeout; for agents with long-running tool calls this is the dominant resume latency. Teams that cannot afford the delay must either shorten child timeouts at the checkpoint boundary or accept the adopt mutation and its cache-invalidation burden. ```python from __future__ import annotations import time from dataclasses import dataclass, field from typing import Optional class SpanClosureOrderViolation(RuntimeError): """Raised when a parent span is ended while it still has open children, and no lawful drain-or-adopt transition was performed.""" @dataclass class GenAISpan: span_id: str parent_span_id: Optional[str] operation: str # e.g. "invoke_agent", "execute_tool" conversation_id: str start_time: float = field(default_factory=time.monotonic) end_time: Optional[float] = None predecessor_span_id: Optional[str] = None _open_children: set[str] = field(default_factory=set) def register_child(self, child_id: str) -> None: if self.end_time is not None: raise SpanClosureOrderViolation( f"cannot attach child {child_id!r} to already-ended span {self.span_id!r}" ) self._open_children.add(child_id) def child_closed(self, child_id: str) -> None: self._open_children.discard(child_id) class SpanProcessor: """Enforces the closure-ordering invariant across a checkpoint/resume boundary.""" def __init__(self, child_timeout_s: float = 30.0) -> None: self.child_timeout_s = child_timeout_s self._spans: dict[str, GenAISpan] = {} def open(self, span: GenAISpan) -> None: self._spans[span.span_id] = span if span.parent_span_id and span.parent_span_id in self._spans: self._spans[span.parent_span_id].register_child(span.span_id) def close(self, span_id: str) -> None: span = self._spans[span_id] span.end_time = time.monotonic() if span.parent_span_id and span.parent_span_id in self._spans: self._spans[span.parent_span_id].child_closed(span_id) def checkpoint( self, parent_id: str, successor: GenAISpan, policy: str = "drain", ) -> None: parent = self._spans[parent_id] if parent.end_time is not None: return # already closed; successor just opens fresh if parent._open_children and policy == "drain": deadline = time.monotonic() + self.child_timeout_s while parent._open_children and time.monotonic() < deadline: time.sleep(0.01) if parent._open_children: raise SpanClosureOrderViolation( f"drain timed out for parent {parent_id!r}; " f"{len(parent._open_children)} children still open" ) elif parent._open_children and policy == "adopt": successor.predecessor_span_id = parent_id for child_id in parent._open_children: child = self._spans[child_id] child.parent_span_id = successor.span_id successor.register_child(child_id) parent._open_children.clear() elif parent._open_children: raise SpanClosureOrderViolation( f"ending parent {parent_id!r} with {len(parent._open_children)} " f"open children and no drain/adopt transition (policy={policy!r})" ) self.close(parent_id) self.open(successor) ```