# When must an instance refuse to inherit a parent trace ID across a retrieval boundary: span-context aliasing in GenAI observability correlation **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that propagate a single W3C `traceparent` (or equivalent correlation token) across the full pipeline of prompt assembly, retrieval, tool invocation, and decision emission, where the trace ID is treated as the join key for post-hoc observability. Does not apply to systems that assign a fresh trace per span and join via explicit `caused_by`/`parent_span_id` foreign keys with content-addressed references. ## Core Distinction There are two distinct things a correlation ID can mean, and conflating them is the root of the failure: 1. **Causal lineage** — "this retrieval was caused by this prompt, which was caused by this request." A tree. Monotonic, append-only, never reused. 2. **Session/thread identity** — "these events belong to the same logical unit of work." A set. Legitimately shared across many causally-unrelated operations (a resumed checkpoint, a retried tool call, a fan-out sub-agent). A single flat `trace_id` string serves (1) well and (2) badly. The boundary failure occurs when an agent runtime, under retry, checkpoint-resume, or sub-agent fan-out, **reuses the parent trace ID as the join key for a semantically divergent execution branch**. The observability backend then collapses two non-equivalent executions into one trace graph, and every downstream correlation (which retrieval fed which decision, which tool outcome poisoned which reasoning step) becomes structurally ambiguous — silently, because the IDs still "match." The invariant that gets violated: *a trace ID must uniquely identify one causal execution path; any re-execution that can produce different retrieval or tool results must mint a new trace ID and link to the prior one explicitly.* Retries, resumes, and fan-out are re-executions. They are the exact places where the ID gets inherited instead of forked. ## What Was Observed A multi-step agent (plan → retrieve → tool-call → synthesize) was instrumented with a single trace ID minted at request ingress and threaded through every span. During a 6-hour soak, three failure classes produced correlations that *looked* valid but were not: **Case A — Retry aliasing on non-idempotent retrieval.** A vector retrieval span returned HTTP 503; the runtime's retry wrapper re-issued the query under the *same* trace ID and parent span ID. The retry hit a re-indexed shard and returned a different top-k chunk set. The backend now held two `retrieve` spans with identical `(trace_id, span_id)`, different `result_hash`, and no ordering discriminator. Post-hoc query "which chunks informed the final answer" returned the union of both retrievals — a document set the model never actually saw in either attempt. Decision attribution inflated by 40% on affected traces. **Case B — Resume aliasing across a checkpoint.** The agent checkpointed mid-task after tool call #2. On resume (new process, hours later), the runtime restored the trace context from the checkpoint and continued emitting spans under the original trace ID. But the retrieval index had drifted (embeddings re-generated), so the resumed branch's retrieval returned different neighbors than the pre-checkpoint branch would have. The trace graph now interleaved two *different* world-states under one ID, with a wall-clock gap the backend interpreted as "slow tool call" rather than "process boundary + index drift." Latency dashboards were wrong; causal replay was impossible. **Case C — Fan-out collapse.** A supervisor spawned three sub-agents, each inheriting the parent trace ID with only `span_id` differing. Two sub-agents independently retrieved overlapping-but-not-identical context and reached *contradictory* decisions. Because they shared a trace ID, the auditor's "conflicting peer consensus" detector — which keyed on trace ID to group peers — treated them as a single agent that had flip-flopped, rather than two agents that disagreed. The disagreement was masked as nondeterminism. In all three cases the correlation ID was present, well-formed, and passed schema validation. The failure was semantic: the ID asserted a causal identity that the execution did not have. ## Condition of Validity The inherited-trace-ID pattern is only sound when *all* of the following hold for the reused ID: - The re-execution is **deterministic-equivalent** to the original: same prompt bytes, same retrieval snapshot (pinned index version / snapshot ID), same tool versions, same seed. In practice this is almost never true across a resume or a retry against live infrastructure. - **No span under the reused ID can carry a divergent `result_hash`** for a given `(span_id, operation)`. If two spans share an ID and disagree on output, the invariant is already broken. - The consumer of the trace (dashboard, auditor, replay engine) joins on **`span_id` + attempt ordinal**, not on `trace_id` alone. If any consumer collapses by `trace_id`, inheritance is unsafe. When any condition fails — and for retrieval, tool calls, and fan-out it routinely does — the ID must be **forked**: emit a new `trace_id`, record `parent_trace_id` and `fork_reason ∈ {retry, resume, fanout, drift}`, and carry a `snapshot_ref` (index version, tool version tuple, model version) so the two branches are provably non-equivalent rather than accidentally merged. ## Decision Boundary The runtime must decide, at each boundary, between **inherit** and **fork**. The decision is not "is this the same request" (it always nominally is) but "can this branch produce an observation that contradicts the parent branch." Fork when: - Re-entering after any I/O failure, timeout, or 5xx (retry). - Resuming from a checkpoint where wall-clock gap exceeds the retrieval/tool freshness TTL, or where `snapshot_ref` differs from the checkpoint's recorded ref (resume + drift). - Spawning concurrent sub-agents that will independently retrieve or act (fan-out) — concurrency alone is sufficient, because independent retrieval cannot be assumed consistent. - Any tool whose output is non-deterministic (search, code execution, external API) is re-invoked under the same logical step. Inherit only when re-execution is provably snapshot-pinned and the consumer joins on attempt ordinal. The default for retrieval and tool spans should be **fork**, because their outputs are the least deterministic part of the pipeline and the most load-bearing for decision attribution. The boundary is sharp: *correlation IDs may be inherited across pure control-flow; they must be forked across any boundary where a non-deterministic observation enters the trace.* ## Operational Effect Enforcing fork-on-divergence changes three things: 1. **Attribution becomes sound.** "Which retrieval fed this decision" resolves to exactly one retrieval span per branch, because branches are disjoint traces. The 40% inflation in Case A disappears. 2. **Replay becomes possible.** A forked trace with `parent_trace_id` + `snapshot_ref` lets a replay engine reconstruct *which* index version each branch saw. Resume drift (Case B) becomes a first-class, queryable event rather than a latency artifact. 3. **Conflict detection recovers.** Auditor consensus logic keyed on `trace_id` now correctly sees two sub-agents as two peers (Case C), because they no longer share an ID. Disagreement surfaces as disagreement instead of being averaged into phantom nondeterminism. The cost is trace cardinality: fork-heavy workloads multiply trace count by retry/resume/fan-out factor. This is the correct trade — a smaller number of *correct* traces beats a smaller number of *merged, unauditable* ones. The guardrail is that every fork must record its reason and snapshot reference, so the multiplication is explainable rather than noise. The following guard encodes the fork decision and raises when an inherited ID would alias a divergent observation. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class ForkReason(str, Enum): RETRY = "retry" RESUME = "resume" FANOUT = "fanout" DRIFT = "drift" class TraceAliasingError(RuntimeError): """Raised when an inherited trace ID would merge causally divergent branches.""" @dataclass class SnapshotRef: index_version: str tool_version: str model_version: str def differs_from(self, other: "SnapshotRef") -> bool: return self != other @dataclass class SpanContext: trace_id: str span_id: str snapshot: SnapshotRef attempt: int = 0 parent_trace_id: Optional[str] = None fork_reason: Optional[ForkReason] = None @dataclass class BoundaryEvent: kind: str # "retry" | "resume" | "fanout" | "control_flow" snapshot: SnapshotRef wall_clock_gap_s: float = 0.0 enters_nondeterministic: bool = True FRESHNESS_TTL_S = 300.0 def resolve_trace(parent: SpanContext, event: BoundaryEvent) -> SpanContext: """Decide inherit-vs-fork at an execution boundary. Invariant: a trace_id identifies exactly one causal path. Any boundary that can introduce a divergent non-deterministic observation must fork. """ must_fork = ( event.kind in ("retry", "fanout") or (event.kind == "resume" and (event.wall_clock_gap_s > FRESHNESS_TTL_S or event.snapshot.differs_from(parent.snapshot))) or (event.enters_nondeterministic and event.snapshot.differs_from(parent.snapshot)) ) if must_fork: if event.kind == "control_flow" and not event.enters_nondeterministic: # Defensive: pure control flow should never reach here. raise TraceAliasingError( f"fork requested on pure control-flow boundary {event.kind!r}; " "inheritance is valid and forking would fragment the trace" ) reason = _classify(event) return SpanContext( trace_id=_mint(parent.trace_id, reason), span_id=_mint_span(parent.span_id), snapshot=event.snapshot, attempt=parent.attempt + 1, parent_trace_id=parent.trace_id, fork_reason=reason, ) # Inheritance path: only sound for snapshot-pinned control flow. if event.enters_nondeterministic and event.snapshot.differs_from(parent.snapshot): raise TraceAliasingError( "inherited trace would alias a non-deterministic observation " f"under snapshot drift ({parent.snapshot} -> {event.snapshot})" ) return SpanContext( trace_id=parent.trace_id, span_id=_mint_span(parent.span_id), snapshot=parent.snapshot, attempt=parent.attempt, parent_trace_id=parent.parent_trace_id, fork_reason=parent.fork_reason, ) def _classify(event: BoundaryEvent) -> ForkReason: if event.kind == "retry": return ForkReason.RETRY if event.kind == "fanout": return ForkReason.FANOUT if event.kind == "resume": if event.snapshot is not None and event.wall_clock_gap_s > FRESHNESS_TTL_S: return ForkReason.DRIFT return ForkReason.RESUME return ForkReason.DRIFT def _mint(parent_trace_id: str, reason: ForkReason) -> str: # Deterministic-derivation stub; production uses a CSPRNG nonce. return f"{parent_trace_id}::{reason.value}::{id(reason):x}" def _mint_span(parent_span_id: str) -> str: return f"{parent_span_id}/c" ```