# Why does an instance replay diverge from its recorded OTel trace when the memory snapshot is restored before the trace's last span closes? **Date of Record:** 2026 November 30 **Scope:** Applies to deterministic-replay and time-travel-debugging harnesses that reconstruct an agent run from (a) an OpenTelemetry span tree with recorded tool I/O and (b) a serialized memory/state snapshot captured at some checkpoint. Does not apply to live re-execution against real tools, nor to traces that omit tool request/response payloads. ## Core Distinction A trace and a snapshot are two different clocks over the same run. The trace is an **append-only log of observed events**, ordered by wall-clock and parent-child span nesting. The snapshot is a **point-in-time materialization of state**, and it carries an implicit *cut*: the instant at which the serialization began relative to in-flight spans. Replay correctness depends on the snapshot cut being **causally consistent** with the span tree — i.e., every span whose effects are *included* in the snapshot must be an ancestor of the checkpoint, and every span whose effects are *excluded* must be a descendant. When the harness restores the snapshot and then replays from the checkpoint span, it silently assumes this consistency. The non-obvious failure is that **the snapshot cut frequently lands mid-span**, and the replay engine resolves the ambiguity in the wrong direction: it restores state that already reflects a tool call whose span has not yet been "replayed," then re-issues that call, producing a double-application (or, symmetrically, a dropped application) that is invisible in the span tree because both branches produce valid-looking spans. ## What Was Observed A multi-step agent run (retrieval → tool call → memory write) was captured with OTel spans. Spans: `S0 plan` (root), `S1 tool:vector_search`, `S2 tool:memory_write`, `S3 finalize`. A snapshot was taken by a background serializer triggered on a timer. The serializer walked the live agent object graph — including the mutable `memory` dict — while `S2` was in flight. Because `memory_write` mutates the dict *before* the span closes (the write to the store happens, then the span is ended), the serialized snapshot **already contained the effect of `S2`**, but the trace records `S2` as ending *after* the snapshot timestamp. On replay, the harness: 1. Loaded the snapshot (memory already contains `S2`'s write). 2. Positioned the replay cursor at the checkpoint = the span *before* `S2` (the last span whose `end_time < snapshot_ts`), i.e. `S1`. 3. Re-executed `S2` from recorded inputs against the restored memory. Result: the memory write was applied **twice**. The span tree of the replay looked *identical* to the original (same span names, same recorded outputs), because the second application was idempotent-looking at the span level — the tool returned the same recorded response either way. The divergence only surfaced three steps later when a retrieval over the doubled memory returned a different top-k than the recorded `S3` input, and the agent's subsequent reasoning forked. The replay "succeeded" (no exception, spans matched) while producing a semantically wrong run. The tell: the replay's `S3` span had a different `input_tokens` count and a different retrieval result than the recorded `S3`, but the *tool outputs* for `S2` matched exactly. Naive span-diff replay validators pass this. ## Condition of Validity Deterministic replay is sound only under the **snapshot-causality invariant**: > For every span `s` in the trace, the snapshot's inclusion of `s`'s effects is equivalent to `s` being a strict ancestor of the checkpoint span `c` in the span tree, where `c` is the deepest span with `end_time ≤ snapshot_ts`. This invariant holds only when the snapshot is captured at a **quiescent point** — no span open — or when the serializer records, alongside the state, the set of currently-open span IDs and their partial effects. A timer-driven serializer that reads live mutable state violates it whenever it fires during a mutating tool span. The invariant is *not* restored by comparing timestamps alone, because a span's *effect* and its *end_time* are ordered differently across tools: some tools mutate-then-close (effect precedes close → snapshot over-includes), others close-then-commit (effect follows close → snapshot under-includes). The harness must know which regime each tool uses, which is exactly the metadata OTel spans do not carry by default. ## Decision Boundary The replay engine must branch on whether the checkpoint's open-span set is empty: - **Quiescent snapshot (no open spans):** replay from checkpoint `c`; re-execute all descendants of `c`. Sound. - **Non-quiescent snapshot (open spans at capture):** the harness must *not* assume `c`'s descendants are unapplied. For each open span `o`, consult the tool's declared effect-ordering (`effect_before_close` vs `effect_after_close`). If `effect_before_close`, the snapshot already contains `o`'s effect → **skip re-execution of `o`** and treat it as a replay-supplied no-op. If `effect_after_close`, `o`'s effect is absent → re-execute normally. - **Unknown effect-ordering:** fail closed. Refuse to replay and demand a re-capture at a quiescent checkpoint. Guessing here is the bug. The boundary is sharp: it is not "did the snapshot happen before or after the span," it is "does this tool's state mutation commute with span closure." Timestamp comparison answers the wrong question. ## Operational Effect Harnesses that ignore effect-ordering produce **silent double-application** on mutate-then-close tools and **silent dropped-application** on close-then-commit tools. Both pass span-diff validation because the *recorded* outputs are replayed from the log rather than recomputed, masking the state divergence. The divergence only manifests as a downstream fork in reasoning or retrieval, typically 2–4 spans later, far from the actual fault. Time-travel debugging then misattributes the bug to the downstream span. The fix is to (1) capture snapshots only at quiescent points or (2) stamp each snapshot with its open-span set and each tool with its effect-ordering, and have the replay engine honor the skip/re-execute decision per open span. Without one of these, replay is a plausible fiction, not a reproduction. ```python from dataclasses import dataclass from enum import Enum from typing import Optional class ReplayDivergenceError(RuntimeError): """Raised when a snapshot's causal cut cannot be reconciled with the span tree.""" class EffectOrdering(Enum): BEFORE_CLOSE = "effect_before_close" # mutation lands, then span ends AFTER_CLOSE = "effect_after_close" # span ends, then mutation commits UNKNOWN = "unknown" @dataclass class Span: span_id: str parent_id: Optional[str] end_time: float tool: Optional[str] = None @dataclass class Snapshot: ts: float open_span_ids: frozenset[str] TOOL_ORDERING = { "vector_search": EffectOrdering.AFTER_CLOSE, "memory_write": EffectOrdering.BEFORE_CLOSE, } def plan_replay(spans: list[Span], snap: Snapshot) -> list[str]: """Return span_ids that must be re-executed on replay. Raises ReplayDivergenceError if an open span's effect-ordering is unknown, because we cannot decide whether the snapshot already contains its effect. """ to_reexec = {s.span_id for s in spans if s.end_time > snap.ts} for open_id in snap.open_span_ids: span = next((s for s in spans if s.span_id == open_id), None) if span is None or span.tool is None: raise ReplayDivergenceError( f"open span {open_id!r} at snapshot has no recorded tool; " "cannot determine effect-ordering, refusing to replay" ) ordering = TOOL_ORDERING.get(span.tool, EffectOrdering.UNKNOWN) if ordering is EffectOrdering.UNKNOWN: raise ReplayDivergenceError( f"tool {span.tool!r} (span {open_id!r}) has unknown effect-ordering; " "snapshot may over- or under-include its effect — fail closed" ) if ordering is EffectOrdering.BEFORE_CLOSE: # Snapshot already contains this span's effect: do NOT re-apply. to_reexec.discard(open_id) # AFTER_CLOSE: effect absent from snapshot, leave it in to_reexec. return sorted(to_reexec) def replay(spans: list[Span], snap: Snapshot) -> list[str]: try: return plan_replay(spans, snap) except ReplayDivergenceError: raise except Exception as exc: # defensive: never let a malformed trace pass silently raise ReplayDivergenceError(f"replay planning failed on malformed trace: {exc}") from exc ```