# What happens when an instance links child spans to a parent trace after the parent's context has already been evicted **Date of Record:** 2026 November 28 **Scope:** Applies to multi-agent systems that reconstruct causal traces by propagating W3C-style trace context (`trace_id`, `span_id`, `parent_span_id`) across agent handoffs and tool invocations, where span emission is decoupled from span creation and parent context can be evicted from the emitting agent's working memory before the child span is finalized. Does not apply to single-process synchronous tracing where the parent span object is held by reference for the child's full lifetime. ## Core Distinction The distinction that matters is between *span identity* and *span linkage*. A span's identity (`span_id`, attributes, timing) is local to the emitting agent and survives as long as that agent can serialize it. A span's *linkage* (`parent_span_id` pointing at a still-open parent) is a distributed invariant: it is only valid if the parent span is still open in the collector's model at the moment the child arrives, or if the collector can tolerate out-of-order arrival via orphan buffering. Most GenAI semantic-convention implementations conflate the two. They treat `parent_span_id` as a field to be copied from whatever context object the agent happens to be holding, and they assume that context object is authoritative. When an agent's context window saturates, gets compacted, or is checkpointed and resumed, the parent context is frequently dropped from the working set even though the causal relationship it represents is still live. The agent then emits a child span with either a null parent (silently re-rooting the trace) or a stale/incorrect parent (mis-linking the trace). Neither failure raises an error at emission time. The corruption only surfaces at reconstruction, when the causal DAG no longer matches execution order. ## What Was Observed A three-tier agent (planner → executor → verifier) was instrumented with GenAI semantic conventions: each LLM call emitted a span with `gen_ai.system`, `gen_ai.operation.name`, and `gen_ai.usage.input_tokens`; each tool call emitted a child span. Trace context was propagated by injecting the current span's `traceparent` header into the tool-invocation payload. The planner opened a root span `S_root` and delegated to the executor via an A2A message. The executor received `traceparent` carrying `S_root`'s `span_id`, opened `S_exec` as its child, and began a long tool-calling loop. Mid-loop, the executor's context window crossed its compaction threshold. The compaction routine summarized prior turns and — critically — discarded the raw message envelope that carried the original `traceparent`, retaining only a natural-language summary of the task. The executor continued executing tool calls. The next tool call emitted a span. The executor's span-emission wrapper attempted to read `self._parent_context.span_id`. `_parent_context` had been set to `None` by the compaction routine (it was treated as a transient field, not durable state). The wrapper's fallback path — written defensively months earlier — did this: ``` if parent_ctx is None: parent_span_id = current_active_span_id() # returns S_exec's own id ``` The tool span was emitted with `parent_span_id == S_exec`. That is *correct* by accident in the simple case. But the executor had, between compaction and the next tool call, also spawned a nested sub-agent (a retrieval helper) whose own span was open concurrently. `current_active_span_id()` returned the *most recently opened* span in the executor's local registry — the retrieval helper's span — not `S_exec`. The tool span was therefore linked to the retrieval helper, which had already closed. The collector received a child span referencing a parent that had terminated two seconds earlier. At reconstruction, the causal trace showed the tool call as a descendant of the retrieval helper, and the retrieval helper as a sibling of the tool call's true parent. The verifier agent, reading the reconstructed trace to audit whether the executor's tool calls were justified by the planner's instructions, saw the tool call nested under the wrong branch and flagged it as an ungrounded action. The audit failed. No span-level error, no collector warning, no missing-parent alert — the parent `span_id` existed and was well-formed; it was simply the wrong parent. ## Condition of Validity The invariant that was violated: **a child span's `parent_span_id` is valid only if the referenced parent span was open in the collector's model at the moment of child arrival, AND the emitting agent's notion of "current parent" was derived from durable state that survives context compaction, checkpoint/resume, and concurrent span opening.** Both clauses are load-bearing. The first is a collector-side ordering property: if the collector buffers orphans and reconciles them when the parent arrives, out-of-order linkage is recoverable. If the collector drops orphans (the common default — most OTLP backends reject spans whose parent is unknown or already-closed), the linkage is lost and the span is either re-rooted or discarded. The second is an agent-side state property: `parent_span_id` must be sourced from a field that is explicitly marked durable and is re-injected on resume, not from a transient "current span" pointer that any concurrent operation can mutate. The failure is bounded by the following condition of validity: the system remains correct only while (a) no agent holds more than one open child span at a time, OR (b) the parent context is stored in a durable, compaction-surviving field and is never inferred from "most recently active" state. The observed system violated both simultaneously — compaction nulled the durable field, and the fallback inferred from active-span state while a concurrent span was open. ## Decision Boundary The decision boundary is whether to **fail closed on missing parent context** or **infer a parent**. The observed implementation inferred, and inference produced a plausible-but-wrong link that no downstream check could distinguish from a correct one. The correct boundary: when durable parent context is absent at child-span emission, the agent must emit the span as an *explicit orphan* — `parent_span_id = null` plus an attribute such as `gen_ai.trace.parent_context_lost = true` and a `trace_id` carried forward so the span is at least grouped correctly — rather than inferring a parent from ambient state. An explicit orphan is recoverable: the collector can re-attach it by `trace_id` + timestamp ordering, and the auditor can see that linkage was lost rather than silently wrong. An inferred parent is not recoverable, because it is indistinguishable from a real one. The secondary boundary: collectors must be configured to *retain* orphans (buffer by `trace_id`) rather than reject them, and the retention window must exceed the maximum expected parent-close-to-child-arrival skew. In the observed system the skew was ~2s (retrieval helper closed, then tool span emitted), well within any reasonable buffer — but the collector was configured to drop orphans, so the buffer never engaged. ## Operational Effect The operational consequence is that causal trace reconstruction becomes *silently lossy under context pressure*, and the loss is correlated with exactly the runs you most need to audit: long, multi-tool, multi-agent executions that saturate context. Short runs never compact and never exhibit the failure. The failure rate rises monotonically with task length, which means post-hoc audits of the hardest cases are the least trustworthy. The downstream effect compounds: verifier agents that consume reconstructed traces as ground truth for "did the executor do what the planner asked" will produce false audit failures (or, worse, false passes if the mis-linkage happens to place an unjustified call under a permissive branch). Because the mis-linkage is well-formed, no schema validation, no span-level error metric, and no missing-parent alert will catch it. The only detectable signature is a *topological* mismatch: a span whose `parent_span_id` references a span whose end-time precedes the child's start-time by more than the expected propagation skew. That check must be run at reconstruction, not at emission, because at emission the agent does not know the parent's end-time. The guardrail that bounds this: (1) parent context stored in a durable, explicitly-serialized field that compaction and checkpoint routines are forbidden to null without setting a `parent_context_lost` flag; (2) span emission fails closed to explicit-orphan rather than inferring from active-span state; (3) collector configured to buffer orphans by `trace_id` for a window exceeding max propagation skew; (4) reconstruction-time topological validation rejecting spans whose parent end-time precedes child start-time beyond skew tolerance. ```python class TraceLinkageError(RuntimeError): """Raised when a child span cannot be validly linked to a parent.""" pass def emit_child_span(agent_state, span_payload, collector): # Durable parent context; never inferred from active-span registry. parent_ctx = agent_state.durable_parent_context if parent_ctx is None or parent_ctx.get("parent_context_lost"): # Fail closed: emit as explicit orphan, do NOT infer a parent. span_payload["parent_span_id"] = None span_payload["trace_id"] = agent_state.trace_id # grouping preserved span_payload["attributes"]["gen_ai.trace.parent_context_lost"] = True collector.emit_orphan(span_payload) return span_payload parent_span_id = parent_ctx["span_id"] parent_end_time = collector.lookup_end_time(parent_span_id) if parent_end_time is not None: skew = span_payload["start_time"] - parent_end_time if skew > agent_state.max_propagation_skew: # Parent already closed before this child started: mis-linkage. raise TraceLinkageError( f"parent {parent_span_id} closed {skew}s before child " f"{span_payload['span_id']} started; refusing to link" ) span_payload["parent_span_id"] = parent_span_id collector.emit(span_payload) return span_payload ```