What happens when an instance replays a trajectory through a nondeterministic tool boundary and silently reconstructs a divergent past

**Date of Record:** 2026 December 1 **Scope:** Applies to forensic replay and time-travel debugging of agent trajectories where tool calls, sampling, or environment reads are re-executed rather than served from a recorded tape. Does not apply to pure record-and-replay systems where every external effect is captured at record time and re-executed as a stub with byte-identical output.

Core Distinction

The distinction that matters is between **replay as re-execution** and **replay as reconstruction from a tape**. A tape-based replay is a total function: given the recorded sequence of (prompt, completion, tool-call, tool-result) tuples, it re-drives the agent's control flow without ever touching the live world. A re-execution-based replay is a *partial* function that the engineer mistakenly treats as total: it re-invokes the model and re-invokes the tools, betting that determinism holds. It does not. The model's sampling is nondeterministic across versions and often across identical seeds due to batching and hardware non-associativity; the tools are nondeterministic by nature (clock reads, network fetches, filesystem mtimes, `uuid4`, `random`, database reads against a mutated table).

The non-obvious boundary is this: **the divergence does not surface at the point of nondeterminism.** It surfaces many steps later, when a branch that the original trajectory never took becomes reachable, or when a branch the original trajectory *did* take becomes unreachable. The replay produces a trajectory that is *locally plausible at every step* and *globally wrong*. There is no exception thrown at the divergence point. The forensics engineer sees a clean run, a clean trace, and a conclusion about the incident that is a fiction of the replay harness rather than a fact about the incident.

The invariant that must hold, and that re-execution replay violates, is: **every observation fed to the agent during replay must be bit-identical to the observation fed to the agent during record, or the replay must halt and mark the divergence as a first-class forensic artifact.** Anything weaker converts a debugging tool into a confabulation engine.

What Was Observed

A production agent was instrumented to call a `search_documents(query)` tool that returned the top-k documents from an index that was continuously re-ingested. During an incident, the agent looped: it called `search_documents("refund policy")`, received a document set, extracted a clause, called a downstream `apply_policy(clause_id)` tool, received a rejection, and re-queried with a slightly reformulated string. After eleven iterations the agent emitted a final answer citing a clause that, per the incident report, "did not exist in the index at the time."

The forensics engineer loaded the trajectory and ran the replay harness. The harness re-executed every tool call against the *current* index and re-sampled the model at `temperature=0` (which is not zero — it is greedy decoding, and greedy decoding is still sensitive to prompt-prefix tokenization differences and to any nondeterminism in the serving stack's batching). The replay completed in 40 seconds with no errors. It produced a trajectory of nine iterations, not eleven. It produced a final answer citing a *different* clause. The engineer, trusting the harness, wrote in the postmortem that the agent had "converged after nine iterations," contradicting the incident log's eleven.

The actual failure in the original run was that the index was mid-reingest: `search_documents` had returned a *partially built* result set for one shard (a known race in the ingestion pipeline), and the agent had latched onto a clause from the half-built shard. By the time of replay, the reingest had long completed, so the half-built shard was no longer observable. The replay could not reproduce the bug because the bug lived in a transient state of an external system, and the replay harness had no record of that state — it only had a record of the *call*, not the *result*.

This is the signature of the failure mode. The replay harness recorded the *intent* of each tool call (the arguments) but not the *outcome* (the result bytes). It therefore could not distinguish "the tool returned X because the world was in state S" from "the tool returns X' because the world is now in state S'." The harness had no way to know it had diverged, because it had nothing to compare against.

A second observation, from a different incident, sharpened the point. Here the harness *did* record tool results, and replayed them faithfully. But it re-sampled the model. At step 6 the recorded trajectory had called `delete_record(id=42)`; the replayed trajectory, sampling a slightly different token at the decision boundary, called `list_records()` instead. The harness then tried to serve the recorded result for `delete_record(id=42)` to a call that was now `list_records()`. The harness's lookup was keyed on `(step_index, tool_name)`, so it found no match, and — because the harness was written to be forgiving — it fell through to *live execution* of `list_records()`. The replay issued a real read against production. The forensic run mutated nothing, but it observed live data, and the resulting trace was a chimera: steps 1–5 from the tape, step 6 from the live world, steps 7+ derived from a step-6 result that never existed in the original run.

The chimerism was invisible in the harness's output because the harness logged "replayed 14 steps, 0 errors." The divergence was detectable only by diffing the recorded trajectory's tool-call sequence against the replayed one — a diff the harness did not perform and did not surface.

Condition of Validity

Deterministic replay of an agent trajectory is valid **only** under the conjunction of three conditions, and the failure mode above is precisely the violation of the second:

  1. **Observation fidelity.** Every value the agent observed during record — every tool result, every retrieval hit, every clock read, every environment variable, every model completion — is captured as immutable bytes and re-served verbatim during replay. Not the arguments to the tool; the *result*. The tool is never re-invoked.
  1. **Control-flow fidelity.** The replay re-drives the agent's control flow using the recorded observations, and at every step verifies that the agent's *decision* (which tool to call, with which arguments, or whether to terminate) matches the recorded decision. This is a checkable invariant: `replay_decision == recorded_decision` for every step. If it fails, the replay has diverged, and the divergence is itself the forensic finding — it tells you the original trajectory was not reproducible from its own tape, which means either the tape is incomplete or the model's decision was sensitive to state not captured in the tape (e.g., a hidden system prompt, a sampling seed, a context-window truncation boundary).
  1. **Closure under divergence.** When control-flow fidelity fails, the replay halts at the divergence step and reports: the recorded decision, the replayed decision, the observation that was about to be served, and the token-level logprob delta if available. It does **not** fall through to live execution. It does **not** "best-effort" continue. A forensic replay that continues past a divergence is not a replay; it is a new run wearing the old run's clothes.

The subtle part is condition 2. It cannot be checked by the harness alone, because the harness does not know what the agent "would have" decided — it only knows what the agent *did* decide. The check must be structural: the harness must intercept the agent's decision emission (the tool-call token sequence, or the structured action) *before* dispatch, compare it to the recorded action at that step index, and raise on mismatch. If the harness dispatches first and compares later, a live side effect may already have occurred. The comparison must be a pre-dispatch gate, not a post-hoc audit.

Decision Boundary

The boundary between "this replay is forensically admissible" and "this replay is a confabulation" is drawn at the first observation that cannot be served from the tape. Operationally:

The boundary is *not* drawn at "the replay ran to completion." A replay that runs to completion by falling through to live execution has crossed the boundary without signaling it. The signal must be the halt, not the completion.

Operational Effect

The operational consequence is that **forensic replay must be architected as a tape-replay with a pre-dispatch decision gate, and the tape must capture observations, not just calls.** Concretely:

The effect on incident response is a shift in what the postmortem can claim. Without the gate, the postmortem claims "the agent did X" based on a replay that may have reconstructed a different agent. With the gate, the postmortem claims "the agent did X, and here is the tape proving it, and here is the divergence point (if any) where the tape could not reproduce the run." The second claim is falsifiable. The first is not, and the difference is exactly the difference between forensics and storytelling.

The failure mode is non-obvious because the replay *succeeds*. It produces a trace. The trace looks like a trajectory. The only way to know it is not *the* trajectory is to have a gate that was designed to catch the difference — and most replay harnesses are designed to "just run the agent again," which is precisely the operation that cannot, in principle, reproduce a nondeterministic system's past.

import hashlib
import json
from dataclasses import dataclass
from typing import Any, Optional


class ReplayDivergenceError(RuntimeError):
    """Raised when a replayed agent decision does not match the recorded decision."""


class TapeGapError(RuntimeError):
    """Raised when the tape lacks an observation required to continue replay."""


@dataclass(frozen=True)
class TapeEntry:
    step_index: int
    decision: str          # canonical serialized action, e.g. '{"tool":"search","args":{...}}'
    observation_bytes: bytes
    observation_hash: str  # sha256 of observation_bytes


def _canonical(action: Any) -> str:
    return json.dumps(action, sort_keys=True, separators=(",", ":"))


def _hash(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


class TapeReader:
    """Serves recorded observations. Never invokes a live tool. Never falls through."""

    def __init__(self, entries: list[TapeEntry]):
        self._by_step = {e.step_index: e for e in entries}

    def serve(self, step_index: int) -> TapeEntry:
        entry = self._by_step.get(step_index)
        if entry is None:
            raise TapeGapError(
                f"tape has no observation for step {step_index}; "
                f"record-time instrumentation was incomplete"
            )
        if _hash(entry.observation_bytes) != entry.observation_hash:
            raise TapeGapError(
                f"tape entry {step_index} failed integrity check; "
                f"observation bytes do not match recorded hash"
            )
        return entry


def replay_step(
    tape: TapeReader,
    step_index: int,
    recorded_decision: Any,
    agent_emitted_decision: Any,
) -> bytes:
    """
    Pre-dispatch decision gate. Must be called BEFORE the agent's action is
    dispatched anywhere. Raises on divergence or tape gap; never continues.
    """
    expected = _canonical(recorded_decision)
    actual = _canonical(agent_emitted_decision)

    if actual != expected:
        # Divergence: the agent, fed the tape up to step_index-1, chose
        # differently than it chose at record time. The replay is no longer
        # a replay of the recorded run.
        raise ReplayDivergenceError(
            f"divergence at step {step_index}: "
            f"recorded={expected!r} replayed={actual!r}; "
            f"trajectory is not reproducible from its tape"
        )

    entry = tape.serve(step_index)
    return entry.observation_bytes


def run_replay(tape_entries: list[TapeEntry], agent_fn) -> list[bytes]:
    """
    agent_fn(step_index, prior_observations) -> emitted_decision
    The agent is driven by tape observations only; tools are never live.
    """
    tape = TapeReader(tape_entries)
    observations: list[bytes] = []
    for entry in sorted(tape_entries, key=lambda e: e.step_index):
        emitted = agent_fn(entry.step_index, observations)
        obs = replay_step(tape, entry.step_index, entry.decision, emitted)
        observations.append(obs)
    return observations

The `ReplayDivergenceError` is the load-bearing artifact. It is the only thing standing between a forensic replay and a confabulated one, and it must fire *before* dispatch — because after dispatch, the live world has already been touched, and the replay has already stopped being a replay.