# What happens when an instance replays a recorded agentic session and the tool layer is not hermetic: counterfactual drift in forensic reconstruction **Date of Record:** 2026 November 21 **Scope:** Applies to deterministic replay and counterfactual auditing of recorded agent sessions (trajectory logs containing model outputs, tool calls, tool results, and context snapshots) where the replay harness re-executes tool calls against live or partially live dependencies. Does not apply to replay of pure model-output transcripts (no tool re-execution) or to replay against a fully captured, byte-identical tool-response tape. ## Core Distinction There are two things an incident-forensics replay can mean, and conflating them is the root of the failure: 1. **Trace replay (hermetic):** the harness feeds the *recorded* tool results back into the agent, never re-invoking the tool. The agent's decisions are re-derived from a frozen observation stream. This is deterministic up to model sampling, and sampling can be pinned with a seed or eliminated by replaying recorded token choices. 2. **Counterfactual replay (non-hermetic):** the harness re-executes tool calls against a live system to ask "what would the agent have done if the tool had returned X?" or "was the failure caused by the tool or the policy?" The forensic invariant that is routinely assumed and routinely violated: **a counterfactual replay is only valid if the re-executed tool call is observationally equivalent to the original at the moment of replay, or if the divergence is explicitly modeled as the counterfactual variable.** When a tool is non-deterministic, time-dependent, or stateful (search indices, market data, `git` working trees, rate-limited APIs, LLM-backed sub-tools), the "counterfactual" branch silently mixes two causes: the intervention you intended and the drift you did not. The reconstruction then attributes an agent failure to a policy error when the actual cause was a tool-layer divergence introduced by the auditor. ## What Was Observed A recorded session shows an agent calling `get_account_balance(acct)` early, receiving `$1,200`, then calling `transfer(acct, $1,100)`, then calling `get_account_balance(acct)` again and receiving `$1,200` (unchanged), then calling `transfer` again and being rejected by an insufficient-funds guard. The recorded trajectory ends in a rejection the incident report flags as "agent looped on transfers; guard prevented double-spend." An auditor replays the session to test the hypothesis "the agent would have stopped if the second balance read had shown the debit." The replay harness re-executes `get_account_balance` against the live ledger. In the live ledger, the account has since been reconciled, so the second read now returns `$100`. The agent, seeing `$100`, does *not* attempt the second transfer. The auditor concludes: "confirmed—the agent's loop was caused by a stale balance read; the guard is a backstop, not the root cause." The conclusion is unsound. In the original session the second read returned `$1,200` because the transfer had not yet posted (asynchronous settlement). The live replay returned `$100` because settlement had since completed. The auditor's "intervention" (changing the second read) was not the only thing that changed: the first read, the settlement timing, and the transfer's idempotency key all differ between the two runs. The replay measured the *current* ledger, not the agent's response to a hypothetical. The agent's actual failure mode—acting on a read that was stale *relative to its own prior write*—was erased by the replay, because the replay's read was fresh. The observable signature of this class of bug is a **replay divergence that is not attributable to the declared intervention**. Concretely: the harness records `(tool_name, args, recorded_result, replayed_result)`. When `recorded_result != replayed_result` for any call *outside* the declared counterfactual set, the replay is contaminated. In the trace above, the first `get_account_balance` alone diverged (`$1,200` vs. `$100`), which is sufficient to invalidate the counterfactual even though the auditor only intended to vary the second read. ## Condition of Validity A counterfactual replay is a valid causal probe under exactly this condition: for every tool call $c_i$ in the session, the replayed observation $r'_i$ equals the recorded observation $r_i$ **unless** $c_i$ is in the declared intervention set $I$, and for $c_i \in I$ the divergence $\Delta_i = r'_i - r_i$ is the *only* channel through which the counterfactual enters the agent's context. Formally, the replay is valid iff the replayed context at each decision step $t$ differs from the recorded context only through the declared intervention: $$ \text{ctx}'_t \setminus \text{ctx}_t \subseteq \{\,\text{effect of } \Delta_i : c_i \in I,\ i \le t\,\} $$ Any element of $\text{ctx}'_t \setminus \text{ctx}_t$ outside that set is **contamination**. Contamination sources in agentic sessions, in rough order of frequency: - **Time-dependent tools.** `now()`, relative-date resolvers, TTL caches, "last 24h" queries. The replayed clock is not the recorded clock. - **Stateful stores.** The tool's backend has advanced (settlement, index rebuild, cache eviction, garbage collection). A read returns a different value for reasons unrelated to the intervention. - **Non-deterministic tools.** Sampling-based sub-agents, `ORDER BY RANDOM()`, distributed reads without a snapshot, fuzzy search with tie-breaking. - **Side-effecting tools re-executed.** A replayed `transfer` posts a second transfer; the second replay now sees the first replay's effect. Replays are not idempotent unless the tool is. - **Rate-limit and quota state.** The replay's tool calls consume budget the original did not, changing later tool behavior (429s, degraded responses). - **Model non-determinism leaking into tool args.** If the model is re-sampled, it may emit different tool *arguments*, which is a different intervention than the one declared. The invariant the harness must enforce: **hermetic by default, intervention by exception.** Every tool call is served from the recorded tape unless explicitly registered as an intervention, and every registered intervention must declare its expected divergence and be logged with the actual divergence for post-hoc contamination checks. ## Decision Boundary The boundary between "valid counterfactual" and "contaminated replay" is not whether the tool *can* be re-executed, but whether the re-executed call is **observationally equivalent outside the intervention set**. Operationally: - **Replay as trace (hermetic) when** the forensic question is "what did the agent do, and why?" — i.e., attribution of the recorded failure. This requires no re-execution and is always valid modulo model sampling, which you pin or replay. - **Replay as counterfactual (non-hermetic) only when** the intervention set is declared, every non-intervention call is served from tape, and the tool layer supports snapshot reads or you accept and *log* the contamination. The question "what would the agent have done if X?" is answerable only if X is the sole difference. - **Never** re-execute a side-effecting tool during replay without an idempotency key derived from the original call, or without a sandboxed ledger. A replay that mutates production state is not an audit; it is a second incident. The decision rule the harness applies at each tool call: ``` if call in declared_interventions: result = execute_live(call) # the counterfactual log_divergence(call, recorded, result) else if tape.has(call): result = tape.get(call) # hermetic: serve recorded else: raise ReplayContamination(...) # cannot serve, cannot honestly execute ``` The `else` branch is the critical one. A harness that falls back to live execution when the tape misses is the contamination vector. A harness that raises is honest: it tells the auditor the replay cannot answer the question without a declared intervention. ## Operational Effect When the invariant holds, counterfactual replay becomes a sound causal instrument: each replay isolates one variable, and the divergence between replayed and recorded trajectories is attributable to the declared intervention. Incident reports can then distinguish "the agent's policy was wrong" from "the tool's observation was stale" from "the guard masked a policy error" with evidence, not narrative. When the invariant is violated, the failure is silent and directional: the replay tends to *understate* tool-layer faults and *overstate* policy faults, because live tools are usually healthier than the tools were at incident time (reconciled ledgers, rebuilt indices, patched endpoints). The auditor sees a well-behaved tool and concludes the agent was at fault. This is the forensic analogue of survivorship bias, and it is the single most common way agentic incident post-mortems reach the wrong root cause. The guardrail is structural, not procedural: the replay harness must be **hermetic by construction** (tape-first, live-execution only for declared interventions, hard failure on tape miss), must **log per-call divergence** between recorded and replayed observations, and must **reject any replay whose non-intervention divergence is non-empty**. The audit artifact is then not just the replayed trajectory but the contamination ledger that certifies it. ```python from dataclasses import dataclass, field from typing import Any, Callable, Optional class ReplayContamination(RuntimeError): """Raised when a counterfactual replay diverges outside the declared intervention set.""" pass class TapeMiss(ReplayContamination): """Raised when a non-intervention tool call has no recorded result to serve.""" pass @dataclass class ToolCall: name: str args: dict @dataclass class RecordedResult: call: ToolCall value: Any @dataclass class ContaminationLedger: entries: list = field(default_factory=list) def record(self, call: ToolCall, recorded: Any, replayed: Any, intervened: bool) -> None: self.entries.append({ "tool": call.name, "args": call.args, "recorded": recorded, "replayed": replayed, "intervened": intervened, }) def non_intervention_divergences(self) -> list: return [e for e in self.entries if not e["intervened"] and e["recorded"] != e["replayed"]] class HermeticReplayHarness: """ Serves every tool call from the recorded tape unless the call is in the declared intervention set. Live execution is permitted ONLY for declared interventions; a tape miss on a non-intervention call is a hard failure. """ def __init__( self, tape: dict, # tape_key(call) -> RecordedResult live_tools: dict, # tool_name -> Callable[[dict], Any] interventions: set, # set of tape_keys declared as counterfactual ledger: Optional[ContaminationLedger] = None, ): self.tape = tape self.live_tools = live_tools self.interventions = interventions self.ledger = ledger or ContaminationLedger() @staticmethod def _key(call: ToolCall) -> tuple: return (call.name, tuple(sorted(call.args.items()))) def invoke(self, call: ToolCall) -> Any: key = self._key(call) intervened = key in self.interventions if intervened: tool = self.live_tools.get(call.name) if tool is None: raise ReplayContamination( f"intervention declared for {call.name} but no live tool registered" ) replayed = tool(call.args) recorded = self.tape[key].value if key in self.tape else None self.ledger.record(call, recorded, replayed, intervened=True) return replayed if key not in self.tape: raise TapeMiss( f"non-intervention call {call.name}{call.args} has no recorded result; " f"refusing live execution (would contaminate the counterfactual)" ) recorded = self.tape[key].value self.ledger.record(call, recorded, recorded, intervened=False) return recorded def certify(self) -> None: """Call after replay: reject the audit if any non-intervention call diverged.""" bad = self.ledger.non_intervention_divergences() if bad: raise ReplayContamination( f"counterfactual replay contaminated: {len(bad)} non-intervention " f"divergence(s), first={bad[0]['tool']}{bad[0]['args']}" ) ``` The `certify()` call is the invariant made executable: a replay that cannot certify its own hermeticity is not evidence, and the harness must refuse to emit it as such.