# What happens when an instance replays a nondeterministic trace and the causal chain diverges at a tool boundary **Date of Record:** 2026 November 24 **Scope:** Applies to post-hoc causal replay and counterfactual debugging of agent traces where tool calls, sampling, or retrieval are re-executed during reconstruction. Does not apply to pure log inspection of already-materialized traces, nor to deterministic workflows with no sampling or external state reads. ## Core Distinction There are two things practitioners conflate under "replay": **trace replay** (re-emitting the recorded sequence of events as immutable data) and **causal replay** (re-running the agent so that the causal dependency graph that produced each decision is reconstructed). Trace replay is a log read; it is deterministic by construction because it never invokes the model or the tools again. Causal replay is a *re-execution* of a probabilistic system against a world that has moved on. The non-obvious boundary is this: causal replay is only sound if every nondeterministic primitive in the original run (sampling seed, tool response, retrieval snapshot, clock, environment variable, remote API version) is either *pinned* to its recorded value or *explicitly marked as a free variable*. The failure mode is not "replay gives a different answer"—that is expected. The failure mode is **silent divergence**: the replay produces a plausible, coherent, differently-caused trace, and the debugger attributes the divergence to the agent's reasoning when the actual cause is an unpinned primitive. The counterfactual you then compute ("what if the agent had chosen differently at step 7?") is computed on a fabricated causal graph, and the conclusion is confidently wrong. ## What Was Observed A coding agent ran a 14-step task: read repo, plan, edit three files, run tests, fix, re-run. Trace T0 recorded: step 6 `read_file("src/auth/session.py")` returned 212 lines; step 9 `run_tests()` returned `FAILED test_session_refresh`; step 10 the agent edited `session.py` line 88; step 12 `run_tests()` passed. An engineer opened the trace in a causal-replay debugger to ask a counterfactual: *"If the agent had read `session.py` at step 5 instead of step 6, would it have avoided the failed test?"* The debugger re-executed from step 1. It re-invoked the model (temperature 0.7, no seed pinned), re-issued `read_file` against the *current* filesystem (the file had been edited by a later commit: now 240 lines, line 88 was different), and re-ran `run_tests` against the current working tree (which now included the fix from step 10). The replay produced a trace T1 in which step 6 returned 240 lines, step 9's test passed immediately, step 10 never edited anything, and the counterfactual concluded: *"reading at step 5 would not have changed the outcome; the fix was unnecessary."* Every step of that conclusion was wrong. The causal chain diverged at three independent points: 1. **Sampling divergence at step 2** (the plan). Unpinned temperature meant the replayed plan was a different plan (it reordered the edits), so the "step 6" of T1 was not the same decision node as the "step 6" of T0. Node identity was matched by *ordinal position*, not by content hash. 2. **Tool divergence at step 6** (`read_file`). The tool was re-executed against mutated external state. The recorded 212-line response was not injected; the live 240-line response was. The agent's subsequent reasoning consumed different evidence. 3. **Environment divergence at step 9** (`run_tests`). The test harness ran against a working tree that already contained the step-10 fix. The failure that motivated the entire branch was erased. The debugger's UI showed a green "causal chain intact" badge because it checked only that the *event types* at each ordinal matched (read → read → edit → test → edit → test). The badge was a structural check, not a causal one. The engineer acted on the counterfactual for two days before noticing the line numbers in the replay did not match the trace. The invariant that was violated: **for causal replay to be sound, the replay must be node-identical to the original at every decision point, and node identity must be established by content hash of (prompt, model config, tool input, tool output), not by ordinal position or event type.** Any node whose hash differs must be flagged as a divergence boundary, and every counterfactual computed downstream of a divergence boundary must be labeled as *conditional on a different causal graph*, not as a counterfactual on the original. ## Condition of Validity Causal replay of a nondeterministic agent trace is valid only when all of the following hold for the segment being replayed: - **Sampling is pinned or branched.** Either the original sampling seed and config are recorded and re-applied (making the model call reproducible up to provider-version drift), or the replayed call is explicitly registered as a *new branch* with a new node id, and no downstream counterfactual may treat it as the same node. - **Tool outputs are injected, not re-fetched.** For any tool with external side effects or mutable reads (filesystem, network, database, clock), the recorded output must be injected from the trace. Re-execution is permitted only for tools declared *pure and idempotent* in the tool manifest, and even then the replay must diff the fresh output against the recorded output and raise on mismatch. - **Environment is snapshotted.** The working tree, environment variables, dependency versions, and remote API versions at the time of the original run must be captured (or the run must be replayed against a frozen copy), because `run_tests` and `read_file` are functions of ambient state the trace does not otherwise record. - **Node identity is content-addressed.** Matching by ordinal ("step 6") is invalid because a single divergence upstream shifts every subsequent ordinal. Identity must be `hash(prompt || model_config || tool_name || tool_input || tool_output)`. - **Divergence is first-class.** The replay engine must emit divergence events with the exact field that differed (e.g., `tool_output` at node `a3f9…`: recorded 212 lines, live 240 lines), and must refuse to emit a counterfactual verdict for any decision reachable from a divergence boundary without an explicit `conditional=True` marker. When any of these does not hold, the replay is a *simulation of a plausible run*, not a reconstruction of the recorded one. It is still useful—but it must be labeled as a new trace, not as the original. ## Decision Boundary The operational decision is: **given a trace and a question, do you replay or do you inspect?** Replay (re-execute) is justified when: - The question is "what would the agent have done if X were different?" and X is a *controlled* variable you can pin while holding all other primitives to their recorded values. - Every tool on the path is either injected-from-trace or declared pure, and the pure tools' fresh outputs match the recorded ones. - You are willing to accept that the answer is conditional on provider-version stability of the model. Inspect (read-only) is required when: - Any tool on the path has external side effects or mutable reads that cannot be snapshotted. - The model does not expose seeds and you cannot pin sampling, and the question depends on the exact token sequence of a decision. - The trace crosses a divergence boundary and the question is about a node downstream of it—because at that point you are asking about a different run. The boundary is crossed silently when the replay engine's divergence detection is structural (event-type or ordinal matching) rather than content-addressed. A structural check passes on a trace where every node has been replaced by a different node of the same type. This is the specific trap: **the more coherent the replayed trace, the less likely the structural check will catch the divergence**, because a coherent replay has the same shape as the original. ## Operational Effect Concretely, teams that adopt causal replay without content-addressed node identity and divergence-first-class reporting experience three downstream failures: 1. **Counterfactual contamination.** A counterfactual computed downstream of an undetected divergence boundary is reported with the same confidence as one computed on an intact chain. The debugger's "chain intact" badge becomes an active source of false confidence—worse than no badge, because it suppresses the engineer's own skepticism. 2. **Fix attribution errors.** When the replay shows the fix was "unnecessary" (as above), the team may revert a correct patch or mis-attribute the original failure to a phantom cause. The mis-attribution is stable and reproducible *within the debugger*, which makes it hard to dislodge. 3. **Drift accumulation across replays.** Each replay against live external state mutates that state (tests write caches, edits persist), so the *next* replay diverges further. The trace becomes progressively less replayable, and the earliest, most-informative replays are the ones with the least divergence—but by the time the engineer asks the important question, the world has moved enough that replay is no longer sound. The guardrail that bounds all three: **record at trace time, not replay time.** Pin the sampling seed and config, snapshot tool outputs inline, capture the environment manifest (tree hash, env vars, dependency lockfile, remote API version headers), and content-address every node. Then replay becomes a matter of *injecting* the recorded primitives rather than *re-fetching* them, and divergence becomes a detectable event rather than a silent substitution. The cost is trace size (tool outputs dominate); the alternative is a debugger that confidently answers questions about a run that never happened. ```python import hashlib import json from dataclasses import dataclass, field from typing import Any class CausalDivergenceError(RuntimeError): """Raised when a causal replay diverges from the recorded trace at a node whose identity is content-addressed. Downstream counterfactuals are invalid.""" class UnpinnedPrimitiveError(RuntimeError): """Raised when a replay attempts to re-execute a nondeterministic primitive (sampling, mutable tool read, clock) that was not pinned in the trace.""" @dataclass(frozen=True) class Node: step: int kind: str # "model" | "tool" | "env" prompt: str model_config: dict tool_name: str | None tool_input: Any tool_output: Any def identity(self) -> str: # Content-addressed identity: NOT the ordinal step. payload = json.dumps( { "kind": self.kind, "prompt": self.prompt, "model_config": self.model_config, "tool_name": self.tool_name, "tool_input": self.tool_input, "tool_output": self.tool_output, }, sort_keys=True, default=str, ).encode() return hashlib.sha256(payload).hexdigest() @dataclass class ReplayResult: node_id: str diverged: bool detail: str conditional: bool = False def replay_node( recorded: Node, live_model_fn, live_tool_fn, pure_tools: set[str], pinned_seed: int | None, ) -> ReplayResult: """Replay one node. Inject recorded tool outputs for impure tools; re-execute only pure tools. Raise on any divergence that invalidates downstream causality.""" if recorded.kind == "model": if pinned_seed is None: raise UnpinnedPrimitiveError( f"step {recorded.step}: model node has no pinned seed; " f"replay would branch, not reconstruct. Register as new branch." ) live_out = live_model_fn(recorded.prompt, recorded.model_config, pinned_seed) live = Node( step=recorded.step, kind="model", prompt=recorded.prompt, model_config=recorded.model_config, tool_name=None, tool_input=None, tool_output=live_out, ) elif recorded.kind == "tool": if recorded.tool_name in pure_tools: live_out = live_tool_fn(recorded.tool_name, recorded.tool_input) else: # Impure tool: MUST inject recorded output. Re-fetching mutates the # causal graph silently — this is the exact failure being guarded. live_out = recorded.tool_output live = Node( step=recorded.step, kind="tool", prompt=recorded.prompt, model_config=recorded.model_config, tool_name=recorded.tool_name, tool_input=recorded.tool_input, tool_output=live_out, ) else: live = recorded # env nodes are snapshots, replayed verbatim if live.identity() != recorded.identity(): raise CausalDivergenceError( f"step {recorded.step} ({recorded.kind} {recorded.tool_name or ''}): " f"content-addressed identity diverged. " f"recorded={recorded.identity()[:12]} live={live.identity()[:12]}. " f"All counterfactuals downstream of this node are conditional on a " f"different causal graph and must not be reported as reconstructions." ) return ReplayResult(node_id=live.identity(), diverged=False, detail="match") def run_causal_replay( trace: list[Node], live_model_fn, live_tool_fn, pure_tools: set[str], pinned_seed: int | None, ) -> list[ReplayResult]: results: list[ReplayResult] = [] for node in trace: try: results.append( replay_node(node, live_model_fn, live_tool_fn, pure_tools, pinned_seed) ) except CausalDivergenceError as e: # First divergence halts the chain: nothing downstream is a # reconstruction of the original run. results.append( ReplayResult( node_id=node.identity(), diverged=True, detail=str(e), conditional=True, ) ) break return results ```