# Why does an instance replay diverge when non-deterministic tool outputs are re-sampled during trace reconstruction? **Date of Record:** 2026 November 24 **Scope:** Applies to post-hoc agent replay systems that reconstruct an execution trace by re-invoking the model and tools from recorded inputs, where any tool or sampling step is non-deterministic. Does not apply to replay systems that store and replay the full literal token/tool-output transcript (deterministic transcript replay). ## Core Distinction There are two incompatible meanings of "replay" that observability tooling routinely conflates: - **Transcript replay** — the recorded sequence of tokens and tool results is fed back verbatim; the agent's state is a pure function of the log. Fully deterministic, but blind to *why* the model chose a branch. - **Re-derivation replay** — the harness re-executes the agent loop from recorded *inputs* (prompts, tool arguments, seeds), re-invoking the model and tools to regenerate outputs. This is what most "causal debugging" and "counterfactual replay" features actually do. The boundary failure lives in the second mode. The invariant that transcript replay satisfies — *replay(state_t) = state_t for all recorded t* — is silently assumed by re-derivation replay, but does not hold. The divergence is not a bug in the model or the tool; it is structural. A single non-deterministic tool result (a `get_time`, a `search` returning re-ranked results, a `read_file` on a mutating file, a temperature>0 sample) forks the trajectory, and every downstream token is conditioned on a state the original run never occupied. ## What Was Observed An agent executing a 14-step tool-use task (`plan → search → fetch → summarize → write`) was instrumented with a re-derivation replayer. The replayer recorded, per step: the exact prompt, the tool name, the serialized arguments, and the sampling seed. On reconstruction it re-issued each call. Step 4 was a `web_search` tool. The original run returned results ranked `[A, B, C]`; the replayed run returned `[A, C, B]` — same corpus, same query, different ranking due to an upstream index refresh between the original execution and replay. The model, conditioned on the reordered context, selected `C` instead of `B` at step 5. From step 5 onward the two traces share no common suffix. The replayer's diff engine reported 9 of 14 steps as "changed," and the operator concluded the model had been "unstable" — when in fact the *inputs* had changed, not the policy. The telltale signature: divergence always originates at the first step whose tool output is not a pure function of (arguments, seed). Every step after that is a *consequence*, not an independent anomaly. A naive per-step divergence metric attributes causality uniformly and mislocates the fault. A second, subtler case: a `get_system_time` call at step 2 returned a timestamp; the model embedded it in a filename at step 11. Replay one hour later produced a different filename, and the downstream `write` tool wrote to a different path. The trace "diverged" at step 11 but the root cause was step 2. Attribution requires tracking *data provenance* through the context, not just step-by-step output equality. ## Condition of Validity Re-derivation replay is only a faithful reconstruction of the original trajectory when, for every step `t`, the replayed tool output and sampled token equal the recorded output. This holds iff: 1. All tools are **referentially transparent** with respect to their recorded arguments (pure, or seeded and side-effect-free), **and** 2. Sampling is **deterministic** given the recorded seed and the exact preceding context, **and** 3. The model serving the replay is the **same weights and same decoding configuration** as the original (a version bump alone breaks this). If any of (1)–(3) fails, the replay is a *counterfactual*, not a reconstruction. It may still be useful, but it must be labeled as such, and divergence must be attributed to the *first* step where the invariant breaks — not to the steps that inherit the break. The invariant to enforce is: **divergence is only meaningful downstream of a verified-identical prefix.** Any comparison of step `t` outputs is undefined unless steps `0..t-1` were byte-identical. ## Decision Boundary The operator must choose, per replay, between: - **Strict reconstruction** — pin tool outputs and sampled tokens from the log (transcript replay for the non-deterministic steps), re-derive only the deterministic reasoning. Divergence then genuinely reflects model instability. Cost: cannot explore counterfactuals on the pinned steps. - **Counterfactual replay** — allow re-sampling, but *mark the fork point explicitly* and refuse to attribute any downstream divergence to the model. Cost: cannot claim the replay represents "what happened." The failure mode is the undeclared middle: re-sampling non-deterministic steps while reporting per-step divergence as if the prefix were stable. The guardrail is a **prefix-equality gate**: the replayer computes the longest common prefix of identical (tool output, sampled token) pairs; it refuses to emit divergence reports beyond the first mismatch unless the operator explicitly opts into counterfactual mode, in which case the report is tagged `COUNTERFACTUAL` and the fork step is named. ## Operational Effect Without the gate, two concrete harms follow. First, **false instability attribution**: model or prompt changes get blamed for divergence actually caused by a re-ranked search or a clock read, leading to spurious "fixes" that mask the real non-determinism. Second, **silent provenance loss**: a timestamp or random ID threaded through context mutates a downstream side effect (a written file, a sent message), and the replay writes to the wrong location — an observability tool with real-world side effects. The fix is to record, per step, a *provenance tag* on every non-deterministic value and to treat any value whose provenance is `non-deterministic` as a mandatory pin in strict mode. The replay harness must fail closed: if it cannot prove prefix equality, it must not present the trace as a reconstruction. ```python import hashlib from dataclasses import dataclass from typing import Optional class ReplayDivergenceError(RuntimeError): """Raised when a re-derivation replay cannot prove prefix equality before a step whose output is being compared for divergence.""" @dataclass(frozen=True) class Step: index: int tool: str args_hash: str output: str provenance: str # "deterministic" | "non-deterministic" def _h(s: str) -> str: return hashlib.sha256(s.encode()).hexdigest() def reconstruct( recorded: list[Step], replayed: list[Step], allow_counterfactual: bool = False, ) -> Optional[int]: """Return the index of the first *meaningful* divergence, or None if the traces are identical through the recorded length. Enforces the prefix-equality invariant: a divergence at step t is only attributable to the model if steps 0..t-1 are byte-identical. If a non-deterministic step re-samples, we must either pin it (strict) or explicitly opt into counterfactual mode and name the fork step. """ if len(recorded) != len(replayed): raise ReplayDivergenceError( f"trace length mismatch: recorded={len(recorded)} replayed={len(replayed)}" ) for rec, rep in zip(recorded, replayed): if rec.index != rep.index or rec.tool != rep.tool or rec.args_hash != rep.args_hash: raise ReplayDivergenceError( f"step {rec.index}: input drift (tool/args changed) — not a valid replay" ) if _h(rec.output) == _h(rep.output): continue # prefix holds; keep going # Outputs differ at this step. If the step is non-deterministic, the # difference is a re-sampling fork, not model instability. if rec.provenance == "non-deterministic": if allow_counterfactual: return rec.index # fork point; caller must tag as COUNTERFACTUAL raise ReplayDivergenceError( f"step {rec.index}: non-deterministic tool '{rec.tool}' re-sampled " f"during strict replay; pin this output or enable counterfactual mode" ) # Deterministic step diverged with identical inputs -> genuine instability. return rec.index return None ```