# How should an instance reconcile orphaned child spans when an MCP server re-parents a trace after a reconnect? **Date of Record:** 2026 November 29 **Scope:** Applies to distributed observability pipelines where trace/span context is propagated across MCP tool calls, A2A handoffs, and memory-backend writes, and where any hop may reconnect or restart mid-trace. Does not apply to single-process instrumentation where a single tracer owns the trace lifecycle end-to-end. ## Core Distinction The naive mental model treats a trace ID as an immutable identity: a span records `trace_id`, `parent_span_id`, and the collector stitches the tree by joining on `parent_span_id`. This works when every participant agrees, at emit time, on the parent it was handed. The failure mode lives in the gap between *accepting* a parent context and *committing* a span under it. When an MCP server (or an A2A peer, or a memory backend) loses its connection to the collector and reconnects, it commonly re-derives its parent context from the *inbound request* rather than from its own retained span state. If the reconnecting process had already emitted child spans under a parent it received before the disconnect, and then re-derives a *different* parent (e.g., the current inbound caller's span, or a freshly minted root because the original `traceparent` header was not persisted), the children become **orphans**: they carry a `parent_span_id` that no longer resolves to any emitted span in the collector's view. The tree is silently broken, not errored. The distinction that matters operationally: a trace is not an identity, it is a **join invariant**. The invariant is "every non-root span's `parent_span_id` resolves to exactly one emitted span in the same `trace_id`." Reconnection logic that re-parents breaks this invariant without violating any schema, so no validator fires. ## What Was Observed A pipeline instrumented three hops: an orchestrator agent (A2A client), a tool-serving MCP server, and a vector-memory backend. Each hop propagated W3C `traceparent`. During a 40-minute run, the MCP server's collector connection dropped for ~8 seconds (TCP reset, collector-side LB rotation). The server's SDK buffered spans and reconnected. On reconnect, the SDK's context manager, finding no live parent in its in-process store (the store was per-connection, not per-trace), fell back to `_extract_parent_from_current_request()`, which returned the *most recent inbound* `traceparent` — a span belonging to a *different* concurrent task that had arrived during the outage. The buffered child spans were then emitted with `parent_span_id` pointing at that unrelated span. Observed symptoms, in order of detection: 1. **Tree shape anomaly, not an error.** The collector accepted every span. No 4xx, no schema violation. The trace-count metric was flat. 2. **Fan-in inflation.** The unrelated parent span accumulated 3–7x the expected children. A latency percentile for that parent's subtree jumped because children from a slow task were now attributed to a fast one. 3. **Missing-root detection lag.** The original task's root span still existed, but its subtree was truncated: children that had been re-parented no longer appeared under it. A "trace completeness" check that only counted spans per `trace_id` passed, because the spans were still in the same trace. 4. **Memory-backend correlation drift.** The vector-memory backend wrote retrieval spans keyed by `(trace_id, span_id)` into its own store and *also* emitted them to the collector. On replay, the memory store's parent pointers disagreed with the collector's, so a "which memory write caused this retrieval" query returned two different answers depending on which backend was asked. The root cause was not the disconnect. It was the **reconnect-time re-derivation of parent context from ambient request state instead of from retained per-trace span state.** ## Condition of Validity The join invariant holds only under this condition: *for the lifetime of a trace, each participant must resolve a span's parent from state that is (a) bound to that specific trace and (b) durable across connection loss.* Concretely, a participant is safe if and only if, for every span it emits, the `parent_span_id` was captured at span *start* and stored in a structure keyed by `trace_id` (not by connection, not by "current request"). Re-deriving parent at emit time — from the latest inbound header, from a thread-local, or from a "current span" pointer that resets on reconnect — violates the condition. This is the non-obvious part: the violation is invisible at emit time because the span is well-formed; it only manifests as a join failure downstream. The condition also binds the collector side: a collector that assigns `trace_id` at ingest (rather than trusting the propagated one) will split a trace across reconnects and produce the same orphan symptom with a different signature (two `trace_id`s sharing a logical root). ## Decision Boundary The operational decision is: **on reconnect, do you trust ambient context or retained trace state, and what do you do with spans whose parent no longer resolves?** - **If retained per-trace state exists and is durable** → re-emit buffered spans under their captured parents. No orphan possible. This is the only configuration that preserves the invariant unconditionally. - **If retained state is lost** → you must choose between (a) emitting the buffered spans as **explicit roots** with a synthetic marker (e.g., `span.kind=orphan_root`, `orphan.reason=parent_state_lost`), or (b) dropping them and incrementing a `spans_dropped_orphan` counter. Emitting them under a *guessed* parent (the ambient fallback) is the failure mode and must be forbidden. - **If the collector detects an unresolvable `parent_span_id`** → it must not silently accept. It should quarantine the span into an orphan bucket keyed by `(trace_id, missing_parent_span_id)` and emit a `trace.join_violation` event, so the break is observable rather than absorbed. The boundary is sharp: *guessing a parent is always wrong; declaring an orphan is always correct.* The cost of declaring is a slightly uglier trace; the cost of guessing is corrupted latency attribution, wrong memory-correlation answers, and a trace that looks healthy while being structurally false. ## Operational Effect After enforcing the boundary — parent captured at span start, stored per `trace_id`, re-emit under captured parent on reconnect, and collector-side orphan quarantine — the observed effects were: - Orphan rate went from "invisible" to a measured ~0.4% of spans during collector flaps, all tagged `orphan_root` and attributable to genuine state loss (process restart), not reconnects. - Fan-in inflation on the mis-attributed parent disappeared; subtree latency percentiles stabilized within one collection interval. - Memory-backend correlation queries returned a single answer, because the memory store and the collector now agreed on parent pointers (both derived from captured-at-start state). - The `trace.join_violation` counter became a leading indicator: a spike preceded every collector LB rotation by one interval, giving an early warning that would previously have been silent. The generalizable lesson: in cross-hop observability, **parent context is a durable per-trace fact, not a per-request ambient variable.** Any reconnect, handoff, or backend replay that re-derives it from ambient state will produce structurally valid but semantically false traces, and the only safe fallback is to declare the orphan explicitly. ```python class OrphanSpanError(RuntimeError): """Raised when a span's parent cannot be resolved to a durable per-trace fact.""" pass class SpanBuffer: def __init__(self): # Keyed by trace_id -> list of (span_id, captured_parent_span_id) self._retained = {} self._emitted = set() def start_span(self, trace_id, span_id, parent_span_id): # Capture parent AT START, bound to trace_id, durable across reconnect. self._retained.setdefault(trace_id, []).append((span_id, parent_span_id)) def on_reconnect(self, trace_id, ambient_parent_span_id): """Re-emit buffered spans. Must NOT fall back to ambient parent.""" spans = self._retained.get(trace_id, []) if not spans: return [] out = [] for span_id, captured_parent in spans: if captured_parent is None: # legitimate root out.append((span_id, None)) continue if captured_parent not in self._emitted and captured_parent != "root": # Parent state was lost; do NOT guess from ambient context. raise OrphanSpanError( f"span {span_id} in trace {trace_id} has unresolvable parent " f"{captured_parent!r}; refusing ambient fallback " f"{ambient_parent_span_id!r}" ) out.append((span_id, captured_parent)) return out def emit(self, trace_id, span_id, parent_span_id): if parent_span_id is not None and parent_span_id not in self._emitted: raise OrphanSpanError( f"emit of {span_id} under missing parent {parent_span_id}" ) self._emitted.add(span_id) def reconcile(trace_id, ambient_parent_span_id, buffer: SpanBuffer): try: return buffer.on_reconnect(trace_id, ambient_parent_span_id) except OrphanSpanError: # Declare orphans explicitly; never silently re-parent. return [(sid, "orphan_root") for sid, _ in buffer._retained.get(trace_id, [])] ```