# Which invariants prevent replay divergence when an agent's tool-call transcript is re-executed against a mutated environment **Date of Record:** 2026 November 28 **Scope:** Applies to deterministic replay of recorded MCP/A2A protocol transcripts for counterfactual debugging of agentic workflows, where the replay target is a live or partially-live tool surface. Does not apply to pure in-memory transcript simulation with fully synthetic tool stubs, nor to single-turn stateless completions. ## Core Distinction A recorded transcript is not a program. It is a *trace* of a program whose control flow was decided by a probabilistic sampler, interleaved with side effects executed against a stateful, non-deterministic environment. Replay fidelity therefore decomposes into two independent axes that are routinely conflated: 1. **Sampler fidelity** — does the model, under the same context, emit the same tokens (or at least the same tool-call structure)? This is approximately achievable with fixed seeds, pinned model versions, and temperature zero, and is what most "replay" tooling actually measures. 2. **Environment fidelity** — does the *effect* of each recorded tool call, when re-executed against the current environment, produce the postcondition the original run observed? The non-obvious failure lives entirely on axis 2 and is invisible to axis 1. A replay can be token-identical at every step and still diverge catastrophically, because the agent's *next* decision was conditioned on the *result* of the tool call, not on the call itself. When a recorded `search_docs(query="refund policy")` returns a different document set on replay (index rebuilt, doc edited, retrieval model upgraded), the recorded assistant turn that consumed the old result is now a non-sequitur — and if you force it, you are replaying a decision against evidence the model never saw. The transcript is *self-consistent only with respect to the result payloads it embeds*, not with respect to the tool surface that produced them. The invariant that prevents divergence is therefore not "same inputs produce same outputs." It is: **every recorded assistant turn must be re-derived from the recorded tool result, and any mismatch between the re-executed tool result and the recorded one must halt replay rather than silently substitute.** Counterfactual debugging depends on this boundary being *loud*, because the entire value of a counterfactual ("what if the retrieval had returned the correct doc?") requires knowing precisely which recorded results are authentic and which are being perturbed. ## What Was Observed A support-triage agent workflow was recorded over 14 turns: 6 assistant messages, 5 tool calls (2× `search_docs`, 2× `get_order`, 1× `issue_refund`), and 3 tool results. The transcript was captured with full request/response envelopes including `tool_call_id`, result payloads, and a `result_digest` (SHA-256 of the canonicalized payload) written by the MCP client at capture time. Replay was launched 72 hours later against the same MCP server to debug a misclassification. The failure trace: - **Turn 3 replay:** `search_docs(query="refund policy", top_k=5)` re-executed. The index had been rebuilt. The recorded result was 5 chunks; the replay returned 5 chunks with 3 overlapping and 2 new. The client did *not* compare digests — it passed the fresh result to the model. - **Turn 4 divergence:** The recorded assistant turn had called `get_order(order_id="A-4471")` because the recorded retrieval surfaced an order-reference chunk. The replayed retrieval surfaced a *policy-exception* chunk instead. The model, now seeing different evidence, called `search_docs` again instead of `get_order`. The replayed call sequence diverged at step 4 of 11. - **Turn 7 silent corruption:** Because the replay harness had a "resume from checkpoint" mode, it re-injected the recorded turns 5–11 *on top of* the diverged turns 3–4, producing a transcript with two `search_docs` calls that never happened in sequence and an `issue_refund` whose preceding `get_order` result was stale. The refund was issued during replay against a live order. - **Post-hoc:** The replay was reported as "successful — 11/11 turns replayed." Digest comparison had been disabled by default in the harness config (`verify_tool_results: false`), and the divergence was only caught by manual diff. The critical observation: **the harness had no notion of a result being *consumed*.** It treated tool results as inputs to be refreshed, not as evidence whose identity the recorded assistant turn was bound to. The `result_digest` existed and was correct; it was simply never enforced as a precondition for advancing the replay cursor. ## Condition of Validity Deterministic replay of an agent transcript is valid for counterfactual debugging **only if** all of the following hold. Each is a precondition, not a best practice: 1. **Result-identity binding.** Every recorded assistant turn is tagged with the `tool_call_id` and `result_digest` of the result it consumed. Replay must verify the digest of any re-executed result against the recorded digest *before* the turn is admitted. A mismatch is a divergence event, not a refresh. 2. **Side-effect quarantine.** Any tool call with non-idempotent external effects (`issue_refund`, `send_email`, `write_file`) must be replayed against a recorded-effect stub or a sandboxed double, never against the live surface. The transcript records the *intent*; replay must not re-assert it. 3. **Cursor monotonicity.** The replay cursor advances only when the current turn's preconditions (digest match, prior turn admitted) hold. There is no "resume from checkpoint N" that skips unadmitted turns; a checkpoint is a *record* of admission state, not a shortcut around it. 4. **Divergence is terminal, not recoverable-by-substitution.** When a re-executed result diverges, the harness must either (a) halt and surface the divergence with both payloads, or (b) enter an explicit *counterfactual branch* where the recorded result is substituted and every downstream turn is re-derived from the model — never a mix of replayed and re-derived turns within one branch. The invariant in one sentence: **a recorded assistant turn is only admissible if the evidence it consumed is bit-identical to the evidence present at replay time, or if the branch is explicitly marked as counterfactual and all downstream turns are re-derived.** ## Decision Boundary The boundary between "replay" and "counterfactual" is where teams get hurt, because both look like "re-run the transcript." The decision rule: - If `result_digest` matches → admit the recorded turn, advance cursor. This is *replay*. - If `result_digest` mismatches and the tool is read-only → **do not** substitute silently. Either halt, or open a counterfactual branch keyed to `(turn_index, original_digest, new_digest)` and re-derive all subsequent turns from the model with the new result. The branch must be labeled; downstream recorded turns are *discarded*, not overlaid. - If `result_digest` mismatches and the tool is side-effecting → halt unconditionally. A side effect whose precondition evidence changed is not replayable; it is a new execution and must be re-authorized. - If the tool is unavailable at replay time → treat as digest mismatch (unavailable ≠ unchanged). The failure mode this prevents is the *hybrid transcript*: a sequence that is part recorded, part re-derived, with no marker distinguishing which turns are authentic. Hybrid transcripts are worse than no replay, because they produce confident-looking debugging artifacts that are causally incoherent — the agent's reasoning at turn 7 was conditioned on turn 4's evidence, which in the hybrid never existed. ## Operational Effect Enforcing result-identity binding converts a class of silent corruptions into loud halts, at the cost of replay fragility: transcripts become non-replayable the moment any read-only dependency mutates. This is the correct trade. The operational consequences: - **Replay success rate drops** from ~100% (because everything "replays") to the fraction of transcripts whose read-only dependencies are pinned. Teams must pin retrieval indexes, snapshot tool versions, and record `result_digest` at capture. Unpinned transcripts are explicitly *not replayable* and should be labeled as such rather than silently re-run. - **Counterfactual branches become first-class artifacts.** Each branch carries `(parent_transcript, divergence_turn, original_digest, substituted_digest, re_derived_turns[])`. Debugging "what if retrieval had worked" produces a *new* transcript that is fully re-derived from the divergence point, not a patched original. - **Side-effect safety is structural.** Quarantine is enforced at the tool-dispatch layer by tool classification, not by harness discipline. A misclassified side-effecting tool is a config error that halts replay, not a live refund. - **The `result_digest` becomes the load-bearing field.** It must be computed over a canonicalized payload (stable key order, normalized floats, stripped volatile fields like timestamps and request IDs) or it will mismatch on every replay for spurious reasons, training operators to disable it — which is exactly how the observed incident happened. The harness config default `verify_tool_results: false` is the single most dangerous line in any replay tool. It must default to `true`, and disabling it must require an explicit, logged override that marks the resulting transcript as `unverified_replay` in its metadata. ```python import hashlib import json from dataclasses import dataclass, field from enum import Enum class ReplayDivergenceError(RuntimeError): """Raised when a re-executed tool result does not match the recorded digest.""" class SideEffectInReplayError(RuntimeError): """Raised when a side-effecting tool is dispatched during replay.""" class ToolClass(Enum): READ_ONLY = "read_only" SIDE_EFFECTING = "side_effecting" @dataclass(frozen=True) class RecordedTurn: turn_index: int tool_call_id: str tool_name: str tool_class: ToolClass result_digest: str # sha256 over canonicalized payload, captured at record time @dataclass class ReplayState: cursor: int = 0 admitted: list = field(default_factory=list) divergences: list = field(default_factory=list) branch: str = "authentic" # or "counterfactual:::" def canonical_digest(payload: dict) -> str: # Strip volatile fields before hashing; stable key order; no whitespace variance. volatile = {"timestamp", "request_id", "server_latency_ms"} clean = {k: v for k, v in payload.items() if k not in volatile} blob = json.dumps(clean, sort_keys=True, separators=(",", ":")).encode() return hashlib.sha256(blob).hexdigest() def admit_turn( recorded: RecordedTurn, reexecuted_payload: dict, state: ReplayState, *, allow_counterfactual: bool, ) -> ReplayState: if recorded.turn_index != state.cursor: raise ReplayDivergenceError( f"cursor {state.cursor} != turn {recorded.turn_index}; " "checkpoint resume across unadmitted turns is forbidden" ) if recorded.tool_class is ToolClass.SIDE_EFFECTING: raise SideEffectInReplayError( f"turn {recorded.turn_index}: {recorded.tool_name} is side-effecting; " "must be replayed against a recorded-effect stub, not the live surface" ) actual = canonical_digest(reexecuted_payload) if actual != recorded.result_digest: state.divergences.append( { "turn": recorded.turn_index, "tool_call_id": recorded.tool_call_id, "recorded": recorded.result_digest, "actual": actual, } ) if not allow_counterfactual: raise ReplayDivergenceError( f"turn {recorded.turn_index} ({recorded.tool_name}): result digest " f"mismatch {recorded.result_digest[:12]} -> {actual[:12]}; " "recorded assistant turn consumed evidence that no longer exists" ) # Open a labeled counterfactual branch; downstream recorded turns are discarded. state.branch = ( f"counterfactual:{recorded.turn_index}:" f"{recorded.result_digest[:12]}:{actual[:12]}" ) state.cursor = recorded.turn_index + 1 return state state.admitted.append(recorded.turn_index) state.cursor = recorded.turn_index + 1 return state def replay( transcript: list[RecordedTurn], reexecute, # callable(RecordedTurn) -> dict *, allow_counterfactual: bool = False, ) -> ReplayState: state = ReplayState() for turn in transcript: payload = reexecute(turn) state = admit_turn( turn, payload, state, allow_counterfactual=allow_counterfactual ) if state.branch != "authentic": # Counterfactual branch: stop replaying recorded turns; caller must # re-derive all subsequent turns from the model. break return state ```