# How should an instance reconcile orphaned spans when a sub-agent's trace context is severed mid-call-graph **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that propagates W3C Trace Context (or an equivalent `trace_id`/`span_id`/`parent_span_id` triple) across tool calls and sub-agent invocations, where a sub-agent may be suspended, re-instantiated, or handed off to a different process. Does not apply to single-process, single-hop tool loops where the entire call graph lives in one in-memory tracer. ## Core Distinction The distinction that matters is between **span loss** and **span orphaning**, because they demand opposite remediation and they look identical in a naive trace viewer. Span *loss* is when a span is never emitted — the sub-agent crashed before flushing, the exporter dropped the batch, the process was OOM-killed. The trace is simply shorter than reality. You cannot reconstruct what was never recorded, and the correct response is to treat the gap as an opaque region and widen your uncertainty bounds. Span *orphaning* is subtler and is the actual failure mode here: the child span **is** emitted and **is** exported, but its `parent_span_id` points at a span that exists in a *different* trace, or at a `span_id` that was never minted, or at a span that was minted by an instance that has since been garbage-collected. The child is present in your backend but is unreachable from the root via parent-pointer traversal. It is a real record of real work, disconnected from the causal chain that produced it. The non-obvious part: orphaning is produced *by correct-looking code*. When a sub-agent is invoked, the parent injects its context. When the sub-agent resumes from a checkpoint — a cold start after eviction, a retry after a timeout, a handoff to a fresh worker — it typically re-reads its serialized state and re-emits spans. If the checkpoint captured the *inbound* trace context but the resumed process re-derives a *new* root context (because its tracer was initialized fresh and no `parent` was threaded in), the sub-agent's spans land under a brand-new `trace_id`. The work is fully instrumented. The causal edge is gone. ## What Was Observed A three-hop graph: orchestrator → planner sub-agent (an LLM loop making tool calls) → a `fetch_document` tool that itself invokes a small extraction sub-agent. During a load test, the planner sub-agent hit a 30-second wall-clock timeout on its third reasoning step. The orchestrator's retry policy re-invoked the planner with a checkpoint payload containing the partial scratchpad and the *original* inbound `traceparent` header. The resumed planner emitted spans for steps 1–3 again (replaying from checkpoint) plus steps 4–6. The extraction sub-agent under `fetch_document` emitted its spans correctly. Yet in the trace backend, the extraction spans appeared under `trace_id=B`, while the planner's resumed spans appeared under `trace_id=A`, and the orchestrator's root span was `trace_id=A` with a `parent_span_id` that no longer matched the planner's *first* attempt because that attempt's spans had been emitted under the *pre-timeout* context and were now siblings, not ancestors. Three concrete symptoms, all traceable to one mechanism: 1. **Duplicate causal branches.** The planner's steps 1–3 existed twice: once under the timed-out attempt (orphaned, no live parent because the orchestrator's retry superseded it) and once under the resumed attempt. A naive "count spans" metric doubled the apparent LLM-call cost. 2. **Cross-trace parent pointers.** The extraction sub-agent's `parent_span_id` referenced the `fetch_document` span from the *first* attempt, which lived in the superseded branch. The extraction work was real and correct, but its parent edge pointed into a dead subtree. 3. **Checkpoint replay inflation.** Because the resumed planner re-emitted steps 1–3, the trace showed six reasoning steps where only three distinct decisions were made. Any downstream auditor replaying the trace to verify the agent's decisions would see phantom reasoning. The mechanism is not "the tracer is buggy." The tracer did exactly what it was told: it emitted spans with the parent IDs it was given. The failure is that **the checkpoint serialized the inbound context but not the outbound context lineage**, so on resume the instance could not distinguish "I am continuing span X" from "I am a new root that happens to have X's input." ## Condition of Validity The invariant that must hold for a distributed trace to be a faithful causal record is: > For every emitted span `s`, either `s.parent_span_id` is null (a legitimate root), or there exists exactly one span `p` in the same `trace_id` such that `p.span_id == s.parent_span_id` and `p` was emitted by the process that invoked `s`. Orphaning is precisely the violation where the second clause fails. The condition under which this invariant is *at risk* — and therefore the condition under which any reconciliation logic is valid — is: - **Context is carried across a process/instance boundary** (checkpoint resume, handoff, retry), AND - **The receiving process initializes a fresh tracer** (new `trace_id` root) rather than adopting the serialized inbound context as its parent, AND - **The serialized state includes inbound context but not the outbound `span_id` minted for the in-flight operation.** If any of these three is false, orphaning does not occur and this analysis does not apply. In particular, if the sub-agent is invoked in-process (same tracer, same context) or if the checkpoint never crosses a process boundary, the parent pointers remain intact and you have ordinary span loss at worst. The validity condition also bounds the *fix*: you cannot repair orphaning by post-hoc joining on timestamps or payload hashes. Those heuristics produce false edges when two attempts share an input document. The only sound repair is to make the resumed instance **adopt** the serialized `traceparent` as its parent context and mint *new* child `span_id`s under it, while marking replayed spans with a `replay=true` attribute so auditors can deduplicate. ## Decision Boundary The decision an instance must make on resume is binary and must be made *before* the first span is emitted: - **Adopt** the serialized inbound context as parent (correct when the resumed work is a continuation of the same logical operation — the retry is the same decision, re-attempted). This preserves the causal edge and lets the trace show the retry as a child of the original attempt. - **Fork** into a new root with a `link` (not a `parent`) back to the superseded attempt (correct when the resumed work is a *new* logical operation that merely consumes the prior attempt's output — e.g., a re-plan after a plan was rejected). This is a legitimate root; the `link` records the dependency without falsely claiming descent. The failure is choosing *neither* — initializing fresh and dropping the parent entirely, which is what a naive `tracer.start_span()` on a cold-started process does. The boundary between adopt and fork is: **does the resumed instance's output replace the prior attempt's output, or does it supersede it?** Replace → adopt (same causal unit). Supersede → fork with link (new causal unit that depends on the old). Getting this wrong in the adopt direction produces phantom duplicate reasoning; getting it wrong in the fork direction produces a trace that falsely claims a rejected plan was executed. ## Operational Effect The observable consequence of unresolved orphaning is that **trace-based verification silently over-counts and under-attributes**. Cost dashboards sum duplicated LLM calls. Auditor replays reconstruct decision sequences that include phantom steps, so a replay that "matches" the trace may be matching a fiction. Latency attribution assigns the extraction sub-agent's time to a dead subtree, so the critical path looks shorter than it is. The guardrail is a **resume-time context assertion** enforced at the sub-agent boundary: before emitting any span, the resumed instance must either (a) hold a non-null parent context and emit under it, or (b) explicitly declare itself a root and emit a `link` to the superseded span. A resume that can do neither must fail closed rather than emit an orphan, because an orphan is worse than a gap — a gap is honestly unknown, an orphan is a false causal claim. The following enforces this at the handoff boundary. ```python import uuid from dataclasses import dataclass, field from typing import Optional class OrphanedSpanError(RuntimeError): """Raised when a resumed sub-agent would emit a span with no resolvable parent.""" @dataclass class SpanContext: trace_id: str span_id: str parent_span_id: Optional[str] = None replay: bool = False links: list = field(default_factory=list) @dataclass class Checkpoint: inbound_traceparent: Optional[str] # serialized context of the invoking span outbound_span_id: Optional[str] # span minted for the in-flight op, if any superseded_span_id: Optional[str] # span of the attempt this resume replaces def parse_traceparent(tp: Optional[str]) -> Optional[SpanContext]: if not tp: return None parts = tp.split("-") if len(parts) != 4: return None trace_id, span_id, _flags, _version = parts return SpanContext(trace_id=trace_id, span_id=span_id) def resume_subagent_span( checkpoint: Checkpoint, decision: str, # "adopt" | "fork" ) -> SpanContext: inbound = parse_traceparent(checkpoint.inbound_traceparent) if decision == "adopt": if inbound is None: raise OrphanedSpanError( "adopt requested but checkpoint carries no inbound traceparent; " "refusing to emit an orphan — fail closed instead." ) # Continuation of the same logical operation: child of the inbound span. return SpanContext( trace_id=inbound.trace_id, span_id=uuid.uuid4().hex[:16], parent_span_id=inbound.span_id, replay=checkpoint.outbound_span_id is not None, ) if decision == "fork": # New logical operation that supersedes the prior attempt: new root, # but a link (not a parent) records the dependency on the dead attempt. if checkpoint.superseded_span_id is None: raise OrphanedSpanError( "fork requested but no superseded span recorded; " "cannot distinguish a legitimate new root from a lost parent." ) return SpanContext( trace_id=uuid.uuid4().hex, span_id=uuid.uuid4().hex[:16], parent_span_id=None, links=[checkpoint.superseded_span_id], ) raise OrphanedSpanError( f"unknown resume decision {decision!r}; must be 'adopt' or 'fork'." ) ```