# Why does an instance replay a multi-agent run to a different verdict: non-commutative span reordering in OpenTelemetry GenAI graph reconstruction **Date of Record:** 2026 November 24 **Scope:** Applies to counterfactual debugging and deterministic replay of multi-agent runs reconstructed from OpenTelemetry GenAI span graphs (span attributes `gen_ai.*`, parent/child span links, and cross-agent `trace_id`/`span_id` references). Does not apply to single-agent linear traces, nor to runs where the trace backend preserves a total order via monotonic sequence IDs and the replay engine honors them. ## Core Distinction A trace is not a program. The OTel GenAI span graph records *what happened* as a set of causally-linked observations with wall-clock timestamps and parent pointers; it does **not** record the *serialization order* in which concurrent agent operations actually touched shared state. Replay engines that rebuild execution order by sorting siblings on `start_time_unix_nano` therefore assume a total order that the trace never guaranteed. When two sibling spans (e.g., two tool-call spans emitted by a fan-out coordinator, or an auditor span and a producer span racing on the same scratchpad) share a timestamp at the collector's clock resolution, or arrive out of order due to per-span export batching, the sort is *stable but arbitrary*. Replaying the reconstructed graph then executes a different interleaving than the one that produced the original verdict. The failure is not nondeterminism in the LLM—the model is seeded and temperature-zero—it is nondeterminism introduced by the *graph-to-schedule* projection step. Counterfactual debugging inherits this silently: you flip one span's output, replay, and attribute the changed verdict to your intervention when the verdict actually flipped because the sibling sort order changed. ## What Was Observed A three-agent run: a `planner` span fans out to two `executor` children (`exec-A`, `exec-B`) that both write to a shared `workspace` resource, followed by an `auditor` span that reads the workspace and emits a pass/fail verdict. The trace exported cleanly. Both executor spans carried `start_time_unix_nano` values differing by 41 microseconds—below the 100µs resolution of the batch exporter's timestamp normalization, so both were quantized to the same tick. On the original run, the auditor verdict was `FAIL` (exec-B's write landed after exec-A's, clobbering a field exec-A depended on). During counterfactual replay, the engine reconstructed sibling order with `sorted(children, key=lambda s: s.start_time_unix_nano)`. Python's sort is stable, so ties break on *list insertion order*—which is the order spans were appended from the export batch, not the order they executed. The batch happened to deliver exec-B before exec-A on replay. The reconstructed schedule therefore ran B-then-A, the clobber never occurred, and the auditor returned `PASS`. The engineer's intervention was a no-op attribute change on the planner; the verdict flip was entirely an artifact of tie-breaking. The counterfactual conclusion ("planner prompt tweak fixes the race") was false. The second-order observation is worse: the replay engine reported *deterministic success*. Re-running the same replay produced `PASS` every time, because the export batch order was cached. Determinism of the replay was mistaken for fidelity to the original run. The engine was deterministically reproducing the *wrong* interleaving. ## Condition of Validity Replay-fidelity holds only when the reconstructed schedule is a linearization consistent with the trace's *happens-before* relation, not merely a timestamp sort. The trace carries a partial order via parent/child pointers and explicit span links; it does **not** carry the total order among concurrent siblings unless the instrumentation emits it. The invariant required is: > For any two spans A, B with no happens-before edge between them, the replay engine must treat their relative order as *unconstrained*, and must either (a) enumerate all linearizations consistent with the partial order, or (b) refuse to replay and flag the run as order-ambiguous. A timestamp sort violates this because it silently imposes an order on unordered pairs. The condition of validity is therefore: **replay is sound iff every pair of spans it orders has a happens-before edge in the graph, or the engine has an explicit, recorded serialization witness (a lock-acquisition span, a sequence attribute, or a causal `link`) justifying the order.** Wall-clock proximity is not a witness; it is a proxy that fails at clock resolution, under clock skew between agent hosts, and under exporter batching. ## Decision Boundary The boundary is crossed when the following predicate holds for any sibling pair in the reconstructed graph: ``` |A.start - B.start| < exporter_clock_resolution AND no happens_before(A, B) AND no happens_before(B, A) AND A, B touch a shared mutable resource (workspace, scratchpad, memory store, tool side-effect) ``` Below the boundary (distinct timestamps, or no shared resource) a timestamp sort is a safe linearization and replay is faithful. Above the boundary the run is *order-ambiguous* and any single replay is one of ≥2 possible schedules. The decision the engine must make: does it (1) collapse to one arbitrary linearization and report a single verdict (unsound for counterfactuals), (2) enumerate the linearization lattice and report a verdict *set* with the ambiguity surfaced (sound, expensive), or (3) hard-fail the replay with a diagnostic naming the ambiguous pair. For counterfactual debugging specifically, option (1) is disqualifying: a counterfactual is only meaningful if the baseline and the intervention are replayed under the *same* linearization, which requires the engine to pin the linearization explicitly rather than let it fall out of sort order. ## Operational Effect The practical consequence is that counterfactual verdicts must be reported as intervals over the linearization lattice, not points. An intervention that flips the verdict under *every* consistent linearization is a real causal finding; one that flips it under *some* linearizations is confounded by ordering and must be reported as such. Operationally this means the replay engine needs a canonical linearization witness captured at record time—a monotonic per-agent sequence counter stamped into each span, or an explicit lock/lease span around shared-resource access—so that replay can reconstruct the *actual* order rather than invent one. Absent that witness, the correct behavior is to detect the ambiguous pair, attach the shared-resource evidence, and raise rather than silently sort. The guardrail is cheap at record time (one counter increment) and catastrophic to retrofit, because the ambiguity is invisible in the trace until a counterfactual depends on it. ```python from dataclasses import dataclass class AmbiguousLinearizationError(RuntimeError): """Raised when replay must order two spans with no happens-before edge.""" pass @dataclass(frozen=True) class Span: span_id: str parent_id: str | None start_ns: int touches: frozenset[str] # shared mutable resources written/read seq: int | None = None # monotonic witness, if instrumented def happens_before(a: Span, b: Span, spans: dict[str, Span]) -> bool: # Ancestor walk: a precedes b if a is an ancestor of b. cur = spans.get(b.parent_id) if b.parent_id else None while cur is not None: if cur.span_id == a.span_id: return True cur = spans.get(cur.parent_id) if cur.parent_id else None # Explicit sequence witness disambiguates concurrent siblings. if a.seq is not None and b.seq is not None and a.parent_id == b.parent_id: return a.seq < b.seq return False def linearize(siblings: list[Span], spans: dict[str, Span], clock_resolution_ns: int) -> list[Span]: """Sort siblings, but refuse when the sort would invent an order.""" ordered = sorted(siblings, key=lambda s: (s.start_ns, s.seq if s.seq is not None else -1)) for i in range(len(ordered) - 1): a, b = ordered[i], ordered[i + 1] if happens_before(b, a, spans): continue # sort already consistent with this edge unordered = not happens_before(a, b, spans) close = abs(a.start_ns - b.start_ns) < clock_resolution_ns shared = a.touches & b.touches if unordered and close and shared: raise AmbiguousLinearizationError( f"cannot order {a.span_id} vs {b.span_id}: no happens-before edge, " f"timestamps within {clock_resolution_ns}ns, shared resource(s) " f"{sorted(shared)}; replay would fabricate a schedule. " f"Pin a sequence witness or enumerate the linearization lattice." ) return ordered def replay_counterfactual(spans: dict[str, Span], clock_resolution_ns: int, baseline_verdict: str) -> str: roots = [s for s in spans.values() if s.parent_id is None] if not roots: raise AmbiguousLinearizationError("empty trace: no root span to anchor replay") schedule = linearize(roots, spans, clock_resolution_ns) # ... execute schedule under pinned linearization ... return baseline_verdict ```