# Why does an instance lose trace parentage when a nested agent re-emits its own span context **Date of Record:** 2026 November 28 **Scope:** Applies to multi-agent systems where a parent agent invokes a child agent (or a tool that itself runs an LLM loop) and both layers emit OpenTelemetry-style spans into a shared collector. Does not apply to single-process, single-agent traces with no nested span emission, nor to systems using a single flat span table keyed only by `trace_id`. ## Core Distinction The failure is not "missing spans" and it is not "broken sampling." It is **parentage inversion caused by context re-injection at the agent boundary**. When an agent invokes a sub-agent, two things are true simultaneously: 1. The sub-agent is a *new* execution context — a fresh LLM instance with its own span emitter, its own `trace_id` generation policy, and often its own SDK version. 2. The sub-agent receives the parent's serialized context (task state, memory, and — critically — the W3C `traceparent` header) as *input payload*, not as *ambient process state*. The invariant that observability tooling assumes — *a span's parent is the span active in the caller's execution context at emission time* — holds for in-process instrumentation but silently breaks for cross-agent invocation, because the sub-agent must *choose* whether to adopt the incoming `traceparent` or mint a new one. That choice is made by probabilistic, model-driven, or default-configured code, not by the runtime. ## What Was Observed A three-tier pipeline: `orchestrator → retriever_agent → summarizer_agent`. Each tier is a separate process behind an MCP-style transport. The orchestrator emitted span `orch.dispatch` with `trace_id = T0`, `span_id = S1`. It passed `traceparent: 00-T0-S1-01` in the tool-call arguments. Observed in the collector: - `retriever_agent` emitted `retr.plan` with `trace_id = T0`, `parent_span_id = S1` — **correct**, because the retriever's SDK honored the inbound header. - `retriever_agent` then called `summarizer_agent`, but the summarizer's prompt-injected payload included the *original* task JSON, whose `traceparent` field still read `00-T0-S1-01`. The summarizer emitted `summ.invoke` with `trace_id = T0`, `parent_span_id = S1`. - The `retr.plan → summ.invoke` edge **did not exist**. The summarizer was re-parented to the orchestrator, skipping the retriever entirely. The trace was not broken — it was *flattened*. Every nested invocation collapsed onto the root because each hop reused the stale header from the task payload rather than the header of its immediate caller. In a 40-step run this produced a fan of 40 sibling spans under `S1` instead of a depth-40 chain, and the critical-path latency attribution was off by 6.2×. A second, subtler artifact: the summarizer that *did* correctly re-parent (when the agent framework happened to rewrite the header) produced traces where `summ.invoke` had a `parent_span_id` pointing to a `retr.plan` span that had been **sampled out** by the retriever's tail-based sampler. Result: orphaned spans with a dangling parent reference — valid `trace_id`, unresolvable `parent_span_id`. Trace UIs render these as roots, re-introducing the same flattening through a different path. ## Condition of Validity The correct-parentage invariant holds **only if** all three of the following are enforced at the agent boundary: 1. **Header authority is the caller's live context, not the payload.** The `traceparent` used for a child span MUST be read from the transport envelope at emission time, never from a field inside the task/memory object that may have been carried forward from an earlier hop. 2. **The sub-agent either adopts the inbound context atomically or mints a new `trace_id` with an explicit link.** Partial adoption (adopt `trace_id`, ignore `parent_span_id`) is the exact state that produces flattening. 3. **Sampling decisions are inherited, not re-rolled.** If the parent span is sampled, every descendant span in the same `trace_id` MUST be sampled, or the parent must be emitted as a link-only reference to avoid dangling parents. When any of these is violated — which is the default for most agent frameworks that treat `traceparent` as just another string in the JSON task envelope — parentage is decided by whatever the sub-agent's prompt or default SDK config happens to do. ## Decision Boundary The boundary is: **does the sub-agent construct its span before or after it parses the task payload?** - If it constructs the span from the *transport envelope* (the MCP/A2A message metadata) → correct parentage. - If it constructs the span from the *task payload* (the JSON the LLM was asked to reason over) → stale parentage, because the payload's `traceparent` is a snapshot of whichever ancestor last serialized it, and an LLM-driven agent may copy, mutate, or omit that field non-deterministically. There is a third, worst case: the agent framework auto-instruments the LLM call *and* the tool call, so two spans are emitted — one with the envelope parent (correct) and one with the payload parent (stale). The collector sees both, and the trace graph now contains a *cycle-free but contradictory* DAG: `summ.invoke` has two candidate parents and the UI picks one by timestamp, non-deterministically across runs. The guardrail is a **parentage assertion at emission**: every child span must carry a `parent_span_id` that resolves to a span emitted by the *immediately preceding* hop in the invocation chain, and the emitter must reject (or quarantine) any span whose parent does not match the envelope's `traceparent` span-id. This converts a silent flattening into a loud, catchable fault. ## Operational Effect Without the assertion, the observable symptoms are: - **Latency misattribution** — nested time is charged to the root, so the retriever looks like the bottleneck when it is the summarizer. - **Cost attribution collapse** — token spend per sub-agent cannot be summed per parent because the parent-child edge is gone. - **Replay divergence** — a failed run cannot be reconstructed step-by-step, because the step order is inferred from timestamps rather than parentage, and concurrent sibling spans interleave non-deterministically. - **Silent sampling asymmetry** — the dangling-parent case produces traces that *look* complete but are missing the middle of the chain, and no error is raised. The fix is not better sampling or a bigger collector. It is enforcing that the trace context travels on the **transport envelope** and that the emitter **validates parentage against the live caller context** at span creation. The code below encodes that check as a hard failure rather than a silent re-parent. ```python from dataclasses import dataclass from typing import Optional class TraceParentageError(RuntimeError): """Raised when a child span's parent does not match the caller's live envelope context.""" pass @dataclass class SpanContext: trace_id: str span_id: str sampled: bool @dataclass class EmittedSpan: name: str trace_id: str span_id: str parent_span_id: Optional[str] sampled: bool def emit_child_span( name: str, envelope_traceparent: str, # from transport metadata, NOT the task payload payload_traceparent: Optional[str], new_span_id: str, parent_sampled: bool, ) -> EmittedSpan: """ Emit a child span for a nested agent invocation. Invariant: the parent must be the caller's live envelope context. A payload-carried traceparent is treated as adversarial/stale and rejected if it disagrees with the envelope, because that is the exact condition that produces trace flattening. """ # envelope format: 00--- parts = envelope_traceparent.split("-") if len(parts) != 4 or parts[0] != "00": raise TraceParentageError( f"malformed envelope traceparent: {envelope_traceparent!r}" ) _, trace_id, parent_span_id, flags = parts envelope_sampled = flags == "01" if payload_traceparent is not None: p_parts = payload_traceparent.split("-") if len(p_parts) == 4: payload_parent = p_parts[2] if payload_parent != parent_span_id: # This is the flattening trigger: the payload points at a # grandparent (or root), not the immediate caller. raise TraceParentageError( f"parentage inversion on span {name!r}: envelope parent " f"{parent_span_id} != payload parent {payload_parent}; " f"refusing to re-parent to a stale ancestor" ) if parent_sampled and not envelope_sampled: raise TraceParentageError( f"sampling asymmetry on span {name!r}: parent sampled but " f"envelope flags={flags}; descendant would dangle" ) return EmittedSpan( name=name, trace_id=trace_id, span_id=new_span_id, parent_span_id=parent_span_id, sampled=envelope_sampled, ) def dispatch_to_subagent( subagent_name: str, envelope_traceparent: str, task_payload: dict, new_span_id: str, parent_sampled: bool, ) -> EmittedSpan: payload_tp = task_payload.get("traceparent") # may be stale or absent span = emit_child_span( name=f"{subagent_name}.invoke", envelope_traceparent=envelope_traceparent, payload_traceparent=payload_tp, new_span_id=new_span_id, parent_sampled=parent_sampled, ) # Rewrite the payload so downstream hops cannot resurrect the stale header. task_payload["traceparent"] = f"00-{span.trace_id}-{span.span_id}-{'01' if span.sampled else '00'}" return span ```