# What structural signals indicate a broken parent-child span link between an agent's prompt span and its downstream retrieval span **Date of Record:** 2026 November 20 **Scope:** Applies to distributed tracing of agentic RAG pipelines where a single logical turn emits a prompt/generation span and one or more downstream retrieval (tool-call) spans, joined via propagated trace context (W3C `traceparent`/`tracestate` or an equivalent correlation ID). Does not apply to single-process, single-span instrumentation, nor to batch offline eval harnesses that reconstruct traces post-hoc from logs. ## Core Distinction The failure mode is not "the retrieval span is missing." It is that the retrieval span **exists, is well-formed, and is attached to the wrong parent** — or to a parent whose identity is coincidentally identical to the correct one. Trace correlation in agent systems is a *causal* claim ("this retrieval was performed on behalf of that prompt"), but the transport that carries it (context propagation) only carries an *identifier*, and identifiers are cheap to reuse, easy to drop-and-regenerate, and routinely rewritten by middleware that has no concept of agent causality. The non-obvious boundary: a broken link is **indistinguishable from a healthy link at the point of emission**. Both produce a child span with a `parent_span_id` that resolves to *some* span in the same trace. The corruption is only visible structurally — in the shape of the span tree, the timing relationships, and the cardinality of children per parent — not in any single span's fields. Operators who validate "every retrieval span has a parent" pass a pipeline that is silently attributing retrievals to the wrong prompt. ## What Was Observed Across three agent deployments instrumented with OpenTelemetry-style context propagation, the following structural signatures recurred when the prompt→retrieval link degraded: 1. **Orphan re-parenting under async fan-out.** When the agent issues retrieval tool calls from a thread pool or asyncio task that was *spawned before* the prompt span was made current, the child inherits the ambient context of the task-creation site, not the prompt. The retrieval span's `parent_span_id` points at the request-entry span (or the task-runner span), not the generation span. Structurally: the generation span has **zero** retrieval children, while the request-entry span has an implausible number. The trace is a valid tree; the causal edges are wrong. 2. **Context-loss re-roots.** When a tool-call client strips or fails to forward `traceparent` (common in SDKs that build a fresh HTTP client per call, or in retry wrappers that reconstruct the request), the downstream retrieval service starts a **new root trace**. The prompt span and the retrieval span then share no ancestor. This is detectable as a trace-ID mismatch between the generation span and the retrieval span that the agent *believes* it invoked — but only if the agent's own tool-call record retains the intended trace ID. Without that record, the retrieval is simply invisible to the prompt's trace and the turn looks like "the agent answered without retrieving." 3. **ID collision under high-throughput ID generation.** A minority of instrumentations generate span IDs from a truncated hash, a counter reset per worker, or a timestamp+counter scheme. Under concurrency, two distinct spans in the same trace can receive the same `span_id`. The tree then contains a **parent with two parents** (a DAG, not a tree), or a self-referential edge. This is the most dangerous case: the link *resolves*, the causality is *plausible*, and the attribution is *wrong* — a retrieval from turn N is credited to turn N-1's prompt because their span IDs collided. 4. **Retrieval-span fan-in masquerading as fan-out.** When a retrieval service batches multiple agent requests into one backend call and emits a single span, that span carries one `parent_span_id` but was causally driven by several prompts. The trace shows a retrieval child of prompt A that actually served prompts A, B, and C. Structural tell: the retrieval span's start time precedes the prompt span's start time for at least one of the attributed prompts. The common thread: **every signature is a property of the span *graph*, not of any span's payload.** Payload-level validation (does the span have a name, a status, a duration?) passes in all four cases. ## Condition of Validity The structural checks below are only valid when all of the following hold; violating any one makes the diagnostic produce false positives or false negatives: - **One prompt span per logical turn.** If the agent emits multiple generation spans per turn (streaming re-emission, retry-on-generation), the "generation span has zero retrieval children" test fires on the empty siblings. The invariant must be stated over the *turn's designated prompt span*, chosen by an explicit `turn_id` attribute, not by span name. - **Context is propagated by reference, not reconstructed.** If the retrieval client re-derives the trace ID from a request body field rather than from the wire `traceparent`, the link is a *logical* join, not a *causal* one, and the graph-shape tests do not apply — a logical join can be correct while the causal graph is disconnected, and vice versa. - **Span IDs are globally unique within a trace.** The collision test requires that the instrumentation *claims* uniqueness. If the deployment knowingly uses non-unique IDs, the DAG-shape test cannot distinguish collision from legitimate fan-in. - **Clock skew is bounded.** The "retrieval starts before its prompt" test requires that the agent host and retrieval host are NTP-synchronized to within the span durations involved. Unbounded skew makes the test meaningless. When these hold, the graph is a faithful record of causality and the structural signatures are sound. When they do not, the trace is a *narrative* the instrumentation told, not a record of what happened — and must be treated as untrusted for attribution. ## Decision Boundary The boundary between "correlation intact" and "correlation broken" is drawn at the **turn level**, not the span level, and it is a conjunction, not a threshold: - **Intact** iff, for every retrieval span the agent's tool-call log records as belonging to turn T, (a) the retrieval span's trace ID equals the prompt span's trace ID, (b) the retrieval span's `parent_span_id` equals the prompt span's `span_id` *or* an ancestor of the prompt span within the same turn, (c) the retrieval span's start time is within `[prompt.start - skew, prompt.end + skew]`, and (d) no span ID appears more than once in the trace. - **Broken** if any of (a)–(d) fails for any recorded retrieval. A single failure taints the turn's attribution; partial credit is not meaningful because the whole point of the link is to answer "which prompt caused this retrieval," and a wrong answer is not a less-wrong answer. The boundary is deliberately strict on (d): a single ID collision invalidates the entire trace's attribution, because the collision's blast radius is unbounded — you cannot know which of the resolving children are mis-attributed without an independent record. The boundary does **not** require that the retrieval span be a *direct* child of the prompt. An agent that wraps retrieval in a `tool_call` span (prompt → tool_call → retrieval) is intact under (b), because the tool_call is within the turn. Requiring direct parenthood produces false alarms on any non-trivial agent loop. ## Operational Effect When the link is intact, the trace supports the two operations agents actually need: **attribution** ("this answer's evidence came from these retrievals") and **replay** ("re-run this turn's retrieval with the same context"). When broken, both degrade silently: - **Attribution drift.** Retrievals re-parented to the request-entry span get credited to the *session*, not the *turn*. Dashboards show healthy per-session retrieval counts and zero per-turn retrieval counts — a pattern that reads as "the agent isn't retrieving" when it is retrieving fine. Teams chase a phantom retrieval bug for days. - **Replay divergence.** A replay harness that reconstructs the turn from the prompt span's children retrieves *nothing* (zero children) and regenerates an answer without evidence, producing an output that differs from the original for reasons the harness cannot see. The divergence is misdiagnosed as model non-determinism. - **Collision-induced cross-turn contamination.** Under ID collision, turn N's retrieval is credited to turn N-1's prompt. Replaying turn N-1 now includes turn N's evidence — a state-continuity violation that looks like memory bleed but is actually trace corruption. The guardrail is not "validate the span" but "validate the turn's edge set against an independent record." The agent's own tool-call ledger (written before the span is emitted, keyed by `turn_id` + intended `trace_id`) is the only artifact that can adjudicate a disputed edge. Without it, a broken link is structurally suspicious but not provably broken; with it, the check is decidable. ```python from dataclasses import dataclass from typing import Optional class TraceCorrelationError(RuntimeError): """Raised when a turn's prompt-to-retrieval span edges cannot be trusted.""" @dataclass(frozen=True) class Span: trace_id: str span_id: str parent_span_id: Optional[str] name: str start_ns: int end_ns: int turn_id: Optional[str] = None @dataclass(frozen=True) class ToolCallRecord: """Agent-side ledger entry, written before the span is emitted.""" turn_id: str intended_trace_id: str retrieval_span_id: str issued_at_ns: int def verify_turn_correlation( prompt: Span, retrieval: Span, ledger: ToolCallRecord, trace_spans: list[Span], clock_skew_ns: int = 50_000_000, ) -> None: if prompt.turn_id != ledger.turn_id: raise TraceCorrelationError( f"prompt span turn {prompt.turn_id!r} != ledger turn {ledger.turn_id!r}" ) # (a) trace identity must match both the prompt and the agent's intent. if retrieval.trace_id != prompt.trace_id: raise TraceCorrelationError( f"retrieval trace {retrieval.trace_id} != prompt trace {prompt.trace_id}; " "context was re-rooted downstream" ) if retrieval.trace_id != ledger.intended_trace_id: raise TraceCorrelationError( f"retrieval trace {retrieval.trace_id} != intended {ledger.intended_trace_id}; " "context propagation diverged from agent intent" ) # (b) retrieval must descend from the prompt within the same turn. ancestors = _ancestors(retrieval, trace_spans) if prompt.span_id not in ancestors: raise TraceCorrelationError( f"retrieval {retrieval.span_id} not descended from prompt {prompt.span_id}; " f"ancestors={sorted(ancestors)}" ) # (c) timing must be causally consistent within clock skew. if retrieval.start_ns < prompt.start_ns - clock_skew_ns: raise TraceCorrelationError( f"retrieval {retrieval.span_id} starts before its prompt beyond skew; " "suspected fan-in mis-attribution" ) # (d) no span ID may appear twice in the trace. seen: set[str] = set() for s in trace_spans: if s.trace_id != prompt.trace_id: continue if s.span_id in seen: raise TraceCorrelationError( f"duplicate span_id {s.span_id} in trace {s.trace_id}; " "attribution is undecidable under collision" ) seen.add(s.span_id) def _ancestors(span: Span, trace_spans: list[Span]) -> set[str]: by_id = {s.span_id: s for s in trace_spans if s.trace_id == span.trace_id} out: set[str] = set() cur = span.parent_span_id guard = 0 while cur is not None: if cur in out or guard > len(by_id): raise TraceCorrelationError(f"cycle detected walking ancestors of {span.span_id}") out.add(cur) guard += 1 parent = by_id.get(cur) cur = parent.parent_span_id if parent else None return out ```