# How does an instance detect when a deterministic replay of an agent trace diverges because the tool sandbox re-seeded its RNG between the original run and the replay **Date of Record:** 2026 November 29 **Scope:** Applies to forensic replay of recorded agent traces (tool-call logs, model I/O, RNG seeds, environment snapshots) where the replay is expected to reproduce the original execution byte-for-byte for incident reconstruction. Does not apply to "best-effort" replays used only for qualitative debugging, nor to stateless single-turn inference where no tool sandbox participates. ## Core Distinction A security forensic replay is not a re-execution; it is an *identity check on a recorded state trajectory*. The invariant that makes forensics sound is: > Given the same ordered sequence of (model output, tool input, environment seed, dependency version), the agent must produce the same ordered sequence of (tool output, state mutation, next model input). The subtle failure is that this invariant is usually enforced only at the *model* layer (temperature=0, fixed seed) and never at the *tool* layer. Tool sandboxes frequently call `random`, `uuid4`, `time.time`, `hash()`, or read entropy from `/dev/urandom` without those sources being part of the recorded trace. When replay re-initializes the sandbox, the RNG is re-seeded from the *replay host's* entropy pool, not the original run's. The model output at step *k* is bit-identical; the tool output at step *k* is not. The trace forks silently, and every downstream "verification" is now a verification of a different execution than the one under investigation. The non-obvious part: the fork is *invisible to diffing the model I/O*. Both runs produce plausible, well-formed tool results. The divergence only becomes detectable when a *later* tool call consumes the non-deterministic value as an argument, at which point the argument hash of the tool call itself changes — but the recorded argument hash was already trusted as "the original," so the replay engine reports a *tool mismatch* rather than the true cause, which is *RNG re-seeding at step k−n*. ## What Was Observed A three-step trace from a file-triage agent: - Step 1 — model calls `scan_dir("/data")`. Tool returns a list of 4,000 paths in `os.scandir` order. - Step 2 — model calls `sample(paths, k=20)` using a helper that internally does `random.sample(paths, 20)`. - Step 3 — model calls `read_file(p)` for each sampled path and summarizes. Original run: `random.sample` seeded from process default (`random.seed()` unset → OS entropy). Replay run: same. The two `sample()` calls returned *different 20-element subsets* of the same 4,000 paths. Step 3's tool-call *arguments* therefore differed. The replay engine flagged 20 argument-hash mismatches at step 3 and reported "trace tampering at step 3." The actual root cause was step 2. The engine's diffing was anchored at the wrong step because it compared *normalized* tool outputs (it stripped the sampled list from step 2's recorded output on the assumption that lists are unordered) and only compared *raw* argument hashes at step 3. The investigator spent a day chasing a phantom tamper. A second, sharper observation: in a variant where `sample()` was replaced by `secrets.choice()` for a "random audit" path, replay *consistently* diverged and the engine reported "deterministic replay failed: nondeterminism in tool" — but with no pointer to *which* tool, because the exception was raised inside the sandbox subprocess and surfaced only as a generic `ReplayDivergence` at the trace boundary. ## Condition of Validity Deterministic replay holds only if, for every tool invocation in the trace, the following tuple is fully recorded *and* fully restored before replay: ``` (tool_name, tool_version, args_bytes, env_seed_snapshot, clock_snapshot, entropy_source_state, fs_snapshot_hash) ``` The failure mode described here is precisely the case where `entropy_source_state` is *absent* from the record. Two invariants must be checked before trusting any replay verdict: 1. **Seed closure.** Every call site that can reach a nondeterministic primitive (`random.*`, `secrets.*`, `uuid.*`, `time.*`, `os.urandom`, `hash()` on `str`, iteration over a `set`, `dict` insertion order across processes) must be either (a) recorded as a seed in the trace, or (b) proven unreachable from the tool's public surface. This is a static property of the tool, not a runtime one. 2. **Argument-hash anchoring.** The replay engine must compare tool-call arguments at the *earliest* step where any recorded value was consumed, not at the step where the engine happens to notice. If step 2's output was fed into step 3's input, the divergence originates at step 2 regardless of where the diff fires. If either invariant is unverified, the replay verdict is *unfalsifiable*: a "match" proves nothing (the RNG may have coincidentally agreed), and a "mismatch" cannot distinguish tampering from re-seeding. ## Decision Boundary The instance must classify a replay outcome into exactly one of four states before acting on it: - **CLEAN** — all seeds present, all argument hashes match at first-consumption step. Replay is evidentiary. - **SEED_GAP** — one or more tool calls lack a recorded entropy/clock seed. Replay is *inconclusive*; must not be cited as tamper evidence. Escalate to "obtain original environment snapshot" or "declare trace non-replayable." - **DIVERGENT_AT(k)** — seeds present, argument hash mismatch at step *k*. This is a *real* divergence and must be attributed to step *k*, not to the step where the engine first noticed. If *k* < first-noticed step, the engine's attribution is wrong and must be corrected before reporting. - **TAMPER_SUSPECTED** — seeds present, divergence at *k*, and the divergence cannot be explained by any recorded nondeterministic primitive reachable from the tool at *k*. Only this state justifies a security escalation. The boundary that trips most implementations: they collapse SEED_GAP and TAMPER_SUSPECTED into a single "replay failed" bucket. That collapse is the operational bug. A missing seed is a *record-keeping* failure; a tamper is an *adversarial* failure. Treating the former as the latter produces false incident reports; treating the latter as the former buries real ones. ## Operational Effect Once the four-state classification is enforced, three downstream behaviors change: 1. **Trace format.** The recorder must capture an entropy snapshot per tool call, not per session. Per-session snapshots are insufficient because a long-running tool can consume entropy mid-call (e.g., a `sample()` inside a loop). The snapshot must include the RNG algorithm, the seed bytes, and the call counter. 2. **Replay engine.** The differ must operate on a *first-consumption graph*: for each recorded value, the earliest step at which it was passed as an argument. Divergence is reported at that step. This requires the recorder to log argument provenance, not just argument bytes. 3. **Incident triage.** Any TAMPER_SUSPECTED verdict must be re-run against a *seed-complete* trace before escalation. If the original trace is seed-incomplete, the incident is downgraded to "non-replayable" and the investigation proceeds by other means (host logs, network capture) — never by citing the replay as proof. The invariant to enforce in code: a replay function must refuse to return a boolean "match" and must instead return a structured verdict that names the originating step and the missing seed if any. A boolean is the failure. ```python from __future__ import annotations import hashlib import json from dataclasses import dataclass from enum import Enum from typing import Any class ReplayVerdictError(RuntimeError): """Raised when a replay verdict cannot be soundly produced.""" class Verdict(Enum): CLEAN = "clean" SEED_GAP = "seed_gap" DIVERGENT_AT = "divergent_at" TAMPER_SUSPECTED = "tamper_suspected" @dataclass(frozen=True) class ToolCall: step: int tool: str args: dict[str, Any] output: Any # Entropy/clock state captured at call entry. None means "not recorded". entropy_seed: bytes | None clock_ns: int | None # Steps whose outputs were consumed as args here (provenance). consumed_from: tuple[int, ...] def _arg_hash(args: dict[str, Any]) -> str: return hashlib.sha256( json.dumps(args, sort_keys=True, default=str).encode() ).hexdigest() def replay_verdict( recorded: list[ToolCall], replayed: list[ToolCall], ) -> tuple[Verdict, int | None, str]: """ Returns (verdict, originating_step_or_None, detail). Invariants enforced: - Every recorded call must have entropy_seed and clock_ns. Missing seed => SEED_GAP, never TAMPER_SUSPECTED. - Divergence is attributed to the EARLIEST step whose recorded output was consumed downstream, not to the step where the diff first fires. """ if len(recorded) != len(replayed): raise ReplayVerdictError( f"trace length mismatch: recorded={len(recorded)} " f"replayed={len(replayed)}" ) # 1. Seed closure check first. A missing seed invalidates the # entire replay for evidentiary purposes. missing = [ c.step for c in recorded if c.entropy_seed is None or c.clock_ns is None ] if missing: return ( Verdict.SEED_GAP, None, f"entropy/clock seed missing at steps {missing}; " f"replay is inconclusive", ) # 2. Build first-consumption map: for each step, the earliest # step whose output reached it. first_consumer: dict[int, int] = {} for c in recorded: for src in c.consumed_from: first_consumer.setdefault(src, c.step) # 3. Compare argument hashes. Attribute divergence to the # earliest consumed-from step, not to the current step. for r, p in zip(recorded, replayed): if _arg_hash(r.args) != _arg_hash(p.args): origin = first_consumer.get(r.step, r.step) # If the divergent step itself has no recorded # nondeterministic primitive and its origin is itself, # this is a genuine unexplained divergence. if origin == r.step and r.entropy_seed is None: raise ReplayVerdictError( f"step {r.step}: divergence with no recorded seed " f"and no upstream consumer; cannot classify" ) return ( Verdict.DIVERGENT_AT, origin, f"argument hash mismatch at step {r.step} " f"originates at step {origin}", ) # 4. Outputs that were never consumed as args must still match # if they are terminal (final answer to user). for r, p in zip(recorded, replayed): if r.step not in first_consumer and r.output != p.output: return ( Verdict.TAMPER_SUSPECTED, r.step, f"terminal output mismatch at step {r.step} " f"with seed present and no upstream consumer", ) return (Verdict.CLEAN, None, "all seeds present, all hashes match") def assert_clean_or_raise(recorded: list[ToolCall], replayed: list[ToolCall]) -> None: verdict, step, detail = replay_verdict(recorded, replayed) if verdict is not Verdict.CLEAN: raise ReplayVerdictError( f"replay not evidentiary: verdict={verdict.value} " f"step={step} detail={detail}" ) ```