# Which invariants prevent orphaned spans from silently truncating an agent's causal trace across MCP tool calls, A2A handoffs, and memory reads **Date of Record:** 2026 November 29 **Scope:** Applies to multi-hop agent systems where a single logical task is instrumented with distributed traces (W3C `traceparent`/`tracestate`) that span MCP tool invocations, A2A peer handoffs, and memory-store operations. Does not cover single-process, single-LLM-call tracing, nor traces that are reconstructed post-hoc from logs rather than propagated at runtime. ## Core Distinction The failure mode is not span *loss* (a dropped export that a collector retry can recover) but span *orphaning*: a child span that is exported successfully, carries a valid span ID, and is durably stored — yet whose `parent_span_id` points to a span the collector never received, or received under a different trace ID. The trace is *present but discontinuous*. From the collector's perspective nothing errored. From the agent's perspective the causal chain from "user intent" to "memory write that poisoned the next turn" has a missing link, and the missing link is exactly the hop where the failure originated. The distinction that matters operationally: a *dropped* span is a gap you can see (span count mismatch). An *orphaned* span is a gap you cannot see, because the orphan is counted, indexed, and queryable — it just floats. A naive observability dashboard that counts spans per trace will report the trace as complete. The invariant that must hold is not "every span is exported" but "every exported span's parent is co-present in the same trace, or is explicitly declared a root." ## What Was Observed A three-agent pipeline: an orchestrator (A) receives a task, calls an MCP filesystem tool to load context, invokes a memory retrieval service to fetch episodic memory, then hands off to a specialist agent (B) over A2A, which calls its own MCP tool and writes a distilled memory record. Trace context is threaded through `traceparent` headers on every outbound request. On roughly 4% of tasks, the resulting trace in the backend contained A's root span, A's MCP child span, A's memory-read child span, and B's MCP child span — but B's *root* span (the A2A server-side span that should be the child of A's handoff span) was absent, while B's MCP child span was present and correctly parented to B's root span ID. The backend rendered B's MCP span as a floating subtree with a dangling parent. The A2A handoff span on A's side was present and marked `error=false`. The mechanism: the A2A handoff is asynchronous. A emits its handoff span, serializes `traceparent` into the A2A `Task` envelope, and returns control to its event loop *before* B acknowledges. B's server-side span is created only when B's executor dequeues the task. When B's queue depth exceeded a threshold under load, B's span creation was delayed past A's span-export batch flush. A's exporter shipped the batch (including the handoff span) at `end_time + batch_window`. B's span was created later, with a `parent_span_id` referencing A's handoff span — which by then existed in the backend, so *that* link was fine. The actual orphan was different: B's *executor* created a short-lived "dequeue" span as the parent of its MCP span, and that dequeue span was created with `sampled=false` because the sampling decision had been re-derived locally from a truncated `tracestate` that B's SDK could not parse (the `tracestate` exceeded the 512-byte limit after A appended its own vendor key, and B's propagator dropped the whole `tracestate` rather than truncating it). An unsampled parent with a sampled child is precisely the orphan condition: the child is exported, the parent is not. The 4% figure correlated almost exactly with tasks where A's `tracestate` had accumulated four or more vendor entries — i.e., the failure was a *header-size* condition, not a load condition. The load only widened the window in which the orphan was created. ## Condition of Validity This analysis holds only when all of the following are true, and the guardrail below is only sound under the same conditions: 1. Sampling is decided **once** at the trace root and propagated via the `sampled` flag in `traceparent`, not re-derived downstream. 2. `tracestate` is propagated verbatim and **truncated from the right** (dropping vendor entries) when it exceeds the 512-byte W3C limit, never dropped wholesale. 3. The A2A handoff carries the `traceparent` in the task envelope's metadata and the receiving executor **adopts** it as its parent context before creating any span, rather than creating a fresh root. 4. Memory operations are instrumented as child spans of the calling agent's current span, not as independent roots. If condition 1 is violated (per-hop re-sampling), orphans are expected by design and the invariant below will fire on legitimate traces. If condition 2 is violated (wholesale `tracestate` drop), the invariant fires correctly but the fix is in the propagator, not the trace validator. ## Decision Boundary The boundary is between **trusting the collector's span count** and **validating parent co-presence at write time**. A trace with N spans and zero dangling parents is *causally closed*. A trace with N spans and one dangling parent is *causally open* and must be treated as an observability failure even though every individual span is well-formed. The decision rule: on every span export, the exporter (or a collector-side validator) checks whether `parent_span_id` is present in the same trace's span set. If not, and the span is not explicitly marked `is_root=true`, emit a `TraceDiscontinuity` event and **quarantine the trace** — do not let it be counted as complete. Do not attempt to repair by re-parenting to the root; that fabricates causality. The correct action is to surface the discontinuity so the operator knows the causal chain is broken at a specific hop, and to fall back to the A2A envelope's own correlation ID (which is independent of the tracing headers) to reconstruct the link from the transport layer. ## Operational Effect Without the invariant, the pipeline's dashboards reported 99.6% trace completeness and 100% span-export success while 4% of traces were causally broken at the A2A boundary — the exact boundary where handoff state loss occurs. Post-incident reconstruction of a memory-poisoning bug was delayed because the trace showed A's memory read and B's memory write as unrelated subtrees, hiding the fact that B's write was derived from A's read. With the invariant active, the same 4% surfaces as `TraceDiscontinuity` events tagged `hop=a2a_handoff`, and the fix (truncate `tracestate` from the right, adopt parent context in the executor) was localized in one afternoon. The broader operational lesson: trace completeness is a *relational* property of the span graph, not an aggregate property of span counts. Any agent observability system that validates spans individually will report success on a graph that is silently disconnected at exactly the probabilistic, stateful boundaries — A2A handoffs, async memory writes, deferred tool execution — where agent failures actually originate. ```python from dataclasses import dataclass, field from typing import Optional MAX_TRACESTATE_BYTES = 512 class TraceDiscontinuity(RuntimeError): """Raised when an exported span's parent is not co-present in its trace.""" pass @dataclass class Span: trace_id: str span_id: str parent_span_id: Optional[str] is_root: bool = False name: str = "" @dataclass class TraceBuffer: spans: dict = field(default_factory=dict) # span_id -> Span def add(self, span: Span) -> None: self.spans[span.span_id] = span def validate(self, trace_id: str) -> None: members = [s for s in self.spans.values() if s.trace_id == trace_id] ids = {s.span_id for s in members} for s in members: if s.is_root: continue if s.parent_span_id is None or s.parent_span_id not in ids: raise TraceDiscontinuity( f"span {s.span_id} ({s.name}) in trace {trace_id} " f"references missing parent {s.parent_span_id}; " f"causal chain is open at this hop" ) def truncate_tracestate(header: str) -> str: """Drop vendor entries from the right until under the W3C limit. Dropping the whole header (the observed bug) forces downstream re-sampling and orphans the child span. Truncating preserves the sampling decision carried by the root vendor entry. """ if len(header.encode("utf-8")) <= MAX_TRACESTATE_BYTES: return header entries = header.split(",") while entries and len(",".join(entries).encode("utf-8")) > MAX_TRACESTATE_BYTES: entries.pop() if not entries: raise TraceDiscontinuity( "tracestate truncation removed all entries; refusing to drop " "sampling context wholesale" ) return ",".join(entries) def validate_export(buf: TraceBuffer, trace_id: str) -> None: buf.validate(trace_id) ```