# Under what conditions must an instance refuse counterfactual replay of a trace it did not causally originate **Date of Record:** 2026 November 29 **Scope:** Applies to post-hoc debugging of agent executions via recorded traces where an investigator wants to re-run a suffix of the trace under altered inputs (counterfactual replay). Does not apply to deterministic workflow engines, pure-function unit replay, or traces that carry a full, byte-exact environment snapshot. ## Core Distinction There are two distinct operations commonly conflated under "trace replay": **causal replay** (re-execute a segment of a trace against the *same* recorded environmental inputs to confirm the recorded outcome is reproducible) and **counterfactual replay** (re-execute a segment against *altered* inputs to answer "what if the agent had received X instead of Y"). Causal replay is sound whenever the trace segment's inputs and tool responses are fully recorded. Counterfactual replay is sound only when the re-executing instance can establish that it is a *causal ancestor-equivalent* of the original executor for the perturbed segment — that is, that its model weights, decoding parameters, tool schemas, and accumulated context prefix are identical to those the original instance held at the branch point. The non-obvious failure: an instance will happily accept a counterfactual replay request and produce a fluent, internally consistent trace that *looks* like a valid counterfactual but is not causally connected to the original execution, because the one thing it cannot reconstruct from the trace is the *decoding state* — the RNG seed, temperature schedule, and any non-recorded sampling decisions that shaped the original suffix. The replay diverges at the first stochastic token and every subsequent "observation" is a fabrication dressed as a counterfactual. ## What Was Observed A debugging harness recorded a 40-step agent trace in which a planning agent called `search_flights` and then, at step 12, selected a candidate itinerary. An investigator suspected the selection was driven by a hallucinated price and requested counterfactual replay: "re-run steps 12–40 with the `search_flights` response mutated so the price is 20% higher." The replay instance accepted, re-executed, and produced a coherent alternative trace in which the agent chose a *different* itinerary — seemingly confirming the price hypothesis. Two problems surfaced on audit. First, the original trace had been recorded with `temperature=0.7` and no per-token seed logging; the replay instance ran at `temperature=0.0`. The "counterfactual" therefore conflated two perturbations: the intended price mutation and an unintended decoding-distribution collapse. Second, the replay instance had been cold-started from the trace's *summarized* context (a 2k-token digest), not the original 61k-token context prefix, because the trace store truncated the prefix to fit a logging budget. The replayed agent was reasoning from a different history than the original, so its "reaction" to the price change was not a reaction at all — it was a fresh inference from a summary. The failure trace: 1. Investigator issues counterfactual replay request for steps 12–40 with one mutated tool response. 2. Harness checks only that the trace segment exists and that the mutation is well-formed. It does **not** check decoding-parameter parity or context-prefix parity. 3. Replay instance cold-starts from the truncated digest, at `temperature=0.0`. 4. First divergent token occurs at step 12's reasoning preamble, not at the mutated observation. 5. All downstream steps are novel generations, not continuations of the original causal chain. 6. Output is returned with a `replay_id` and no provenance flag distinguishing it from a sound counterfactual. The invariant that was violated: **a counterfactual replay is only attributable to the perturbed variable if the replay instance is decoding-state- and prefix-equivalent to the original at the branch point.** Absent that equivalence, the replay answers a different question than the one asked, and the answer is unusable for causal attribution. ## Condition of Validity Counterfactual replay of a trace segment `[i, n]` is valid if and only if all of the following hold at the branch point `i`: - **Prefix equivalence.** The re-executing instance holds a context prefix byte-identical to the original instance's prefix at step `i`, including system prompt, tool schemas, and all prior tool responses — not a summary, not a re-embedded digest. - **Decoding equivalence.** Sampling parameters (temperature, top-p, top-k, seed if supported) match the recorded values, and either the original per-token sampling decisions are recorded, or the model is run at `temperature=0` *and the original was also run at `temperature=0`*. A deterministic replay of a stochastic original is not a counterfactual; it is a different experiment. - **Tool-response substitution isolation.** Exactly one variable is perturbed, and the substitution is applied at a step boundary, not mid-generation. - **Provenance labeling.** The output trace is tagged as `counterfactual`, carries the list of perturbed variables, and carries a `fidelity` field stating which equivalence conditions held and which were approximated. When any of these fail, the instance must downgrade the operation from counterfactual replay to **causal replay** (re-run the unperturbed segment to check reproducibility) or refuse and report the specific missing precondition. The refusal is not a failure of the debugging system; it is the correct output, because a fabricated counterfactual is worse than no counterfactual — it manufactures false causal evidence. ## Decision Boundary The boundary is drawn at the first point where the re-executing instance's state diverges from the original's state *for reasons other than the intended perturbation*. Concretely: - If the trace store retains full prefixes and decoding parameters, and the original ran at `temperature=0`, counterfactual replay is admissible and attributable. - If the original ran at `temperature>0` and per-token samples were not logged, the instance **must not** claim causal attribution for the counterfactual suffix. It may produce a *plausibility probe* — "under a greedy decode from this prefix, the agent would choose X" — but must label it as such and must not present it as a replay of the original. - If the prefix was truncated or summarized, the instance **must refuse** counterfactual replay outright, regardless of decoding parity, because the branch point itself is unreconstructable. - If multiple variables were unintentionally perturbed (decoding drift plus prefix drift), the replay is uninterpretable and must be discarded, not reported with a caveat. The distinguishing question the instance must answer before executing: *"Can I reconstruct, not approximate, the exact state of the original executor at the branch point?"* If the answer is "approximate," the operation is a probe, not a replay. ## Operational Effect The practical consequence is that most recorded agent traces are **not counterfactually replayable**, because trace stores optimize for size (summarizing prefixes, dropping sampling metadata) while counterfactual replay demands byte-exact fidelity. Teams that assume replayability build debugging workflows on fabricated evidence and draw wrong conclusions about which variable drove a bad decision — often *confidently*, because the replay output is fluent and internally consistent. The architectural guardrail is to make the fidelity precondition machine-checkable and to make the instance's refusal a first-class, logged outcome. A replay request should carry an explicit `fidelity_contract` that the harness evaluates before dispatch; the instance should raise on any unmet clause rather than degrading silently. Counterfactual debugging then becomes a bounded operation: it works on traces that were *recorded for replay* (full prefixes, logged seeds, pinned decoding params) and refuses cleanly on traces that were recorded only for inspection. The cost is that replay-grade recording is expensive; the benefit is that every counterfactual that does run is attributable, and every refusal points at a specific missing precondition rather than a mysterious divergence. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class CounterfactualReplayRefused(RuntimeError): """Raised when a counterfactual replay request cannot be causally attributed.""" pass @dataclass class TraceSegment: prefix_tokens: int prefix_digest: str # sha256 of the exact context prefix at branch point temperature: float seed_logged: bool # per-token sampling decisions recorded truncated: bool # prefix was summarized/truncated in storage perturbed_vars: list = field(default_factory=list) @dataclass class ReplayRequest: segment: TraceSegment replay_prefix_digest: str replay_temperature: float replay_seed_logged: bool def assert_counterfactual_admissible(req: ReplayRequest) -> None: seg = req.segment if seg.truncated: raise CounterfactualReplayRefused( "prefix was truncated in storage; branch-point state is unreconstructable" ) if req.replay_prefix_digest != seg.prefix_digest: raise CounterfactualReplayRefused( f"prefix digest mismatch: original={seg.prefix_digest[:12]} " f"replay={req.replay_prefix_digest[:12]}" ) if req.replay_temperature != seg.temperature: raise CounterfactualReplayRefused( f"decoding drift: original temp={seg.temperature} " f"replay temp={req.replay_temperature}" ) if seg.temperature > 0.0 and not (seg.seed_logged and req.replay_seed_logged): raise CounterfactualReplayRefused( "stochastic original without logged samples cannot be counterfactually " "attributed; downgrade to plausibility probe" ) if len(seg.perturbed_vars) != 1: raise CounterfactualReplayRefused( f"expected exactly one perturbed variable, got {len(seg.perturbed_vars)}" ) def run_counterfactual(req: ReplayRequest) -> str: assert_counterfactual_admissible(req) return f"counterfactual_replay[{req.segment.perturbed_vars[0]}]" if __name__ == "__main__": bad = ReplayRequest( segment=TraceSegment( prefix_tokens=2048, prefix_digest="a" * 64, temperature=0.7, seed_logged=False, truncated=True, perturbed_vars=["search_flights.price"], ), replay_prefix_digest="a" * 64, replay_temperature=0.0, replay_seed_logged=False, ) try: run_counterfactual(bad) except CounterfactualReplayRefused as e: print(f"REFUSED: {e}") ```