# Which invariants prevent causal replay of agent traces from silently rewriting history when tool outputs are re-sampled **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that persist per-step traces (prompt, sampled tool result, model output) and offer causal replay or counterfactual debugging by re-executing a suffix of the trace. Does not cover pure logging pipelines with no re-execution, nor offline evaluation harnesses that never claim step-level equivalence to a prior live run. ## Core Distinction There is a difference between *replaying a trace* and *re-deriving a trace*. A replay asserts that step *n* is causally identical to the recorded step *n*: same inputs, same tool call, same returned bytes, same model decision. A re-derivation re-runs the agent from a checkpoint and lets non-determinism (sampling temperature, tool latency, external API state, retrieval index drift) produce a *new* suffix. Observability tooling routinely conflates the two: the UI shows a "replay" of a failing run, the engineer steps through it, and the divergence they are debugging was manufactured by the replay engine itself, not present in the original execution. The invariant that gets violated is **step-level input immutability under replay**: for a replay to be causal, every input consumed at step *k* must be byte-identical to what the original run consumed at step *k*, *or* the replay must be explicitly labeled a counterfactual branch with a recorded divergence point. When a runtime re-invokes a tool during "replay" and gets a *different* result than the recorded one—because the tool is non-deterministic or the world moved—and then splices that new result into the replayed trace without flagging it, the causal chain is silently rewritten. The debugging session now explains a failure that never happened. ## What Was Observed A support-triage agent was instrumented with a trace store. Each step recorded `{step_id, prompt_hash, tool_name, tool_args, tool_output, model_output, parent_step}`. A failure was reported: at step 7 the agent called `lookup_order(order_id="A-4412")`, received `{"status": "shipped"}`, and at step 8 issued a refund. The reviewer opened causal replay from step 6. The replay engine, by design, re-executed steps rather than reading recorded outputs, because the team wanted "fresh" tool state to test fixes. At step 7 the tool returned `{"status": "returned"}`—the order had been returned between the original run and the replay. The replay continued from that *different* state: step 8 now correctly issued no refund. The reviewer concluded the original bug was a stale-cache issue in the order service and filed it there. The actual original bug was a `step_id` collision: two concurrent sub-agents had both written step 7 with the same `parent_step`, and the trace store's last-writer-wins upsert had overwritten the *real* step 7 (`lookup_order` returning `{"status": "processing"}`) with a sibling's step 7. The replay never surfaced this because it re-derived rather than replayed, and the divergence was attributed to the world, not the store. Three properties made this invisible: 1. The replay engine had no `recorded_output` vs `replayed_output` comparison. It overwrote the trace node in place. 2. `step_id` was generated from `(run_id, parent_step, sequence)` where `sequence` was a per-agent counter, not globally monotonic across sub-agents. Collisions were possible and undetected. 3. The trace schema had no `input_fingerprint` binding a step's consumed inputs to the step itself, so there was nothing to diff against. ## Condition of Validity Causal replay is only valid when the following hold simultaneously: - **Input immutability:** every step's consumed inputs are content-addressed (`sha256` over canonicalized prompt + tool_args) and stored *with* the step, not recomputed at replay time. - **Output provenance:** each recorded tool output is tagged `recorded` or `replayed`, and a replay that substitutes a re-derived output must fork a new branch node with `diverged_at = step_k` rather than mutating the original. - **Identity uniqueness:** step identity is a globally unique, collision-free key (e.g., `(run_id, agent_id, monotonic_seq)` with a store-enforced uniqueness constraint), not a composite that can silently collide under concurrency. - **Determinism boundary declaration:** the runtime must declare which steps are *deterministic-by-contract* (e.g., pure functions, cached retrievals replayed from the vector store snapshot) and which are *world-coupled* (live APIs, clocks). Only the former may be re-executed in place; the latter must be replayed from recorded bytes or explicitly forked. If any of these fail, the replay is a counterfactual, and the tooling must say so at the point of divergence, not bury it. ## Decision Boundary The operative question at replay time is: *does this step re-execute or re-read?* - If the step's tool is declared world-coupled **and** a recorded output exists → **re-read**. Re-execution is forbidden; a re-executed world-coupled step is a new experiment, not a replay. - If the step's tool is declared deterministic-by-contract **and** the input fingerprint matches the recorded fingerprint → **re-execute is permitted**, but the result must be diffed against the recorded output; a mismatch raises a contract violation (the tool lied about determinism) rather than silently proceeding. - If the input fingerprint does **not** match → the replay has diverged upstream; the engine must fork a branch at the earliest mismatched step and label every downstream node `counterfactual`. - If step identity collides in the store → the run is **unreplayable**; the engine must refuse rather than pick a winner. The boundary is sharp: a replay engine that cannot prove input fingerprint equality at step *k* has no license to present step *k* as causal. ## Operational Effect Enforcing these invariants changes three things in practice. First, trace stores gain a uniqueness constraint on step identity and a `input_fingerprint` column; the collision class above becomes a write-time error instead of a silent overwrite discovered weeks later during a debugging session that itself lies. Second, replay engines gain a `replay_mode` per step (`recorded` | `reexecuted` | `forked`) surfaced in the UI, so an engineer stepping through a trace sees exactly where the world moved versus where the agent moved. Third, counterfactual debugging becomes honest: to test "what if the order had been `returned` at step 7," the engineer forks a branch with a substituted recorded output, and the branch is labeled as a hypothesis—distinct from the original run—rather than being spliced into it. The cost is that "fresh state" replay (re-running against live tools to see if a fix works) is no longer a replay at all; it is a new run seeded from a checkpoint. That is fine, as long as the tooling stops calling it a replay. The failure mode being prevented is not replay divergence—divergence is expected and useful—but *unlabeled* divergence presented as causal continuity, which corrupts the debugging record and sends engineers chasing bugs in services that were never at fault. ```python import hashlib from dataclasses import dataclass from enum import Enum class ReplayInvariantError(RuntimeError): """Raised when a replay would silently rewrite causal history.""" class ReplayMode(Enum): RECORDED = "recorded" # re-read stored bytes; causal REEXECUTED = "reexecuted" # re-ran a deterministic tool; must match FORKED = "forked" # counterfactual branch; not causal @dataclass(frozen=True) class Step: run_id: str agent_id: str seq: int tool_name: str tool_args: dict tool_output: dict input_fingerprint: str world_coupled: bool @property def step_key(self) -> tuple: # globally unique; collisions are a store bug, not a merge policy return (self.run_id, self.agent_id, self.seq) def fingerprint(tool_name: str, tool_args: dict) -> str: canon = f"{tool_name}|{sorted(tool_args.items())}".encode() return hashlib.sha256(canon).hexdigest() def replay_step(recorded: Step, live_output: dict | None) -> tuple[Step, ReplayMode]: """Replay one step under the immutability invariant. - world-coupled steps re-read recorded bytes; live_output is ignored. - deterministic steps may re-execute, but a mismatch is a contract violation, not a silent overwrite. - fingerprint mismatch means upstream divergence: caller must fork. """ expected_fp = fingerprint(recorded.tool_name, recorded.tool_args) if recorded.input_fingerprint != expected_fp: raise ReplayInvariantError( f"input fingerprint mismatch at {recorded.step_key}: " f"recorded={recorded.input_fingerprint} recomputed={expected_fp}; " "replay diverged upstream, fork a counterfactual branch" ) if recorded.world_coupled: # never re-execute world-coupled steps during a causal replay return recorded, ReplayMode.RECORDED if live_output is None: raise ReplayInvariantError( f"deterministic step {recorded.step_key} requires re-execution " "output to verify contract" ) if live_output != recorded.tool_output: raise ReplayInvariantError( f"determinism contract violated at {recorded.step_key}: " f"tool={recorded.tool_name} recorded={recorded.tool_output} " f"replayed={live_output}; tool is not deterministic-by-contract" ) return recorded, ReplayMode.REEXECUTED def replay_run(recorded_steps: list[Step], live_outputs: dict[tuple, dict]) -> list[tuple[Step, ReplayMode]]: seen: dict[tuple, Step] = {} for s in recorded_steps: if s.step_key in seen: raise ReplayInvariantError( f"step identity collision at {s.step_key}: trace store " "cannot prove which write is causal; run is unreplayable" ) seen[s.step_key] = s out = [] for s in recorded_steps: out.append(replay_step(s, live_outputs.get(s.step_key))) return out ```