# Which invariants prevent trajectory-replay divergence when GenAI semantic-convention exporters lose span parentage across a mid-run trace-flush boundary **Date of Record:** 2026 November 28 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for trajectory replay and incident forensics, specifically when the exporter batches spans and the collector or SDK performs a mid-run flush, partial drop, or reordering. Does not apply to synchronous single-span tracing, or to runtimes that write trajectory records directly to durable append-only storage without an OTel export hop. ## Core Distinction A GenAI trajectory is not a log stream; it is a *causal tree* whose forensic value depends on the parent-child edges between `invoke_agent`, `chat`, `execute_tool`, and `retrieval` spans being reconstructable *after* the fact. The distinction that matters here is between **span completeness** (every span arrived) and **edge integrity** (every span arrived with a resolvable parent). Exporters are typically tuned for completeness—retry queues, batch sizing, drop counters—and almost never for edge integrity. A flush boundary can deliver 100% of spans and still yield a trajectory that replays as a forest of orphans, because parent spans and child spans land in different export batches, and the child batch is emitted before the parent's `SpanContext` has been persisted to the exporter's local state. The invariant under examination is the **parent-before-child emission order across flush boundaries**, which the OTel spec permits exporters to violate and which GenAI trajectories make catastrophic because a single orphaned `execute_tool` span detaches the tool call from the reasoning step that produced it. ## What Was Observed During a post-incident replay of a 47-step agent run, the forensic tool reconstructed 46 spans but produced a trajectory graph with 11 disconnected components. The run had terminated with a wrong-answer outcome after a `execute_tool` call returned a truncated JSON payload that the agent misparsed. The replay could not attribute the malformed tool output to the `chat` span that emitted the tool-call arguments, because that `chat` span's `parent_span_id` pointed to an `invoke_agent` span that had been *dropped*—not delayed—by the batch exporter. The mechanism: the SDK's `BatchSpanProcessor` was configured with `max_export_batch_size=512` and `schedule_delay_millis=5000`. The `invoke_agent` root span was created at t=0 and remained open for the full 41-second run. Its `SpanContext` was therefore *never enqueued* until the span ended. Child `chat` and `execute_tool` spans ended and were enqueued immediately, and the 5-second scheduler flushed them in batches while the root was still live. When the process was killed by the incident's OOM condition at t=41s, the in-flight root span was lost along with its `SpanContext`, while all children had already been exported. The collector received children whose `parent_span_id` referenced a `trace_id`/`span_id` pair it had never seen. The replay tool, encountering an unresolvable parent, promoted each orphan to a root—silently, without a forensic marker. A second, subtler observation: span *reordering* within a batch. Because `execute_tool` spans ended before their sibling `chat` spans (tool execution overlapped with the next model call in a pipelined runtime), the exported order was `execute_tool`, then `chat`. A replay tool that reconstructs edges by assuming "the most recent open span is the parent" (a common heuristic when `parent_span_id` is absent) mis-attributed the tool call to the *previous* turn's `chat` span, producing a plausible but false causal chain. The forensic report initially blamed the wrong reasoning step. ## Condition of Validity The parent-before-child invariant holds for replay only under the conjunction of three conditions, any of which can be violated independently: 1. **Parent liveness bound:** every span's `SpanContext` is durably persisted to the export path *before* any child span is enqueued. This requires the exporter to emit a "span started" record (or a `SpanContext` reservation) at span *start*, not at span *end*. The default `BatchSpanProcessor` violates this by design—it only sees a span at `on_end`. 2. **Ordering preservation:** the export path preserves enqueue order per `trace_id`, or the replay tool does not rely on order to infer edges. OTel's batch processor does not guarantee cross-batch ordering under concurrent export workers. 3. **Orphan detection:** the replay tool distinguishes "parent intentionally absent" (a root span) from "parent unresolvable" (a dropped or lost span). This requires an explicit `parent_absent_reason` field or a sentinel `span_id`, which the GenAI semantic conventions do not currently mandate. The invariant is *only* valid when the replay tool treats an unresolvable `parent_span_id` as a hard forensic fault, not as a promotion-to-root. Silent promotion is the failure amplifier: it converts a detectable data-loss event into an undetectable wrong-causality event. ## Decision Boundary The boundary is between **lossy-but-honest** and **complete-but-lying**. An exporter that drops the root span and *marks* the children as `orphaned: true` yields a replay that knows it is incomplete and can refuse to attribute causality. An exporter that drops the root and lets children export with dangling parent references yields a replay that appears complete (all spans present) but attributes tool effects to the wrong reasoning step. The decision rule for the runtime architect: - If `schedule_delay_millis` × (expected span rate) can exceed `max_export_batch_size` while a root span is open, the exporter *will* emit children before the root. Bound this by either (a) forcing a `SpanContext` reservation at span start, or (b) configuring the replay tool to quarantine any `trace_id` with a missing root rather than replay it. - If the runtime pipelines tool execution with model calls (so sibling spans end out of causal order), the replay tool must reconstruct edges *exclusively* from `parent_span_id`, never from temporal adjacency. Any heuristic that infers parentage from "most recent open span" is invalid under pipelining and must be disabled. The guardrail is a **replay admission check**: before any trajectory is admitted to forensic analysis, verify that every non-root span's `parent_span_id` resolves within the same `trace_id`, and that the count of root spans per trace is exactly one. If not, the trace is `QUARANTINED_INCOMPLETE` and causality claims are suppressed. ## Operational Effect With the admission check in place, the 47-step run above would have been quarantined at replay time with a precise fault: `trace_id=... missing root span_id=... (invoke_agent, started t=0, never exported)`. The forensic team would have known immediately that the tool-output attribution was unavailable, rather than spending two days chasing a false causal chain. The cost is that ~3–7% of traces in pipelined runtimes get quarantined under default batch settings; the mitigation is to raise `schedule_delay_millis` above the p99 root-span duration, or to emit a lightweight `span_start` event at reservation time so the collector can synthesize a placeholder root. The invariant that prevents replay divergence is not "export all spans"—it is "never let a child span outlive its parent's `SpanContext` in the export path, and never let an unresolvable parent be silently promoted to root." ```python from dataclasses import dataclass, field from typing import Optional class ReplayAdmissionError(RuntimeError): """Raised when a trajectory cannot be safely replayed for forensics.""" pass @dataclass class Span: trace_id: str span_id: str parent_span_id: Optional[str] name: str start_ns: int end_ns: Optional[int] = None def admit_trajectory(spans: list[Span]) -> dict[str, list[Span]]: """ Reconstruct causal edges ONLY from parent_span_id. Reject any trace with an unresolvable parent or multiple roots. Never infer parentage from temporal adjacency (pipelined runtimes break that). """ by_trace: dict[str, list[Span]] = {} for s in spans: by_trace.setdefault(s.trace_id, []).append(s) admitted: dict[str, list[Span]] = {} for trace_id, group in by_trace.items(): ids = {s.span_id for s in group} roots = [s for s in group if s.parent_span_id is None] dangling = [s for s in group if s.parent_span_id is not None and s.parent_span_id not in ids] if dangling: missing = {s.parent_span_id for s in dangling} raise ReplayAdmissionError( f"trace {trace_id} has {len(dangling)} orphaned span(s); " f"unresolvable parent_span_id(s)={sorted(missing)}. " f"Refusing to promote orphans to root; causality suppressed." ) if len(roots) != 1: raise ReplayAdmissionError( f"trace {trace_id} has {len(roots)} root spans; expected exactly 1. " f"Root span may have been dropped mid-run (check batch flush boundary)." ) admitted[trace_id] = group return admitted def replay_step(admitted: dict[str, list[Span]], trace_id: str, span_id: str) -> Span: group = admitted.get(trace_id) if group is None: raise ReplayAdmissionError(f"trace {trace_id} not admitted; cannot replay step {span_id}") for s in group: if s.span_id == span_id: return s raise ReplayAdmissionError( f"span {span_id} absent from admitted trace {trace_id}; " f"replay would fabricate causality — aborting." ) ```