# When must an instance refuse to close a causal span: orphaned parent links under cross-agent context propagation **Date of Record:** 2026 November 25 **Scope:** Applies to multi-agent systems that emit distributed traces (OpenTelemetry-style span trees) where a downstream agent's span declares a `parent_span_id` owned by an upstream agent's execution context. Does not apply to single-process, single-agent instrumentation where parent and child spans share one in-memory context object. ## Core Distinction There are two categorically different notions of "parent" in an agent trace, and conflating them is the root of the failure. A **causal parent** is the span whose execution *actually* produced the inputs the child consumed — the agent turn that emitted the tool call, the retrieval that populated the context window, the handoff that transferred the baton. A **declared parent** is whatever `parent_span_id` the child wrote into its span record at emission time. In a well-behaved synchronous program these are identical by construction. In a multi-agent system they diverge silently, because the declared parent is propagated as *data* (a trace header, a context token, a field in a handoff envelope) across a boundary where the causal chain can be severed, re-rooted, or replayed — while the span record itself is still emitted with full confidence. The boundary failure is this: an agent instance can emit a span that *references* a parent span that either (a) was never durably written, (b) was written by a different trace, or (c) was written but whose causal relationship to the child is false because the context was injected by a non-causal path (retry, replay, cache hit, or adversarial injection). The trace tree assembles without error. The observability backend happily links the child to the parent. The resulting causal graph is *structurally valid and causally wrong*. No invariant at the storage layer catches this; the only place it can be caught is at span-emission time, by the emitting instance, which must decide whether it is entitled to close the span against that parent. ## What Was Observed A three-agent pipeline: a **planner** (P) decomposes a task and dispatches to a **retriever** (R) and a **synthesizer** (S). Context propagation uses a W3C-style `traceparent` header carrying `trace_id` and `parent_span_id`, threaded through the handoff envelope. Each agent wraps its turn in a span. The failure surfaced as a systematic ~4% of traces with a specific shape: S's span declared a `parent_span_id` pointing at a P span, but P's corresponding span was timestamped *after* S's span completed, and in some cases appeared in a *different* trace_id entirely. Root-causing produced three distinct trigger conditions that all present identically in the assembled trace: 1. **Retry re-rooting.** When R timed out and the orchestrator retried the handoff, it reused the *original* `traceparent` header from a dead attempt rather than minting a fresh child context. S consumed the retried payload but inherited a `parent_span_id` belonging to an attempt whose span had been abandoned (never flushed). The declared parent was a span that, from the backend's perspective, never existed — S became an orphan whose parent link dangled. 2. **Cache-hit context transplant.** A semantic cache in front of R returned a previously computed retrieval result. The cached payload carried the *original* caller's `traceparent` embedded in its metadata. S, consuming the cached result, adopted that stale parent context. The causal parent of S's span was a P invocation from a completely different task — a cross-trace contamination that silently merged two unrelated trace trees. 3. **Fan-out join ambiguity.** When P dispatched to R and S concurrently and then joined, the join step re-emitted a span that re-declared the *dispatch* span as its parent rather than the *join* span. Under concurrency the dispatch span had already been closed; the join span declared a parent that had terminated before the join began, producing a child that appears to complete before its parent. In all three, the assembled trace was a valid DAG. The backend's span-linker accepted every edge. The only signal was a soft anomaly (child-before-parent timestamp inversion, or cross-trace parent reference) that a naive dashboard renders as a normal waterfall. The invariant that was missing: **a span may only be closed against a parent whose causal production of the child's inputs is attested by the same execution context that produced the child.** Propagation of `parent_span_id` as opaque data does not carry that attestation. The context token proves *identity of a trace lineage*, not *causality of a specific payload*. ## Condition of Validity The failure is bounded by a precise condition. A declared parent link is causally valid iff all of the following hold at the moment the child span is closed: - **Liveness:** the parent span was durably emitted (or is guaranteed to be, via a write-ahead span buffer) before the child closes. If the parent is abandoned (retry, crash, timeout), the child must not inherit its id. - **Temporal ordering:** `child.start_time >= parent.start_time` and `child.end_time >= parent.start_time`. Child-before-parent is a hard violation, never a clock-skew artifact to be tolerated in agent traces (agent turns are seconds-to-minutes scale; sub-second skew is irrelevant). - **Lineage identity:** the `trace_id` embedded in the propagated context equals the `trace_id` of the payload actually consumed by the child. A cache hit or replay that returns a payload bearing a foreign `traceparent` breaks this. - **Production attestation:** the context token was minted by the *same* execution context that produced the child's inputs. A retry that reuses a dead attempt's token, or a fan-out join that reuses a dispatch token, violates this even when liveness and lineage hold. When any condition fails, the instance is in the orphaned-parent condition and must not emit a causally-linked child span. It must either re-root (emit the child with a synthetic, locally-minted parent that records the true production event, plus a `link` to the intended-but-invalid parent marked as non-causal) or fail closed. ## Decision Boundary The decision the emitting instance must make at span-close time is not "does a parent id exist" but "am I entitled to assert causality to it." The boundary is sharp: - **Re-root, do not drop.** If the declared parent fails liveness or lineage, the child span is still real and must be recorded. Emit it with a fresh local parent span that captures the actual production event (e.g., `cache_hit`, `retry_attempt_2`, `join`), and attach the intended parent as a non-causal *link* annotated `causality=unverified`. Dropping the span loses the observation; keeping the false edge corrupts the causal graph. - **Fail closed on temporal inversion.** A child that completes before its declared parent *starts* is never a benign artifact. Treat it as a propagation bug and raise, because it means the context token was minted out of order — the exact signature of retry re-rooting and fan-out join reuse. Silently re-rooting here would mask the orchestrator bug. - **Never trust a token carried inside a payload.** Context that rides *inside* a cached or retried payload (rather than in the live handoff envelope) is a transplant candidate. The consuming instance must compare the payload's embedded `trace_id` against the live envelope's and reject on mismatch. The boundary is *not* "reject any parent link that can't be verified" — that would drop most legitimate async links. It is "reject the specific combinations (inversion, cross-trace, dead-parent) that are provably non-causal, and downgrade-to-link everything merely unverified." ## Operational Effect Enforcing this invariant changes what the trace tree means. Before: the assembled DAG was a *record of declared links*, and ~4% of edges were false, silently merging unrelated traces and inverting causal order — making latency attribution and failure root-cause actively misleading (a synthesizer that "caused" a planner's delay). After: the DAG is a *record of attested causality*, with unverified relationships preserved as explicit links rather than fabricated edges. Orphaned spans remain visible but are quarantined from causal path analysis. The cost is that dashboards must now handle a two-tier edge model (causal edges vs. unverified links), and the orchestrator's retry/cache/join paths surface as first-class production events rather than invisible context leaks. The benefit is that the one question observability must answer — *which upstream execution actually produced this downstream behavior* — is answerable without a human reconstructing the propagation path by hand. The general principle for agent observability: **context propagation is a claim, not a proof.** The emitting instance is the only party positioned to check the claim against the execution context it actually ran in, and it must do so at span-close, before the false edge is durably written. ```python import time from dataclasses import dataclass from typing import Optional class OrphanedParentError(RuntimeError): """Raised when a span cannot be causally linked to its declared parent.""" pass @dataclass class SpanContext: trace_id: str span_id: str start_time: float end_time: Optional[float] = None @dataclass class ChildSpan: trace_id: str span_id: str start_time: float end_time: float declared_parent: Optional[SpanContext] payload_trace_id: Optional[str] # trace_id embedded in the consumed payload def close_span_causally(child: ChildSpan, live_envelope_trace_id: str) -> str: """ Decide whether `child` may be closed against its declared parent. Returns 'causal' if the edge is attested, 're-rooted' if it must be downgraded to a non-causal link. Raises on provable non-causality. """ parent = child.declared_parent if parent is None: return "re-rooted" # root span, no claim to verify # 1. Temporal inversion is never benign in agent traces -> fail closed. if child.start_time < parent.start_time or child.end_time < parent.start_time: raise OrphanedParentError( f"temporal inversion: child {child.span_id} " f"(start={child.start_time:.3f}) precedes parent {parent.span_id} " f"(start={parent.start_time:.3f}); context token minted out of order " f"(retry re-root or fan-out join reuse)" ) # 2. Liveness: parent must have been durably closed. if parent.end_time is None: raise OrphanedParentError( f"dead parent: {parent.span_id} never closed; " f"child {child.span_id} inherited an abandoned attempt's context" ) # 3. Lineage: payload's embedded trace must match the live envelope. if child.payload_trace_id is not None and child.payload_trace_id != live_envelope_trace_id: raise OrphanedParentError( f"cross-trace transplant: payload trace {child.payload_trace_id} " f"!= live envelope {live_envelope_trace_id}; " f"child {child.span_id} adopted cached/foreign parent {parent.span_id}" ) # 4. Lineage identity between declared parent and child trace. if parent.trace_id != child.trace_id: return "re-rooted" # unverified, preserve as link, do not fabricate edge return "causal" def emit_child_span(child: ChildSpan, live_envelope_trace_id: str) -> dict: verdict = close_span_causally(child, live_envelope_trace_id) if verdict == "causal": return {"span_id": child.span_id, "parent_span_id": child.declared_parent.span_id, "edge": "causal"} # re-rooted: mint a local parent recording the true production event return {"span_id": child.span_id, "parent_span_id": f"local:{child.span_id}:producer", "edge": "causal", "links": [{"to": child.declared_parent.span_id if child.declared_parent else None, "causality": "unverified"}]} ```