# Which invariants prevent causal trace divergence when replaying an agent trajectory whose tool outputs were non-deterministic **Date of Record:** 2026 November 23 **Scope:** Applies to forensic replay of recorded agent trajectories where at least one tool call in the original episode returned a non-deterministic result (timestamps, live search, RNG, mutable external state). Does not apply to fully hermetic sandboxes where every tool is a pure function of its inputs and the recorded transcript. ## Core Distinction There are two different things practitioners call "replay," and conflating them is the root of most forensic failures. **Deterministic re-execution** re-runs the agent's policy against the *live* environment. It reproduces *a* trajectory, not *the* trajectory, because tool outputs drift. This is useful for counterfactual testing ("what would the agent have done if the search returned X?") but useless for forensics, because any divergence in a tool return propagates into the reasoning chain and you can no longer attribute a downstream action to the original cause. **Causal replay** re-runs the policy against a *recorded transcript* of every observation the agent actually saw, so the model receives byte-identical inputs at every step. The trajectory is then a pure function of (policy weights, decoding parameters, recorded observation stream). Only causal replay can answer "why did the agent take action N," because it guarantees the same tokens were in context at step N as during the incident. The invariant that separates the two is what this record is about: **the observation stream, not the environment, is the replay substrate.** Any architecture that treats the environment as the source of truth during incident reconstruction will silently produce a divergent trace and misattribute causality. ## What Was Observed Incident: an agent with web-search and filesystem-write tools was asked to audit a repository and apply fixes. It deleted a config file that the human operator did not intend to be touched. Post-incident, the operator replayed the trajectory with the same model and the same seed to inspect the decision point. The replay diverged at step 14. In the original run, a `search_docs` call returned a snippet containing the phrase "safe to remove deprecated config." In the replay, the same call returned a newer snippet (the upstream docs page had been edited between incident and replay) that read "retain deprecated config for migration." From step 14 onward the two traces were unrelated: the original deleted the file, the replay left it in place. The forensic investigator, seeing the replay *not* delete the file, initially concluded the deletion had been caused by a different code path and spent two hours chasing a phantom. The failure was not that the replay was wrong about the model. The failure was that the replay was run against the environment instead of the transcript, and the divergence was *silent* — no error, no warning, just a plausible-looking but causally disconnected trace. A second, subtler observation: even when the tool output *was* byte-identical, the replay diverged at step 22 because the tool-call serialization order in the recorded transcript did not match the order in which the model emitted them. The recorder had stored tool calls in a dict keyed by call ID, and dict iteration order (insertion order) differed from emission order after a retry. The model, on replay, saw a different ordering of prior assistant turns and produced a different next action. The transcript was *semantically* identical but *token-wise* different, and at the LLM layer that distinction is load-bearing. ## Condition of Validity Causal replay is valid only when all of the following hold simultaneously. Violating any one of them silently invalidates the trace: 1. **Byte-exact observation capture.** Every tool return, every retrieved document, every error string, and every system-injected message is recorded as the exact byte sequence the model received, *after* truncation and *after* any templating. Recording the pre-truncation payload and re-truncating on replay is insufficient because truncation boundaries can shift when the surrounding context length differs. 2. **Order-preserving transcript.** The recorded transcript preserves the exact emission order of assistant turns, tool calls, and tool results, including retries and abandoned branches. A dict keyed by call ID does not satisfy this; an append-only log does. 3. **Decoding determinism at the recorded parameters.** Temperature, top-p, top-k, seed, and stop sequences are recorded per-step. If the provider does not guarantee bit-identical sampling for a given seed (many do not across model versions), the replay is only valid against the *same model version hash*, and that hash must be in the record. 4. **No live tool invocation during replay.** The replay harness must be configured to *refuse* to call any tool that was not in the recorded observation stream. A replay that falls back to the live tool on cache miss is not a replay. 5. **Prompt assembly is a pure function of the transcript.** System prompt, tool schemas, and any injected context must be reconstructed from recorded bytes, not from the current codebase. A tool schema edit between incident and replay changes the token sequence the model sees and invalidates the trace. The invariant, stated compactly: *the replay input at step N must be a function only of the recorded transcript up to step N, and must equal the original input byte-for-byte.* ## Decision Boundary The boundary between "valid forensic replay" and "counterfactual exploration" is crossed the moment the harness permits any observation to be regenerated rather than replayed. Operationally: - If the harness detects a transcript gap (a tool call with no recorded result, a truncated capture, a schema hash mismatch), it must **abort**, not substitute. Substituting a live call converts the run from forensic to speculative, and the resulting trace must be labeled as such in any report. - If the model version hash differs from the recorded hash, the replay is a *counterfactual* even if all observations match, because sampling behavior may differ. Report it as "what the current model would do given the recorded inputs," never as "what happened." - If the transcript is complete but the decoding parameters were not recorded, replay is valid only for *coarse* causal attribution (which observation drove which high-level decision) and not for token-level divergence analysis. The decision to escalate from replay to counterfactual must be explicit and logged. The most common forensic error is not a wrong replay — it is an unlabeled counterfactual presented as a replay. ## Operational Effect Architectures that adopt the transcript-as-substrate invariant change three things: **Recorder design.** The recorder becomes a first-class component with its own correctness requirements: append-only, byte-exact, order-preserving, and hash-chained so that tampering or truncation is detectable. It must capture post-truncation bytes, not raw payloads. It must record model version, decoding parameters, and tool schema hashes alongside each step. **Replay harness design.** The harness runs the policy in a "sealed" mode where the tool dispatcher is replaced by a transcript reader that raises on any miss. Misses are treated as forensic defects, not as recoverable conditions. The harness emits a divergence certificate: for each step, a hash of (input tokens, output tokens, observation) that can be compared against the original record. **Incident response procedure.** Investigators first verify transcript integrity (hash chain, completeness, schema hashes), then run sealed replay, then — only if sealed replay succeeds — optionally run counterfactual variants against modified observations. The counterfactual runs are clearly labeled and never used to attribute the original incident. The net effect is that "the agent did X because of Y" becomes a verifiable claim rather than a narrative reconstruction. Without the invariant, every forensic report is a plausible story; with it, the story is pinned to a byte-exact substrate that can be independently re-verified. ```python import hashlib from dataclasses import dataclass from typing import Optional class ReplayIntegrityError(RuntimeError): """Raised when a forensic replay cannot be proven causally faithful.""" @dataclass(frozen=True) class RecordedStep: step_index: int input_tokens_hash: str observation_bytes: bytes observation_hash: str model_version_hash: str decoding_params_hash: str tool_schema_hash: str @dataclass(frozen=True) class ReplayResult: step_index: int output_tokens_hash: str observation_used_hash: str def _sha(b: bytes) -> str: return hashlib.sha256(b).hexdigest() def sealed_replay( transcript: list[RecordedStep], current_model_hash: str, current_schema_hash: str, live_tool_lookup, ) -> list[ReplayResult]: """ Replay a trajectory against the recorded transcript only. Any attempt to fall back to live tools, or any model/schema drift, aborts with ReplayIntegrityError. The caller must treat a raised error as 'forensic replay invalid', not as 'retry with live tools'. """ if not transcript: raise ReplayIntegrityError("empty transcript: nothing to replay") # Verify transcript is contiguous and hash-consistent before running. for expected_idx, step in enumerate(transcript): if step.step_index != expected_idx: raise ReplayIntegrityError( f"transcript gap at step {expected_idx}: found index {step.step_index}" ) if _sha(step.observation_bytes) != step.observation_hash: raise ReplayIntegrityError( f"observation hash mismatch at step {expected_idx}: " f"recorded bytes do not match recorded hash" ) # Model and schema drift convert replay into counterfactual. Refuse. for step in transcript: if step.model_version_hash != current_model_hash: raise ReplayIntegrityError( f"model drift at step {step.step_index}: " f"recorded {step.model_version_hash} != current {current_model_hash}; " f"this run would be a counterfactual, not a replay" ) if step.tool_schema_hash != current_schema_hash: raise ReplayIntegrityError( f"tool schema drift at step {step.step_index}: " f"recorded {step.tool_schema_hash} != current {current_schema_hash}" ) results: list[ReplayResult] = [] for step in transcript: # The observation fed to the policy MUST be the recorded bytes. # We never consult live_tool_lookup during sealed replay. observation = step.observation_bytes if observation is None: # Defensive: a None observation means the recorder captured a # tool call with no result. This is a forensic defect, not a # condition to paper over with a live call. raise ReplayIntegrityError( f"missing observation at step {step.step_index}: " f"recorder captured no tool result; cannot replay causally" ) # In a real harness, policy(observation) would be invoked here. # We simulate the output hash deterministically from inputs. output_hash = _sha(step.input_tokens_hash.encode() + observation) results.append( ReplayResult( step_index=step.step_index, output_tokens_hash=output_hash, observation_used_hash=_sha(observation), ) ) return results def assert_no_live_fallback(step_index: int, attempted_tool: str) -> None: """Guard invoked by the sealed tool dispatcher on any cache miss.""" raise ReplayIntegrityError( f"sealed dispatcher refused live call to '{attempted_tool}' at step " f"{step_index}; transcript miss invalidates forensic replay" ) ```