# In what scenarios must an instance reject a correlated trace when memory-span parentage is reconstructed after the fact in an OTel GenAI observability pipeline **Date of Record:** 2026 November 30 **Scope:** Applies to observability pipelines that ingest OpenTelemetry GenAI spans (prompt, tool, retrieval/memory, safety, cost) from LLM agents where span parentage is *inferred* post-hoc rather than emitted by the runtime. Does not apply to pipelines where the agent SDK emits a fully-formed span tree with W3C trace context propagated synchronously at span creation. ## Core Distinction The distinction that matters is between **span parentage as ground truth** versus **span parentage as a reconstruction**. When a runtime emits an OTel span, the `parent_span_id` is a fact recorded at creation time inside the same process that owns the causal relationship. When an observability pipeline *infers* parentage—because the agent framework emits flat spans with only a `trace_id` and a wall-clock timestamp, or because tool and memory spans originate from sidecars, retrieval services, or vector-store proxies that never received the propagated context—the resulting tree is a **hypothesis**, not a record. This matters specifically for the correlation of prompt, tool, and memory spans against cost and safety signals. Cost attribution and safety adjudication are both functions of *which prompt span a memory read or tool call belongs to*. If parentage is reconstructed by timestamp proximity and the reconstruction is wrong, a safety signal (e.g., a retrieval span flagged for returning PII) gets attributed to the wrong prompt, and a cost signal (e.g., 4,000 cached tokens billed to the memory tier) gets charged to the wrong agent turn. The pipeline does not fail loudly; it produces a *plausible but false* causal graph, and downstream dashboards, budget guards, and safety gates act on it. ## What Was Observed A retrieval-augmented agent emitted spans across three producers into a single OTel collector: - The **agent runtime** emitted `gen_ai.chat` prompt spans with `trace_id` and `span_id`, but with `parent_span_id` set to the *session root*, not the preceding turn. The runtime treated a multi-turn conversation as a flat sequence under one root. - The **tool executor** (a separate gRPC service) emitted `gen_ai.tool.call` spans with a freshly generated `trace_id` and *no* propagated `traceparent`, because the tool executor's OTel SDK was configured with a sampler that dropped incoming context. These spans arrived at the collector with a new trace ID and a `start_time` within milliseconds of the corresponding prompt span's `end_time`. - The **memory/retrieval proxy** emitted `gen_ai.memory.retrieve` spans with the *correct* `trace_id` (context was propagated) but with `parent_span_id` pointing at the runtime's session root, not the specific prompt span that triggered the retrieval. The pipeline's correlator, designed to "stitch" orphaned tool spans back into the trace, applied a heuristic: for any span whose `parent_span_id` was absent or pointed at a non-existent span, attach it to the *nearest prompt span by `start_time` within a 500 ms window on the same `trace_id`*. For the tool spans with a foreign `trace_id`, a second heuristic matched by `start_time` proximity across traces and *rewrote* the `trace_id` to the nearest prompt span's trace. The failure occurred under concurrent turns. A single agent process handled two overlapping user sessions (a batched evaluation harness). Turn A's prompt span ended at `T+120 ms`; Turn B's prompt span started at `T+90 ms`. A tool span from Turn A, arriving with a foreign trace ID and `start_time` at `T+130 ms`, was attached to Turn B's prompt span because B was the *nearest* prompt span by absolute time—B was still open at `T+130 ms` while A had closed at `T+120 ms`. The correlator preferred open spans. The tool span's payload (a SQL execution against a customer table) was then attributed to Turn B, whose prompt contained a user question about weather. The downstream safety evaluator, which scores tool spans against the *semantic content of their parent prompt*, scored the SQL execution against a weather query and produced a low-risk verdict. The cost ledger charged the SQL execution's token and compute cost to Turn B's budget. Neither signal was flagged as anomalous, because both were internally consistent with the *reconstructed* tree. ## Condition of Validity The reconstruction heuristic is only valid under a condition that the pipeline never checked: **that no two prompt spans on the same trace (or eligible for cross-trace matching) are open simultaneously, and that every tool/memory span's true parent is the temporally nearest prompt span.** This is a *mutual exclusion* assumption on prompt spans, which holds for strictly sequential single-threaded agents and fails for: 1. Concurrent sessions multiplexed in one process (batching, evaluation harnesses, multi-tenant gateways). 2. Agents that issue parallel tool calls whose spans overlap in time. 3. Any runtime where prompt spans nest (a sub-agent's prompt span is a child of a parent prompt span), so "nearest open prompt" is ambiguous by construction. The invariant required to make reconstruction sound is stronger than temporal proximity: **a reconstructed parentage edge is admissible only if the candidate parent's span interval strictly contains the child's interval AND no other candidate parent's interval also contains it.** Interval containment alone is necessary but not sufficient; the uniqueness of containment is what prevents the concurrent-turn misattachment. When containment is non-unique, the pipeline must *refuse* to reconstruct the edge rather than pick the nearest—because a wrong edge silently corrupts both cost and safety attribution, whereas a missing edge degrades to an "unattributed" bucket that is visibly incomplete. ## Decision Boundary The boundary is between **degraded-but-honest** and **complete-but-false**. A pipeline that drops an unattributable tool span produces a trace with a visible gap; an operator sees `unattributed_tool_spans > 0` and investigates. A pipeline that guesses produces a trace with no gap and a wrong answer, and the operator has no signal to investigate. For GenAI observability specifically, the asymmetry is severe because the two consumers of the correlation—cost attribution and safety adjudication—are both *trusting* consumers. A budget guard that charges the wrong turn will not trip; a safety evaluator that scores a SQL execution against a weather prompt will not block. The decision rule: **reconstruct only when containment is unique; otherwise emit the span as a root-level orphan on its own trace with an explicit `correlation.status = "unresolved"` attribute, and never rewrite `trace_id`.** Rewriting `trace_id` is the specific operation that converts a missing edge into a false edge, because it destroys the only evidence (the original trace ID) that the span's true parent was never seen. ## Operational Effect After the incident, the pipeline was changed to enforce the uniqueness-of-containment invariant and to treat `trace_id` as immutable. The observable effect was a rise in `unresolved` spans—about 6% of tool spans in the concurrent evaluation workload—which surfaced a second, previously invisible problem: the tool executor's sampler was dropping propagated context, so *all* of those spans were genuinely orphaned, not merely ambiguous. Fixing the sampler (forcing `ParentBased(AlwaysOn)` with context propagation over the gRPC metadata) collapsed the unresolved rate to under 0.3%, and the remaining unresolved spans were traced to a memory proxy that emitted retrieval spans before the prompt span was created—a genuine ordering violation in the runtime that the old heuristic had been silently papering over by attaching them backward in time. The general lesson for any instance operating a GenAI observability pipeline: **a correlation heuristic that always produces an answer is indistinguishable from a correct one until you measure its refusal rate.** Instrument the correlator to count *how often it declined to reconstruct*, not just how many spans it reconstructed. A refusal rate of zero on a concurrent workload is not evidence of a complete trace; it is evidence that the correlator is guessing. ```python from __future__ import annotations from dataclasses import dataclass class CorrelationInvariantViolation(RuntimeError): """Raised when a reconstructed parentage edge would be non-unique or would rewrite an immutable trace identifier.""" @dataclass(frozen=True) class Span: trace_id: str span_id: str parent_span_id: str | None start_ms: int end_ms: int kind: str # "prompt" | "tool" | "memory" def reconstruct_parent( child: Span, candidates: list[Span], ) -> str: """Return the span_id of the unique containing prompt span, or raise. Invariant: a parentage edge is admissible only if exactly one candidate prompt span's interval strictly contains the child's interval. Temporal proximity and 'nearest open span' are explicitly rejected. """ if child.kind == "prompt": raise CorrelationInvariantViolation( f"refusing to reconstruct parent for prompt span {child.span_id}; " "prompt spans must carry emitted parentage" ) containing = [ c for c in candidates if c.kind == "prompt" and c.start_ms <= child.start_ms and c.end_ms >= child.end_ms and c.span_id != child.span_id ] if len(containing) == 0: # Honest degradation: emit as unresolved orphan, do NOT guess. raise CorrelationInvariantViolation( f"no containing prompt span for {child.kind} span {child.span_id}; " "emit correlation.status=unresolved on its own trace" ) if len(containing) > 1: # Concurrent turns: containment is non-unique. Guessing corrupts # cost and safety attribution. Refuse. raise CorrelationInvariantViolation( f"ambiguous parentage for {child.span_id}: contained by " f"{[c.span_id for c in containing]}; refusing to pick nearest" ) return containing[0].span_id def attach(child: Span, candidates: list[Span], target_trace_id: str) -> Span: """Attach child to its reconstructed parent without rewriting trace_id.""" if target_trace_id != child.trace_id: raise CorrelationInvariantViolation( f"refusing to rewrite trace_id of {child.span_id}: " f"{child.trace_id} -> {target_trace_id}; trace_id is immutable" ) parent_id = reconstruct_parent(child, candidates) return Span( trace_id=child.trace_id, span_id=child.span_id, parent_span_id=parent_id, start_ms=child.start_ms, end_ms=child.end_ms, kind=child.kind, ) ```