# What happens when an instance replays a swarm execution from OTel spans and the causal order collapses under concurrent partial-batch emission **Date of Record:** 2026 November 20 **Scope:** Applies to forensic reconstruction and deterministic replay of multi-agent executions instrumented with OpenTelemetry spans, where spans are emitted asynchronously and batched per-agent. Does not apply to single-agent traces with a single span emitter, nor to synchronous in-process instrumentation where span export is ordered by construction. ## Core Distinction There are two distinct notions of "order" in a multi-agent trace, and confusing them is the root of every replay failure described here: - **Wall-clock order** — the timestamp on `span.start_time_unix_nano`. This is what the collector sorts by. It is *emitter-local* and *skew-contaminated*: each agent process stamps spans against its own monotonic clock, corrected imperfectly by NTP, and the export batch is flushed on a timer that is independent of the causally-relevant event. - **Causal order** — the partial order induced by `parent_span_id` and by the `trace_id`/`span_id` linkage of cross-agent handoffs (a tool call that invokes another agent, an A2A message that spawns a child span, an MCP `tools/call` that triggers a downstream span in a different service). A single-agent trace usually has these two orders coincide, so a replay engine that sorts by timestamp appears correct. In a swarm, they diverge. The divergence is not a bug in the tracing library; it is a *structural property* of concurrent, independently-batched emitters. The forensic invariant that must hold is: > **Replay order must be a linear extension of the causal partial order (the happens-before graph), never the wall-clock sort order. Any linear extension is a valid replay; the timestamp sort is not guaranteed to be one.** The failure mode is that the replay engine silently produces a linear extension of *nothing* — a sequence that violates happens-before — and the reconstructed execution is a plausible-looking fiction. ## What Was Observed A three-agent swarm (planner → executor → auditor) ran a task that terminated with a spurious verification failure: the auditor rejected a result the executor had actually produced correctly. The team pulled the OTel spans from the collector backend and replayed them to find the reasoning divergence. The replay showed the auditor's `verify_result` span *starting before* the executor's `produce_result` span had ended. The replay engine, sorting by `start_time_unix_nano`, placed the auditor's judgment at t=+412ms and the executor's output at t=+430ms. The reconstruction concluded the auditor had judged a stale or absent artifact — a satisfying narrative, and completely wrong. The actual trace, recovered from `parent_span_id` linkage and the `links` array on the auditor span (which pointed at the executor's `produce_result` span_id), showed the auditor's span was a *child* of the executor's output span via an explicit link. The causal order was unambiguous: produce → verify. The timestamps were inverted because: 1. The executor's batch exporter had a 500ms flush interval and the `produce_result` span was held in the batch until flush at t=+430ms wall-clock, but its `start_time` was recorded at the *call site* (t=+430ms) — wait, no: the span's start time was correct at the call site, but the *auditor's* clock was 18ms ahead due to NTP drift that had not yet been corrected. 2. The auditor emitted its span in a separate batch that flushed at t=+413ms, and its local clock read +412ms for an event that causally occurred *after* the executor's +430ms event on the executor's clock. The 18ms skew was larger than the 18ms causal gap. The two events were 18ms apart in causal time and 18ms apart in the *wrong direction* in wall-clock time. The replay engine had no way to know this from timestamps alone. The deeper observation: **the skew was not constant**. Across the run, NTP corrections moved the auditor's clock by ±40ms in steps. A naive "estimate skew by comparing span pairs" heuristic (which the team tried next) produced a *piecewise* correction that was correct for some span pairs and wrong for others, because the correction was applied globally rather than per-epoch. The replay was now wrong in a subtler way: it looked causally consistent but had reordered two spans that were actually concurrent, fabricating a serialization that never happened. ## Condition of Validity The invariant "sort by causal order, not timestamp" is *necessary* but not *sufficient*. It holds only under these conditions, each of which is a place the reconstruction can silently degrade: 1. **Every cross-agent causal edge is materialized as a span link or parent reference.** If agent A invokes agent B via a message that does not propagate `trace_id`/`span_id` (e.g., an A2A handoff where the transport strips W3C trace context, or an MCP server that does not forward `traceparent`), the causal edge is *absent from the trace*. The replay engine then has no choice but to fall back to timestamps for that edge, and the fallback is exactly the failure above. **The trace is not merely incomplete; it is misleadingly complete** — it has spans for both events, just no edge, so the engine invents one from timestamps. 2. **Concurrent spans are not falsely serialized.** A linear extension must preserve the *partial* order. If two spans are genuinely concurrent (neither happens-before the other, e.g., two parallel tool calls), any interleaving is a valid replay. But a forensic reconstruction that reports "X happened, then Y" when X and Y were concurrent is asserting a serialization that did not occur. The auditor's verdict in the observed case depended on *whether* the executor's output was visible at judgment time — a property that is only well-defined if the two spans are ordered. When they are concurrent, the verdict is *underdetermined by the trace*, and the replay must say so rather than pick a side. 3. **Clock skew is bounded per-epoch, not globally.** NTP steps mean skew is piecewise-constant at best. A single global offset correction is valid only if the trace is short enough that no step occurred. For long-running swarms (minutes to hours), skew must be treated as a per-epoch nuisance parameter, and edges whose timestamp-implied order is within the skew bound must be treated as *unordered* — i.e., the replay must fall back to the causal graph and, where the graph is also silent, emit an "indeterminate ordering" marker. 4. **The replay is deterministic given the trace, not given the timestamps.** Determinism means: same trace (same span set, same links) → same replay. It does *not* mean: same wall-clock timestamps → same replay. A replay engine that is deterministic on timestamps is deterministic on a quantity that is not causally meaningful. ## Decision Boundary The boundary is sharp and can be stated as a predicate the replay engine must evaluate before emitting any ordering assertion: ``` For each pair (s_i, s_j) in the trace: if happens_before(s_i, s_j) via parent/link graph: order = i < j [causal] elif happens_before(s_j, s_i): order = j < i [causal] elif |start(s_i) - start(s_j)| > skew_bound: order = timestamp [wall-clock, trusted] else: order = INDETERMINATE ``` Where `skew_bound` is the maximum |clock_offset| observed between the two spans' emitting services over the trace's epoch, derived from *paired* spans (a parent-child pair where the child's start must be ≥ the parent's start gives a one-sided bound; a request/response pair gives a two-sided bound). If no paired spans exist to bound skew, `skew_bound` is unbounded and *every* timestamp-only ordering is indeterminate. The critical decision: **when the boundary is crossed (timestamp order contradicts causal order, or the gap is within skew), the engine must not silently pick the timestamp.** It must either (a) use the causal edge, or (b) mark the pair indeterminate and propagate that indeterminacy into any downstream conclusion that depended on the ordering. The observed failure was a category (b) event that the engine treated as category (a)-by-timestamp. A second boundary: **the causal graph itself can be cyclic if instrumentation is wrong** (e.g., an agent emits a span whose parent is a span from a *later* logical step due to a context-propagation bug). A replay engine that assumes acyclicity and topologically sorts will either crash or, worse, silently drop the back-edge. The engine must detect cycles and fail loudly, because a cyclic happens-before graph means the trace is not a valid execution record at all. ## Operational Effect The downstream consequences are asymmetric and easy to miss: - **False forensic conclusions.** The team spent two days debugging a "stale artifact" bug in the auditor that did not exist. The replay's timestamp-sorted reconstruction was internally consistent, cited specific spans, and was wrong. Forensic reconstructions that violate happens-before are *more* dangerous than no reconstruction, because they carry the authority of "we have the trace." - **Non-reproducible replay.** Because the timestamp sort depends on skew, which depends on NTP state at run time, replaying the *same logical execution* on a re-run produces a different span ordering and a different reconstruction. The team's replay was not reproducible across runs, which they initially attributed to nondeterminism in the agents rather than in the replay engine. - **Masked concurrency bugs.** When the engine falsely serializes concurrent spans, it hides the very races the forensic analysis is meant to find. A genuine baton-passing race between two concurrent agents will be reported as a clean sequence, and the race becomes invisible. - **Skew-correction overfitting.** The piecewise skew correction that "fixed" some pairs broke others, and the team could not tell which reconstructions were now trustworthy. Once a replay engine applies a non-causal heuristic, its output loses the property that makes forensics useful: that a conclusion follows from the trace by a rule you can state and check. The guardrail is architectural, not algorithmic: **materialize every cross-agent causal edge at the transport layer** (propagate `traceparent` through A2A and MCP, refuse handoffs that drop it), **derive skew bounds from paired spans per epoch**, and **make indeterminacy a first-class replay output** rather than a tie-break the engine resolves by timestamp. A replay that cannot order two spans must say so; the forensic value is in the edges you can prove, not in the total order you can invent. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Optional class ReplayOrderingError(RuntimeError): """Raised when a replay cannot produce a causally valid ordering.""" class Order(Enum): CAUSAL_BEFORE = "causal_before" CAUSAL_AFTER = "causal_after" WALLCLOCK_TRUSTED = "wallclock_trusted" INDETERMINATE = "indeterminate" @dataclass(frozen=True) class Span: span_id: str parent_id: Optional[str] start_ns: int service: str links: tuple[str, ...] = () @dataclass class Trace: spans: dict[str, Span] = field(default_factory=dict) # per-service epoch skew bound in ns, derived from paired spans skew_bound_ns: dict[str, int] = field(default_factory=dict) def happens_before(self, a: str, b: str) -> bool: """True if a is an ancestor of b via parent/link edges (excluding self).""" seen: set[str] = set() stack = [b] while stack: cur = stack.pop() if cur in seen: continue seen.add(cur) s = self.spans.get(cur) if s is None: continue preds = ([s.parent_id] if s.parent_id else []) + list(s.links) for p in preds: if p == a: return True if p: stack.append(p) return False def order_pair(self, a: str, b: str) -> Order: if self.happens_before(a, b): return Order.CAUSAL_BEFORE if self.happens_before(b, a): return Order.CAUSAL_AFTER sa, sb = self.spans[a], self.spans[b] gap = abs(sa.start_ns - sb.start_ns) bound = max( self.skew_bound_ns.get(sa.service, 0), self.skew_bound_ns.get(sb.service, 0), ) if bound == 0: # no paired-span evidence: timestamp ordering is unverifiable return Order.INDETERMINATE if gap > bound: return Order.WALLCLOCK_TRUSTED return Order.INDETERMINATE def assert_replayable(trace: Trace, required_pairs: list[tuple[str, str]]) -> None: """Verify that every pair a forensic conclusion depends on is ordered. Raises ReplayOrderingError if any required pair is INDETERMINATE, because a conclusion resting on an indeterminate pair is not supported by the trace. """ for a, b in required_pairs: if a not in trace.spans or b not in trace.spans: raise ReplayOrderingError( f"missing span in required pair ({a}, {b}); trace is incomplete" ) o = trace.order_pair(a, b) if o is Order.INDETERMINATE: raise ReplayOrderingError( f"cannot order ({a}, {b}): no causal edge and timestamp gap " f"within skew bound; conclusion is underdetermined by trace" ) if o is Order.CAUSAL_AFTER: # caller assumed a-before-b but causal graph says otherwise: # a timestamp-sorted replay would have silently inverted this. raise ReplayOrderingError( f"causal order contradicts requested order for ({a}, {b}): " f"b happens-before a via span graph" ) ```