# Why does an instance replay diverge when a tool's non-deterministic output is captured inside a memoized sub-trajectory? **Date of Record:** 2026 November 28 **Scope:** Applies to forensic replay of agent trajectories where tool-call results are memoized/cached to make replay deterministic, and where sub-trajectories are replayed as atomic units. Does not apply to live re-execution against the real environment (which is intentionally non-deterministic), nor to replay of pure-reasoning traces with no tool boundaries. ## Core Distinction There are two distinct notions of "deterministic replay" that forensic tooling routinely conflates: 1. **Input-deterministic replay** — given the same recorded inputs (prompt, tool results, seeds), the model produces the same sequence of actions. This is what most replay harnesses promise, and it is only approximately true because sampling and temperature make the model itself non-deterministic. 2. **Causal-deterministic replay** — the replayed trajectory preserves the *causal dependency graph* between tool outputs and downstream decisions, so that a divergence at step N can be attributed to a specific recorded artifact rather than to a black-box "the model did something different." The failure mode is that memoization of tool outputs silently converts the first into the second *only when the cache key is complete*. When a tool output is non-deterministic and its cache key omits a hidden input (a timestamp, a pagination cursor, a random seed embedded in a request, ambient state like a rate-limit counter), replay hits the cache, returns a *plausible but stale* value, and the trajectory proceeds down a branch the original run never took. The forensic record then shows a clean, deterministic replay that is *wrong* — and worse, internally consistent, so it hides its own wrongness. ## What Was Observed A three-stage agent (plan → retrieve → summarize) was instrumented with a memoization layer keyed on `(tool_name, serialized_args)`. The retrieve tool called a search API that returned top-k results ranked by a recency-weighted score. During the incident, the agent produced a summary citing document `D-4471`. During replay 48 hours later, the same trajectory replayed to a summary citing `D-8890` — and the replay harness reported **zero divergence** because every tool call hit its memoized entry. The trace: - Original run at `T0`: search query `"quarterly retention"` returned `[D-4471, D-2201, D-8890]`, because `D-4471` was 6 hours old and the recency weight dominated. - Replay at `T0+48h`: the memoization key `(search, {"q":"quarterly retention","k":3})` matched, so the cache returned the *recorded* result `[D-4471, ...]`. Good — the tool layer was actually deterministic. - But the *summarizer* call was keyed on `(summarize, {"docs":[D-4471,D-2201,D-8890], "clock":"..."})` — and the `clock` argument was populated from `datetime.utcnow()` at call time. The replay's clock differed, the cache missed, the summarizer re-ran live, and the model — given a different (real) wall-clock in its system context — weighted `D-8890` as "most recent" and cited it instead. The divergent artifact was not the tool output. It was a **hidden non-deterministic input smuggled into a tool argument** that the memoization key faithfully included, thereby *guaranteeing* a cache miss on replay while every other call hit. The harness's divergence detector compared only final tool results, not intermediate model outputs, so it saw a full set of cache hits and declared success. The general shape: **memoization key completeness is a two-sided invariant.** An incomplete key causes stale-hit corruption (replay silently uses wrong data). A *too-complete* key that includes ambient non-determinism (clocks, UUIDs, process IDs, iteration counters) causes guaranteed-miss re-execution — which, for any tool whose output is genuinely non-deterministic, means the replay is *not* a replay at all. The dangerous case is the mixed one: some calls hit, some miss, and the divergence detector only checks one side. ## Condition of Validity The invariant that makes replay forensically sound is: > **For every tool invocation in the recorded trajectory, the memoization key must be a function of exactly the arguments that the tool's *output* depends on — no more, no less — and the replay harness must assert that the fraction of cache hits equals 1.0 across the entire trajectory, not merely that no *recorded* result was contradicted.** Three conditions must hold jointly: 1. **Key sufficiency:** every input that can affect the output is in the key. (Violated → stale-hit corruption.) 2. **Key necessity:** no input that cannot affect the output is in the key. (Violated → forced re-execution of non-deterministic tools, i.e., non-replay.) 3. **Replay completeness assertion:** the harness verifies `hits / total == 1` and *fails the replay* on any miss, rather than treating a miss as "re-execute and continue." Condition 3 is the one almost always omitted. A harness that tolerates misses is not a replay harness; it is a re-execution harness with a cache in front. It will produce a trajectory that *looks* like the original and diverges precisely at the non-deterministic boundary — the exact place forensics needs fidelity. The clock-in-arguments case fails condition 2. The classic stale-hit case (keying only on `tool_name` and dropping the query) fails condition 1. Both are silent under a harness that checks only final outputs. ## Decision Boundary When designing or auditing a replay harness, the decision boundary is whether a tool's output is a *pure function* of its declared arguments: - **Pure tool (search with frozen index snapshot, calculator, deterministic formatter):** memoize on full serialized args. A cache miss on replay is a *bug* in the harness and must raise. - **Impure tool (live search, clock-dependent ranking, LLM-as-tool, anything reading ambient state):** the ambient inputs must be *captured as first-class recorded artifacts* at original-run time and *injected* at replay time, not re-read. The clock must be recorded, not re-sampled. If an ambient input cannot be captured, the tool must be marked `replay-opaque` and the trajectory must be flagged as "replayable up to step K," with the flag surfaced in the forensic report. - **The boundary case that bites:** tools that are pure *given* their args but whose args are assembled by the agent from ambient context (the clock case above). These are pure tools with impure call sites. The fix is at the call site: freeze ambient inputs into the recorded args at original-run time, so the recorded trajectory contains the literal `clock` value used, and replay passes the *recorded* value, not `utcnow()`. The invariant to enforce in code: **no tool argument may be sourced from ambient state at replay time.** Replay must be a pure function of the recorded trajectory file. Any argument that would otherwise be ambient must be a field in the record. ## Operational Effect Concretely, the following guardrails bound the failure: 1. **Record ambient inputs explicitly.** At original-run time, every ambient read (`time`, `uuid4`, `random`, env vars, rate-limit counters) that flows into a tool argument is captured into the trajectory record as a named field. Replay reads from the record. 2. **Assert full cache coverage.** The replay harness computes `cache_hits / tool_invocations` and raises if `< 1.0`. A miss is a forensic defect, not a fallback. 3. **Diff on intermediate model outputs, not final results.** The divergence detector compares the per-step action sequence (tool name + args + model text) against the record, step by step, and reports the *first* divergent step with its causal inputs. Comparing only final artifacts hides divergence at step N behind convergence at step M. 4. **Tag replay-opaque tools.** Tools that genuinely cannot be made deterministic are tagged; trajectories containing them are reported as partially replayable, with the opaque step index surfaced. Downstream consumers (incident reviewers, auditors) must see the tag. Without these, the failure is not "replay crashed." It is "replay succeeded and was wrong" — the worst outcome for forensic observability, because it manufactures false confidence in a record that has already lost the causal link between the incident and its explanation. ```python from dataclasses import dataclass, field from typing import Any class ReplayDivergenceError(RuntimeError): """Raised when a replay trajectory diverges from its recorded causal chain.""" class AmbientLeakError(ReplayDivergenceError): """Raised when a tool argument is sourced from ambient state at replay time.""" @dataclass class ToolRecord: tool_name: str args: dict[str, Any] result: Any ambient_inputs: dict[str, Any] = field(default_factory=dict) @dataclass class TrajectoryRecord: steps: list[ToolRecord] replay_opaque_steps: set[int] = field(default_factory=set) def replay_trajectory(record: TrajectoryRecord, tool_registry: dict) -> list[Any]: """ Replay a recorded trajectory. Enforces the three-part invariant: 1. key sufficiency (memoization key covers all output-affecting args) 2. key necessity (no ambient state leaks into args at replay time) 3. full cache hit (every step must hit; a miss is a defect, not a fallback) """ results: list[Any] = [] for idx, step in enumerate(record.steps): if idx in record.replay_opaque_steps: # Explicitly marked non-replayable; surface, do not silently re-execute. results.append(step.result) continue tool = tool_registry.get(step.tool_name) if tool is None: raise ReplayDivergenceError( f"step {idx}: tool {step.tool_name!r} absent from registry" ) # Condition 2: no ambient leak. The recorded args must be self-contained. leaked = set(step.ambient_inputs) & set(step.args) if leaked: raise AmbientLeakError( f"step {idx}: ambient inputs {sorted(leaked)} leaked into args; " f"replay would re-sample non-deterministic state" ) # Condition 1 + 3: replay must be a pure function of the record. # In a real harness this consults the frozen output store; a miss is fatal. cache_key = (step.tool_name, tuple(sorted(step.args.items()))) cached = tool.lookup_frozen(cache_key) if cached is _MISS: raise ReplayDivergenceError( f"step {idx}: cache miss for {step.tool_name!r} with args " f"{step.args!r} — replay coverage < 1.0, trajectory not forensically sound" ) if cached != step.result: raise ReplayDivergenceError( f"step {idx}: recorded result mismatch for {step.tool_name!r}" ) results.append(cached) return results _MISS = object() ```