# What structural signals indicate trace-context decoherence at MCP transport boundaries: orphaned span parents and the correlation-identity invariant **Date of Record:** 2026 November 24 **Scope:** Applies to multi-hop agent systems where a root trace context (trace_id/span_id, baggage) is propagated across an MCP client→server transport boundary, and where memory operations are instrumented as child spans of the invoking agent turn. Does not apply to single-process agents with no transport hop, nor to systems that regenerate a fresh trace per tool call by design. ## Core Distinction Observability correlation is not the same as observability coverage. Coverage asks: did every hop emit a span? Correlation asks a stricter, structural question: does every emitted span resolve, via its parent reference, to a span that exists in the same trace? A system can have 100% span coverage and 0% correlation integrity—every hop reports, but the reported spans form disconnected forests rather than one tree. The failure is non-obvious because it is silent. Nothing errors. The MCP server returns a valid result, the memory write succeeds, the agent continues. The breakage only manifests downstream, in the trace store, as orphaned parent references—spans whose `parent_span_id` points to a span that was never exported under that `trace_id`. The structural signal is a **parent-reference resolution failure rate** that rises precisely at transport boundaries, not at reasoning boundaries. ## What Was Observed A four-hop agent turn: (1) orchestrator LLM turn opens root span `S0`; (2) orchestrator issues an MCP `tools/call` to a retrieval server; (3) the server performs a memory read, then a memory write, each instrumented as child spans; (4) the server returns results and the orchestrator resumes. The MCP transport layer carries the trace context in the JSON-RPC request `params._meta` (or an equivalent out-of-band header). Three concrete decoherence triggers were observed: - **Header-drop at the transport shim.** The client SDK serialized `traceparent` into `_meta`, but the server-side middleware reconstructed the request context from the JSON-RPC body only, discarding `_meta` before the tracing interceptor ran. The server emitted spans with a freshly minted `trace_id`. Result: a new root, not a child. The orchestrator's `S0` has no descendants; the server's spans form an independent tree. - **Async context-var leak across the memory operation.** The memory-write span was created inside an `asyncio` task spawned by the server's handler. The tracing context lived in a `contextvars.ContextVar` that was set in the request handler but not copied into the spawned task. The write span captured an empty parent and defaulted to a new trace. The read span—created synchronously—correlated correctly. So the *same hop* produced one correlated and one orphaned memory span. - **Span-id reuse under retry.** The client retried the `tools/call` after a timeout, reusing the original `span_id` for the retry. The server, having partially processed the first attempt, had already exported a span with that id under a different parent. The trace store now had two spans claiming the same id with different parents—an ambiguous parent resolution that the backend resolved by keeping the first, silently mis-parenting the retry's memory writes. The common structural signature across all three: **the orphan rate is a step function of hop count, not of token count or reasoning depth.** A ten-step reasoning loop within one process correlates perfectly; a two-hop MCP call with a broken shim correlates zero beyond hop one. ## Condition of Validity The correlation invariant holds only if all of the following are true simultaneously: 1. **Context propagation is total.** Every field required to reconstruct the parent (`trace_id`, `parent_span_id`, and any sampling decision) survives serialization, transport, and deserialization at *every* hop, including through async task boundaries and retry paths. 2. **Span identity is unique per attempt.** A retried request must mint a new `span_id`; reusing the original id under a new parent violates the tree invariant and produces ambiguous resolution. 3. **Parent references are resolvable within the exported set.** A span may only reference a parent that is guaranteed to be exported under the same `trace_id`. If a hop samples out the parent but keeps the child, the child is structurally orphaned regardless of propagation correctness. The invariant is therefore: **for every exported span `s`, `resolve(s.parent_span_id, s.trace_id)` must return exactly one span, or `s` is a root.** Any span that is neither a root nor resolvable is a correlation defect, independent of whether its payload is correct. ## Decision Boundary The operational question is not "is tracing enabled?" but "at which hop does the tree stop being a tree?" The boundary that matters: - **If orphan rate ≤ baseline (single-hop noise) and flat across hop count** → correlation is intact; treat trace as authoritative for causality. - **If orphan rate rises monotonically with hop count, concentrated at transport and async boundaries** → propagation is lossy; the trace is *not* authoritative for cross-hop causality. Do not use it to attribute latency or failures to a specific hop—the parent links are lying. - **If duplicate span ids with divergent parents appear** → the trace store's dedup policy is masking the defect; the retained span may be the wrong attempt. Treat the trace as corrupted for that subtree and fall back to request-id correlation. The decisive signal is the **shape of the orphan-rate curve against hop depth**, not its absolute value. A flat curve at 2% is healthy. A curve that jumps from 2% to 40% between hop one and hop two is a transport-boundary defect even though the absolute number looks tolerable. ## Operational Effect When the invariant is violated, three second-order effects follow, and each is worse than the raw orphan count suggests: - **Latency attribution inverts.** The server's orphaned spans form their own root with its own duration. Aggregation by `trace_id` undercounts end-to-end latency because the transport hop's cost is split across two trees. The orchestrator appears faster than it is; the MCP server appears to be a separate, slow service. - **Memory-operation causality is lost.** A memory write that poisoned a later retrieval cannot be linked to the write span, because the write span is orphaned. Debugging "why did the agent retrieve stale state" becomes impossible from traces alone—the causal edge from write to read is severed at exactly the boundary where it matters. - **Retry storms hide.** Duplicate span ids under divergent parents mean the retry's cost is attributed to the original attempt. A retry loop that doubles server load shows as a single span. The guardrail is a **correlation-integrity check run as a first-class assertion**, not a dashboard. At trace export, reject or flag any span that is neither a root nor resolvable, and any duplicate id with divergent parent. Emit the orphan rate keyed by hop depth; alert on the *derivative* with respect to hop count, not the level. And enforce attempt-unique span ids at the client retry layer, so the tree invariant cannot be violated by a timeout. ```python import hashlib from dataclasses import dataclass, field class TraceCorrelationError(RuntimeError): """Raised when a span cannot be resolved to a unique parent within its trace.""" @dataclass class Span: trace_id: str span_id: str parent_span_id: str | None hop: int name: str @dataclass class TraceStore: spans: dict[str, dict[str, list[Span]]] = field(default_factory=dict) def add(self, span: Span) -> None: self.spans.setdefault(span.trace_id, {}).setdefault(span.span_id, []).append(span) def resolve(self, trace_id: str, span_id: str) -> Span: candidates = self.spans.get(trace_id, {}).get(span_id, []) if not candidates: raise TraceCorrelationError( f"parent {span_id} not exported under trace {trace_id}" ) if len({c.parent_span_id for c in candidates}) > 1: raise TraceCorrelationError( f"ambiguous parent: span {span_id} in trace {trace_id} " f"has {len(candidates)} instances with divergent parents " f"({[c.parent_span_id for c in candidates]})" ) return candidates[0] def orphan_rate_by_hop(self) -> dict[int, float]: totals: dict[int, int] = {} orphans: dict[int, int] = {} for trace_id, by_id in self.spans.items(): for span_id, instances in by_id.items(): for s in instances: totals[s.hop] = totals.get(s.hop, 0) + 1 if s.parent_span_id is None: continue try: self.resolve(trace_id, s.parent_span_id) except TraceCorrelationError: orphans[s.hop] = orphans.get(s.hop, 0) + 1 return {h: orphans.get(h, 0) / totals[h] for h in totals} def assert_correlation_invariant(store: TraceStore, hop: int) -> None: rates = store.orphan_rate_by_hop() base = rates.get(1, 0.0) current = rates.get(hop, 0.0) # Guardrail: alert on derivative w.r.t. hop depth, not absolute level. if current - base > 0.10: raise TraceCorrelationError( f"orphan rate jumped from {base:.2%} at hop 1 to {current:.2%} at hop {hop}; " f"transport-boundary propagation is lossy — trace is not authoritative " f"for cross-hop causality" ) def mint_attempt_span(trace_id: str, parent_span_id: str, attempt: int) -> Span: # Attempt-unique span id: prevents retry from reusing a parent-bearing id. digest = hashlib.sha256(f"{trace_id}:{parent_span_id}:{attempt}".encode()).hexdigest()[:16] return Span(trace_id=trace_id, span_id=digest, parent_span_id=parent_span_id, hop=2, name="mcp.tools.call") if __name__ == "__main__": store = TraceStore() root = Span("t-1", "root0", None, hop=1, name="agent.turn") store.add(root) # Hop-2 span whose transport shim dropped _meta: parent is not exported. store.add(Span("t-1", "srv1", "missing-parent", hop=2, name="memory.write")) assert_correlation_invariant(store, hop=2) # raises TraceCorrelationError ```