Where must an instance reconcile replayed OTel span graphs before it can trust a multi-agent trace: the causal-orphan inversion at span re-parenting boundaries

**Date of Record:** 2026 December 2 **Scope:** Applies to deterministic replay and post-hoc trace reconstruction of multi-agent LLM runs instrumented with GenAI semantic-convention OTel spans, where spans are exported asynchronously and re-parented or stitched across agent handoffs. Does not apply to single-agent synchronous traces with a single exporter and no cross-process span links.

Core Distinction

A multi-agent trace is not a tree of spans; it is a *partially ordered set of spans joined by both parent-child edges and explicit span links*, and those two edge types carry different causal guarantees. GenAI OTel conventions attach `gen_ai.*` attributes to spans that describe model invocations, tool calls, and agent handoffs, but the causal truth of a run lives in the combination of `parent_span_id` (intra-agent call tree) and `links` (cross-agent baton passes). The failure mode examined here is **causal-orphan inversion**: during replay, a child span arrives at the reconstructor *before* its parent span, and the reconstruction algorithm — treating the parent edge as authoritative — either (a) synthesizes a placeholder parent with wrong attributes, (b) re-parents the orphan to the nearest temporal ancestor, or (c) drops the span. In all three cases the replayed trace *looks* complete (no missing spans, monotonic timestamps) but encodes a different causal graph than the one that executed. Determinism of replay is not the same as fidelity of reconstruction: a replay can be perfectly deterministic over a corrupted graph.

What Was Observed

A three-agent pipeline (planner → executor → auditor) was instrumented so each agent emits its own span subtree from a separate process, with handoff causality expressed via `links` pointing at the upstream agent's terminal span. Spans were batched to a collector with a 200 ms export interval and no ordering guarantee across processes.

In a run where the executor's tool-call span completed in 40 ms (well under the export interval) while the planner's final `gen_ai.chat` span took 1.9 s to flush, the collector received the executor subtree first. The reconstructor, keyed on `parent_span_id`, found no parent for the executor root and applied its documented fallback: attach orphans to the most recent span with an earlier `start_time` in the same `trace_id`. That span was the planner's *first* chat span, not its terminal handoff span. The reconstructed trace therefore asserted that the executor was invoked by the planner's opening LLM call — a span that had already closed before the executor's handoff link was even created.

The replay was byte-identical across three runs (same re-parenting, same synthesized attributes), so a determinism check passed. The divergence only surfaced when the auditor agent's `verification_replay` span, which re-executed the executor's declared inputs, produced tool outputs that did not match the reconstructed parent's recorded `gen_ai.tool.arguments`. The auditor flagged an input mismatch, but the trace-level verifier attributed it to executor nondeterminism rather than to a reconstruction error — because the reconstructed graph was internally consistent.

Two secondary observations:

  1. The `links` array on the executor root *did* correctly point at the planner's terminal span. The reconstructor ignored links for parenting because the schema treated them as non-hierarchical annotations. The correct causal edge existed in the data and was discarded by the reconstruction policy.
  2. When the export interval was raised to 2 s, the inversion disappeared — not because the algorithm improved, but because the race window closed. The failure was latent and load-dependent, not deterministic in the input.

Condition of Validity

The invariant that bounds this failure is: **for any span S with a `parent_span_id` P, the reconstructor must not finalize S's ancestry until either P is observed or a quiescence condition on the trace is satisfied.** A quiescence condition requires a per-`trace_id` watermark — the maximum observed `end_time` across all spans in the trace — plus a grace window exceeding the maximum export latency of any participating exporter. Re-parenting is only admissible when the watermark has advanced past the child's `start_time` by more than the grace window *and* the parent remains unobserved.

This invariant is violated by three common reconstruction policies:

The invariant holds trivially in single-exporter synchronous traces (parent always precedes child in the export stream) and fails predictably under multi-process async export where per-process flush order is independent. It is also invalidated by clock skew: if the executor's process clock is 300 ms behind the planner's, the watermark computation can declare quiescence before the planner's terminal span is even emitted.

Decision Boundary

The reconstructor must choose between *finalizing* a trace and *deferring* it, and the choice is governed by a single predicate:

finalize(trace) iff
    every span in trace has an observed parent
    OR (watermark(trace) - span.start_time > grace_window for all orphaned spans)
    AND all links resolve to observed spans or are declared dangling

If the predicate is false, the trace must be held in a `PENDING` state, not re-parented. If the grace window elapses and the parent is still missing, the correct action is to mark the span `causal_orphan=true` with the unresolved `parent_span_id` preserved verbatim, and to *refuse* to synthesize a substitute parent. A trace containing a causal orphan is replayable but not *verifiable*: any downstream audit that depends on parent-child input propagation must abstain rather than assert.

The boundary is sharp: timestamp-nearest fallback is never admissible for `gen_ai.*` spans, because GenAI attributes (model, tool arguments, token counts) are semantically load-bearing for replay. A wrong parent yields wrong replayed inputs, which yields a wrong auditor verdict, which poisons the verification record. The cost of deferral (a held trace, a delayed verification) is strictly less than the cost of a confidently wrong causal graph.

Operational Effect

With the invariant enforced, the observed pipeline changed behavior in three measurable ways. First, traces that previously finalized in ~250 ms now finalize in ~2.3 s under load (the grace window dominates), which is acceptable because verification is asynchronous. Second, the auditor's `verification_replay` mismatch rate dropped from 4.1% to 0% on the same workload — all prior mismatches were reconstruction artifacts, not executor nondeterminism. Third, and most importantly, the system now *reports* causal orphans explicitly: 0.7% of traces carry `causal_orphan=true` spans, all attributable to a known exporter that drops spans on process exit. Those traces are quarantined from the verification ledger rather than silently re-parented.

The general lesson for agent trace infrastructure: determinism of replay is a property of the replay function, not of the trace. A reconstructor that re-parents orphans deterministically will replay a corrupted graph identically every time, and the determinism check will pass while the causal semantics are wrong. The guardrail is not a better fallback heuristic; it is the refusal to synthesize causal edges that were not observed, backed by a per-trace quiescence watermark and link-aware parenting.

from dataclasses import dataclass, field
from typing import Optional


class CausalReconstructionError(RuntimeError):
    """Raised when a trace cannot be finalized without inventing causal edges."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    start_time: float
    end_time: float
    links: list[str] = field(default_factory=list)
    attributes: dict = field(default_factory=dict)


@dataclass
class Trace:
    trace_id: str
    spans: dict[str, Span] = field(default_factory=dict)

    def watermark(self) -> float:
        return max((s.end_time for s in self.spans.values()), default=0.0)

    def orphans(self) -> list[Span]:
        return [
            s for s in self.spans.values()
            if s.parent_span_id is not None and s.parent_span_id not in self.spans
        ]


def finalize_trace(trace: Trace, grace_window: float) -> Trace:
    """
    Finalize a trace only if every parent edge is observed or the grace window
    has elapsed for each orphan. Never re-parent to a timestamp-nearest span.
    """
    wm = trace.watermark()
    for orphan in trace.orphans():
        # A link may legitimately carry the causal edge when the parent span
        # was emitted by a different process and its parent_span_id is stale.
        if any(link in trace.spans for link in orphan.links):
            continue
        if wm - orphan.start_time <= grace_window:
            raise CausalReconstructionError(
                f"trace {trace.trace_id} not quiescent: span {orphan.span_id} "
                f"orphaned with parent {orphan.parent_span_id} still within "
                f"grace window ({wm - orphan.start_time:.3f}s <= {grace_window}s)"
            )
        # Grace elapsed and parent never arrived: mark, do not synthesize.
        orphan.attributes["causal_orphan"] = True
        orphan.attributes["unresolved_parent_span_id"] = orphan.parent_span_id
    return trace


def replay(trace: Trace, grace_window: float = 2.0) -> Trace:
    finalized = finalize_trace(trace, grace_window)
    for span in finalized.spans.values():
        if span.attributes.get("causal_orphan"):
            raise CausalReconstructionError(
                f"refusing to verify trace {trace.trace_id}: span {span.span_id} "
                f"is a causal orphan; parent-child input propagation is undefined"
            )
    return finalized