# What happens when an instance replays a GenAI trace whose tool-call spans were reordered by the collector's batch exporter **Date of Record:** 2026 November 21 **Scope:** Applies to deterministic replay of agent sessions reconstructed from OpenTelemetry GenAI semantic-convention event logs (spans carrying `gen_ai.*` attributes plus `gen_ai.tool.call` / message events), where spans are exported via an asynchronous batching processor. Does not apply to synchronous exporters that preserve emission order, nor to traces captured with a single-span-per-session custom envelope. ## Core Distinction There are two different things practitioners call "replay." The first is *semantic replay*: feed the recorded prompts and tool outputs back to a model and let it regenerate reasoning; divergence from the original run is expected and is the point. The second is *deterministic replay*: reconstruct the exact causal sequence of model invocations and tool executions so that a verifier can assert byte-equality on inputs and outputs at each step. The boundary failure described here belongs exclusively to the second kind, and the distinction matters because the failure is invisible under semantic replay — the agent still "works," it just silently reorders the world. The specific invariant that breaks: **a GenAI span log is a set of spans, not a sequence of events, and the collector's batch exporter does not guarantee that `start_time_unix_nano` ordering survives the trip to the backend.** Deterministic replay requires a total order over the events that constitute one turn. OTel gives you a partial order (parent/child via `parent_span_id`) plus per-span timestamps, and timestamps from different processes on different hosts are not comparable at the nanosecond resolution the replay engine assumes. ## What Was Observed A single agent session with three tool calls in one turn — `search_docs`, `read_file`, `write_file` — where `write_file` depends on the handle returned by `read_file`. The trace arrived at the backend with all four spans present and all `parent_span_id` values correct. But the batch processor had flushed the `write_file` span in an earlier batch than the `read_file` span, because `write_file` completed fast (cache hit) and the SDK's `BatchSpanProcessor` uses a 512-span queue with a 5-second schedule delay and does not sort by start time on flush. The backend stored them in arrival order. The replay engine, written against the reasonable assumption that "spans come back in the order they happened," reconstructed the turn as: ``` turn[0]: model_call (llm.request) turn[1]: tool_call search_docs turn[2]: tool_call write_file <-- arrived first, replayed second turn[3]: tool_call read_file ``` Replay then executed `write_file` with an unbound file handle. Depending on the tool implementation this either raised (good) or wrote to a default/empty path (bad — silent corruption). The verifier, comparing the replayed tool inputs to the recorded `gen_ai.tool.call.arguments`, found them identical, because the *arguments* were recorded correctly. The bug was in the *order*, and the arguments hash matched. The replay "passed" while producing a different filesystem state than the original run. The tell, when we finally looked, was a timestamp inversion: `write_file.end_time` was earlier than `read_file.end_time` even though `write_file` appeared first in the stored list. The replay engine never checked this because it trusted list order. Two independent ordering signals — list position and timestamps — disagreed, and the engine consumed only one. ## Condition of Validity The failure requires all of the following to co-occur: 1. **Asynchronous batch export** with a queue large enough that spans from one turn land in different batches, or a schedule delay long enough that a fast child span flushes before its slower sibling. 2. **Cross-process or cross-host clock skew** exceeding the inter-span delta, so that `start_time_unix_nano` cannot be used as a tiebreaker without a tolerance window. A 1ms skew is enough when two tool calls are 200µs apart. 3. **A replay engine that treats stored list order as causal order** rather than reconstructing order from `parent_span_id` + a monotonic per-process sequence number, or from a causal vector derived from `trace_id`/`span_id` linkage. 4. **A tool with a side effect whose correctness depends on ordering** — a handle, a lock, a cursor, a write that must follow a read. Pure functions are immune; stateful tools are not. Remove any one and the failure does not manifest. This is why it survives so long in the wild: most test traces are short, single-process, and use pure tools, so the ordering assumption is never stressed. ## Decision Boundary The guardrail is a **replay admission check** that runs before any step is executed, and it must reject the trace rather than guess. The rule: - Build the causal DAG from `parent_span_id` edges. This is authoritative and survives reordering. - For each parent, order children by `(start_time_unix_nano, span_id)` but only *after* verifying that the max `end_time` of any child is ≤ the min `start_time` of the next child within a tolerance equal to the measured clock skew. If the tolerance is exceeded, the trace is **not replayable deterministically** and must be flagged. - Never fall back to list order. If the DAG is incomplete (missing parent span, dropped span), reject — a partial DAG replayed as if complete is exactly the silent-corruption path above. The boundary is: *deterministic replay is admissible only when the reconstructed order is consistent across at least two independent signals (DAG topology and timestamps within skew tolerance).* One signal is not enough. When the signals disagree, the correct action is to fail closed, not to pick the more convenient one. ## Operational Effect On our fleet this check converted a class of silent replay divergences into hard admission failures. Before: ~0.7% of replay sessions produced a final-state hash mismatch with no error, and we spent days attributing them to model non-determinism. After: those sessions are rejected at admission with a `ReplayOrderingError` naming the conflicting spans, and the residual mismatch rate dropped to the level explainable by legitimate sampling non-determinism. The cost is that ~0.4% of traces are now un-replayable and must be re-captured with a synchronous exporter or a session-scoped envelope. That is the correct trade: an un-replayable trace is a known unknown; a silently reordered trace is an unknown unknown that corrupts the verifier's ground truth. The broader lesson for agent systems: **logs are not histories.** A trace is a set with a partial order, and any component that consumes it as a sequence has imported an ordering assumption it did not earn. The same boundary appears in MCP session logs, A2A handoff records, and checkpoint streams — anywhere the transport is allowed to reorder and the consumer is not told. ```python from dataclasses import dataclass, field from typing import Optional class ReplayOrderingError(RuntimeError): """Raised when a GenAI trace cannot be deterministically ordered for replay.""" @dataclass class Span: span_id: str parent_span_id: Optional[str] name: str start_ns: int end_ns: int # arrival order as stored by the backend; NOT causal order stored_index: int = 0 def admit_for_replay(spans: list[Span], clock_skew_ns: int = 2_000_000) -> list[Span]: """ Reconstruct a deterministic execution order from a reordered span set. Fails closed: any inconsistency between DAG topology and timestamps is a rejection, never a guess. clock_skew_ns defaults to 2ms. """ by_id = {s.span_id: s for s in spans} if len(by_id) != len(spans): raise ReplayOrderingError("duplicate span_id in trace; cannot build DAG") # 1. Verify every non-root span has a resolvable parent. for s in spans: if s.parent_span_id is not None and s.parent_span_id not in by_id: raise ReplayOrderingError( f"span {s.span_id} ({s.name}) references missing parent " f"{s.parent_span_id}; DAG is incomplete, replay would be partial" ) # 2. Group children by parent and order by (start_ns, span_id). children: dict[Optional[str], list[Span]] = {} for s in spans: children.setdefault(s.parent_span_id, []).append(s) for parent_id, kids in children.items(): kids.sort(key=lambda k: (k.start_ns, k.span_id)) # 3. Cross-check: consecutive children must not overlap beyond skew. for prev, nxt in zip(kids, kids[1:]): if prev.end_ns - nxt.start_ns > clock_skew_ns: raise ReplayOrderingError( f"siblings under parent {parent_id} violate causal order: " f"{prev.name} ends at {prev.end_ns}, {nxt.name} starts at " f"{nxt.start_ns}, overlap {prev.end_ns - nxt.start_ns}ns > " f"skew tolerance {clock_skew_ns}ns; timestamps and DAG disagree" ) # 4. Emit a topological order; tie-break only by span_id, never list order. ordered: list[Span] = [] def visit(pid: Optional[str]) -> None: for kid in children.get(pid, []): ordered.append(kid) visit(kid.span_id) visit(None) if len(ordered) != len(spans): raise ReplayOrderingError( "cycle or disconnected component in span DAG; trace is not a single " "causal chain and cannot be replayed as one session" ) return ordered ```