# Which invariants prevent trace-context orphanage when agent hops re-parent spans across MCP and A2A boundaries **Date of Record:** 2026 November 30 **Scope:** Applies to multi-hop agent systems where each LLM-driven hop emits OpenTelemetry spans and propagates W3C `traceparent`/`tracestate` through tool calls (MCP) and peer delegation (A2A). Does not cover single-process instrumentation, nor spans emitted by non-agentic infrastructure (load balancers, queues) that never re-parent. ## Core Distinction There are two ways a trace context can "break" across an agent hop, and only one is a real invariant violation: 1. **Context loss** — the child hop starts a fresh root trace because `traceparent` was dropped. This is loud: `trace_id` changes, the collector sees a new root, and the orphan is visible as a disconnected trace. It is annoying but *detectable*. 2. **Context orphanage** — the child hop *keeps* the incoming `traceparent` but re-parents itself under a span that the parent process has already ended, or under a span whose `span_id` was reused after a checkpoint/resume. The trace *looks* connected (same `trace_id`, valid 16-hex parent) but the parent span is not in the same logical execution epoch. This is the non-obvious failure: the trace is structurally valid and semantically a lie. The distinction matters because the standard W3C validation (well-formed `traceparent`, 32-hex trace-id not all-zero, 16-hex span-id not all-zero, flags byte) passes in both cases. Orphanage is invisible to spec-level validation. ## What Was Observed A three-hop pipeline: orchestrator (hop 0) → retrieval agent over MCP (hop 1) → synthesis agent over A2A (hop 2). Each hop is a separate process with its own LLM loop and its own span lifecycle. Observed failure trace on a resumed task: - Hop 0 starts span `S0` (`span_id=aa..01`), emits `traceparent` `00--aa..01-01`, then **checkpoints and suspends** mid-task. `S0` is ended locally at suspension so the span record is flushed — but the *logical* epoch continues after resume. - On resume, hop 0 re-instantiates its loop and allocates a **new** span `S0'` (`span_id=aa..01` reused because the allocator resets, or `bb..02` — either way, not the same span object that hop 1 saw). - Hop 1, still holding the *pre-suspension* `traceparent` from its last MCP call, resumes its own loop and emits child spans with `parent_span_id=aa..01`. The collector accepts them. They attach to a span that ended minutes ago in a different epoch. - Hop 2 (A2A) receives `tracestate` carrying vendor keys from hop 0's *pre-suspension* context, appends its own, and forwards. The `tracestate` now contains a key/value that hop 0 will never read again — it's a fossil. Result: a single `trace_id` with two disjoint span subtrees stitched at a dangling parent. Latency attribution double-counts the suspension gap; error counts from hop 1's post-resume failures get attributed to a pre-suspension span; root-cause queries that walk "parent → child" hit a span with `end_time < start_time` of its alleged child, which most backends silently accept and most humans misread. The same shape recurs without checkpointing whenever an agent hop performs **retry with a fresh span** but forwards the *original* `traceparent` to downstream tools. The downstream tool's parent is the abandoned attempt, not the live one. ## Condition of Validity The invariant that prevents orphanage is not "propagate `traceparent`." It is: > **A child hop may only parent under a span that is (a) still open in the parent's process, or (b) explicitly tombstoned with a `span_id` that will never be reused, and the child must carry the parent's `epoch_id` in `tracestate` so the collector can reject cross-epoch parenting.** Two conditions make this hold: 1. **Span-id non-reuse across epochs.** The parent must not recycle `span_id` values after a checkpoint/resume or retry. W3C only requires uniqueness within a trace's lifetime; it says nothing about epoch boundaries. A resumed agent that resets its span allocator violates the stronger invariant even though it satisfies the spec. 2. **Epoch tagging in `tracestate`.** A vendor key (e.g., `agentepoch=`) must be set at trace root and propagated unchanged by every hop. On resume, the root sets a *new* `agentepoch` and marks the old one as closed. Any child span whose `parent_span_id` resolves to a span in a different `agentepoch` is a violation the collector can flag deterministically — no heuristics needed. If either condition is absent, the system is in the orphanage-permissive regime and the trace is only *cosmetically* correlated. ## Decision Boundary The boundary is **resume vs. restart**: - **Resume** (same logical task, same causal chain, new process epoch): must preserve `trace_id`, must set a new `agentepoch`, must *not* reuse `span_id`s from the prior epoch, and must re-parent the resumed loop under a fresh span that carries `agentepoch` forward. Children from the prior epoch are tombstoned, not revived. - **Restart** (new task, fresh causal chain): must start a new `trace_id` and must *not* forward the old `tracestate`. Forwarding a dead `tracestate` is the fossil-key failure above. The failure mode emerges precisely when a system does *neither* cleanly: it resumes the task (keeps `trace_id`) but treats the span allocator as restarted (reuses `span_id`s) and forwards pre-suspension `tracestate` (fossils). That combination is the orphanage generator. A second boundary: **A2A handoff must re-sign `tracestate`.** If hop 2 accepts hop 1's `tracestate` without verifying the `agentepoch` is still open, a compromised or stale hop 1 can inject a `tracestate` pointing at a closed epoch, and hop 2's spans will silently orphan. Warrant propagation and trace propagation must share the same epoch check. ## Operational Effect With the invariant enforced, three things become true that were previously false: 1. **Trace-walk queries are total.** Every span's `parent_span_id` resolves to a span in the same `agentepoch`, so parent→child walks never hit dangling parents. Latency and error attribution stop double-counting suspension gaps. 2. **Orphanage is detectable at ingest.** The collector rejects or flags spans whose `agentepoch` differs from their parent's, converting a silent semantic lie into a countable metric (`trace.orphaned_spans`). This is the difference between "we think traces are correlated" and "we can prove a hop's context was valid." 3. **Checkpoint/resume is auditable.** The epoch boundary is explicit, so a resumed task's spans form a second subtree under the same `trace_id` with a clear causal seam — reviewers can see *where* the suspension happened instead of inferring it from a time gap. Without it, telemetry correlation across agent hops is a best-effort heuristic that fails silently under exactly the conditions (long tasks, retries, handoffs) where correlation matters most. ```python from dataclasses import dataclass from typing import Optional import re _TRACEPARENT_RE = re.compile(r"^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$") class TraceContextOrphanageError(RuntimeError): """Raised when a child span would parent under a span from a closed epoch.""" @dataclass(frozen=True) class SpanRef: trace_id: str span_id: str epoch_id: str open: bool class EpochAwarePropagator: """ Enforces: a child may only parent under an OPEN span whose epoch_id matches the epoch_id carried in tracestate. Reused span_ids across epochs and fossil tracestate keys are rejected. """ def __init__(self) -> None: self._open_spans: dict[tuple[str, str], SpanRef] = {} self._closed_epochs: set[str] = set() def register_open(self, ref: SpanRef) -> None: if not ref.open: raise TraceContextOrphanageError( f"cannot register closed span {ref.span_id} as open" ) key = (ref.trace_id, ref.span_id) if key in self._open_spans: raise TraceContextOrphanageError( f"span_id {ref.span_id} reused within trace {ref.trace_id}" ) self._open_spans[key] = ref def close_epoch(self, epoch_id: str) -> None: self._closed_epochs.add(epoch_id) for key, ref in list(self._open_spans.items()): if ref.epoch_id == epoch_id: del self._open_spans[key] def child_parent( self, traceparent: str, tracestate: str, child_epoch_id: str, ) -> SpanRef: m = _TRACEPARENT_RE.match(traceparent) if not m: raise TraceContextOrphanageError( f"malformed traceparent: {traceparent!r}" ) trace_id, parent_span_id, _flags = m.groups() parent_epoch = self._parse_epoch(tracestate) if parent_epoch is None: raise TraceContextOrphanageError( "tracestate missing agentepoch; cannot validate parent epoch" ) if parent_epoch in self._closed_epochs: raise TraceContextOrphanageError( f"parent epoch {parent_epoch} is closed; refusing orphanage" ) if parent_epoch != child_epoch_id: raise TraceContextOrphanageError( f"epoch mismatch: parent {parent_epoch} vs child {child_epoch_id}" ) key = (trace_id, parent_span_id) parent = self._open_spans.get(key) if parent is None: raise TraceContextOrphanageError( f"parent span {parent_span_id} not open in epoch {parent_epoch}; " "span_id likely reused or parent already ended" ) if not parent.open: raise TraceContextOrphanageError( f"parent span {parent_span_id} is tombstoned" ) return parent @staticmethod def _parse_epoch(tracestate: str) -> Optional[str]: for member in tracestate.split(","): member = member.strip() if member.startswith("agentepoch="): return member.split("=", 1)[1] return None ```