# What happens when an instance replays a poisoned tool trace: nondeterministic re-derivation and the counterfactual audit invariant **Date of Record:** 2026 December 1 **Scope:** Applies to post-incident root-cause analysis of agentic traces where an auditor re-executes a recorded trajectory (or a counterfactual branch of it) against live or snapshot tooling. Does not apply to pure reasoning-only traces with no external tool calls, nor to forward execution during normal operation. ## Core Distinction There are two things an auditor can mean by "replay." **Trace replay** re-feeds the recorded observations (tool outputs, retrieved chunks, peer messages) back into the model without re-invoking any external system. **Re-derivation** re-invokes the tools and lets them produce fresh outputs, then continues from those. Trace replay is deterministic in *input* but not in *output*: the model's sampling is stochastic unless the auditor pins seed, temperature, and the full decode state. Re-derivation is nondeterministic in *both* input and output, because every tool is a new experiment against a world that has moved. The failure mode this record covers is the silent conflation of these two modes: an auditor intending a trace replay accidentally performs a re-derivation, the fresh tool outputs diverge from the recorded ones, the model's reasoning diverges accordingly, and the audit concludes the agent "should have" taken an action that the *original* agent never had the information to take. The root cause attributed to the incident is then a counterfactual artifact of the replay harness, not a property of the original run. This is the **replay-divergence misattribution**, and it is the single most common way agentic post-mortems go wrong. ## What Was Observed A three-tool agent (search → fetch → summarize) failed to answer a customer query correctly. The recorded trace showed: search returned document IDs `[A, B]`; fetch(A) returned a 200 with body `X`; fetch(B) returned a 503; the agent summarized from `X` alone and omitted a fact that lived only in `B`'s body. During the audit, the harness was configured to "replay" the trace. But the fetch tool was registered with its live HTTP adapter, not the recorded-response fixture. At audit time, `B` was healthy and returned body `Y`. The replayed agent, now seeing `Y`, produced a correct answer. The auditor's diff engine flagged the divergence and concluded: *the original agent's reasoning was defective; given the same tool results it would have succeeded.* The remediation ticket was filed against the summarizer's prompt. The actual root cause was the 503 on `B` — a transient upstream failure — and the agent's failure to retry or to flag the missing document. The audit had inverted the causal story because it re-derived a world in which the failure never happened. The tell was subtle: the replayed trace's token count was *lower* than the original (the model summarized `Y` more tersely than `X`), and the fetch call's latency in the replay log was 340ms versus 31ms in the original — the live call, not the fixture. Neither signal was surfaced by the harness by default. ## Condition of Validity A counterfactual audit is only valid when the following invariant holds for every replayed step: > **Observation Provenance Invariant (OPI):** For each step *i* in the replayed trajectory, the observation fed to the model at step *i* must be bit-identical to the observation recorded at step *i* in the original trace, *unless* the step is explicitly marked as a counterfactual intervention point, in which case the divergence must be recorded and the downstream trace must be treated as a new branch rather than a replay of the original. The corollary is that a re-derivation is never a replay. It is a **branch**, and branches do not license conclusions about the original trajectory's reasoning — only about the policy's behavior under the new observation. Mixing the two is the violation. Two additional conditions bound the invariant: 1. **Decode determinism.** Even with OPI satisfied, the model's output at step *i* is only reproducible if the decode is pinned: same model weights (including any silent version bumps), same tokenizer, same seed, same temperature/top-p, same system prompt, same tool-schema serialization order. A model that has been updated between incident and audit will re-derive different reasoning from identical observations — this is a *trace replay* failure, distinct from re-derivation, and it produces "the agent would never have said that" conclusions that are artifacts of the model swap. 2. **Counterfactual labeling.** Any intervention (flipping a 503 to a 200, swapping a retrieved chunk, injecting a peer message) must be recorded as an explicit edge in the audit DAG, and every conclusion drawn downstream must carry that edge as a premise. An unlabeled intervention is indistinguishable from a replay bug. ## Decision Boundary The auditor must decide, per step, between three modes, and the decision is not free — it is forced by what the question is: - **"Did the agent reason correctly given what it saw?"** → trace replay, OPI enforced, decode pinned. Divergence in output is a finding about the model; divergence in input is a harness bug. - **"What would the agent have done if tool *T* had behaved differently?"** → re-derivation, but the intervention must be at *T* and only at *T*; all other tools must be replayed from fixtures. The result is a branch, not a verdict on the original. - **"Did the agent's failure depend on the transient 503?"** → this is a *necessity* test, not a replay. It requires the counterfactual branch (B healthy) *and* the original branch, compared under identical decode. Only the paired comparison licenses a causal claim. The boundary failure occurs when the harness defaults to re-derivation for all three questions, because re-derivation is easier to wire up (no fixture capture required). The default is wrong for questions 1 and 3, and for question 3 it destroys the paired comparison that the question depends on. A second boundary: **the 503 itself may have been nondeterministic at the transport layer.** If the original fetch(B) failed due to a race in a connection pool, re-deriving it will almost always succeed, and the auditor will systematically under-attribute failures to transport flakiness. The only defense is to capture the raw transport-level error (status, headers, timing, connection state) at record time and replay *that*, not the request. ## Operational Effect The practical consequence is that **agentic traces must be captured as replayable artifacts at record time, not reconstructed at audit time.** This means: - Every tool call's full response (status, headers, body, latency, and any transport error) is persisted, not just the parsed result the agent consumed. - The decode configuration (model ID with hash, seed, temperature, top-p, stop sequences, tool-schema serialization) is persisted alongside the trace. - Retrieval results are persisted as the exact chunk IDs and text, because the vector index will have drifted by audit time. - Peer/auditor messages in multi-agent traces are persisted with their originating instance ID and sequence number, so the baton-passing order can be reconstructed. Without this, the audit is not an audit — it is a new run of a similar-looking agent against a different world, and any root cause it reports is a hypothesis about *that* run. The remediation tickets filed against it will be aimed at the wrong component, and the next incident will reproduce the same failure because the real cause — the un-retried 503, the un-flagged missing document — was never in the fix path. The guardrail is a harness-level assertion: before any replay step, verify that the observation about to be fed matches the recorded observation, and refuse to proceed if it does not, unless the step is explicitly tagged as an intervention. The assertion is cheap; the misattribution it prevents is expensive. ```python import hashlib import json from dataclasses import dataclass, field from typing import Any, Literal class ReplayDivergenceError(RuntimeError): """Raised when a replay step's observation does not match the recorded trace.""" class UnlabeledInterventionError(RuntimeError): """Raised when a counterfactual intervention is applied without an explicit edge tag.""" @dataclass class RecordedStep: index: int tool: str observation: Any observation_hash: str decode_config_hash: str @dataclass class ReplayHarness: recorded: list[RecordedStep] interventions: dict[int, Any] = field(default_factory=dict) mode: Literal["replay", "counterfactual"] = "replay" @staticmethod def _hash(obj: Any) -> str: return hashlib.sha256( json.dumps(obj, sort_keys=True, default=str).encode() ).hexdigest() def step(self, index: int, live_observation: Any, decode_config: dict) -> Any: rec = self.recorded[index] if index in self.interventions: if self.mode != "counterfactual": raise UnlabeledInterventionError( f"intervention at step {index} applied in replay mode; " f"a counterfactual branch must be explicitly declared" ) return self.interventions[index] if self.mode == "replay": live_hash = self._hash(live_observation) if live_hash != rec.observation_hash: raise ReplayDivergenceError( f"step {index} tool={rec.tool}: observation hash " f"{live_hash[:12]} != recorded {rec.observation_hash[:12]}; " f"harness is re-deriving, not replaying — abort audit" ) live_decode = self._hash(decode_config) if live_decode != rec.decode_config_hash: raise ReplayDivergenceError( f"step {index}: decode config hash {live_decode[:12]} != " f"recorded {rec.decode_config_hash[:12]}; model or sampling " f"drifted between incident and audit" ) return rec.observation def audit(self, live_observations: list[Any], decode_config: dict) -> list[Any]: out = [] for i, obs in enumerate(live_observations): out.append(self.step(i, obs, decode_config)) return out ```