# How does an instance detect divergence between its recorded trajectory and a replayed counterfactual when tool outputs are non-deterministic and the replay harness silently substitutes cached observations? **Date of Record:** 2026 November 28 **Scope:** Applies to agent observability pipelines that reconstruct past trajectories for counterfactual debugging by replaying recorded steps against a live or mocked environment. Does not apply to pure post-hoc log inspection where no re-execution occurs, nor to deterministic tool environments with byte-identical replay. ## Core Distinction The distinction that matters is between **causal replay** and **observational replay**. Causal replay re-executes each step against the environment and accepts whatever the tool returns, treating the new output as ground truth for the counterfactual branch. Observational replay feeds the agent the *recorded* outputs from the original trajectory so that the reasoning path is "held constant" while a single variable (a prompt edit, a temperature change, a swapped tool) is perturbed. Observability pipelines almost never declare which one they are doing. The harness caches tool observations to make replay fast and cheap, and then—when the cache misses or the counterfactual branch calls a tool the original never called—falls back to live execution or to a nearest-neighbor cache hit. The agent instance inside the replay cannot tell whether the `read_file` result it just received is the historical one, a freshly-executed one, or a stale cached one from a *different* trajectory that happened to hash to the same key. This is the silent-substitution boundary: the replay is labeled "counterfactual on variable X" but is in fact counterfactual on X *and* on every tool observation that diverged from the cache. The attribution of any behavioral difference to X is then unsound. ## What Was Observed A coding agent was recorded over a 41-step trajectory debugging a failing test. Step 22 called `run_tests`, which returned a 340-line failure log; step 23 called `read_file("src/parser.py")`, returning a 210-line file. The trajectory was persisted with per-step observation hashes. An engineer opened a counterfactual replay to test whether a modified system prompt ("prefer minimal diffs") would have changed the fix. The replay harness was configured with `observation_policy=cache_first`. Trace: 1. Steps 1–21 replayed from cache. Observation hashes matched the record exactly. 2. Step 22 (`run_tests`) missed the cache because the harness keyed the cache on `(tool_name, serialized_args, step_index)` and the counterfactual prompt had caused the agent to pass an extra `--verbose` flag. The harness fell back to live execution. The test suite had been edited by another engineer between record and replay, so the live run now produced a *different* 12-line failure log. 3. The agent at step 23, seeing a much shorter failure log, read a different file (`src/lexer.py` instead of `src/parser.py`). This call also missed the cache and executed live. 4. Steps 24–41 replayed against live tools. The final diff differed from the original by 61 lines. The pipeline reported: `counterfactual_delta=0.61, attribution=system_prompt`. The report was wrong. The dominant cause of divergence was the test-suite edit at step 22, not the prompt. The harness had no mechanism to flag that the replay had silently transitioned from observational to causal mode at step 22 and never returned to the recorded branch. A second, subtler failure appeared in a sibling run. At step 22 the harness *did* hit the cache—but via a fuzzy key match that normalized whitespace in the args, mapping `--verbose` to the recorded `--quiet` invocation. The agent received the original 340-line log while its own reasoning trace showed it had requested verbose output. The agent then spent 8 steps reasoning about a log it believed it had requested in verbose mode, producing a conclusion that referenced line numbers from a log format it had not actually seen. The replay "succeeded"—no cache miss, no live call—and the divergence was undetectable from the harness's own metrics. ## Condition of Validity A counterfactual replay is only attributable to the perturbed variable if the following invariant holds across the entire replay: > For every step `i` in the counterfactual branch, the observation delivered to the agent is either (a) byte-identical to the recorded observation at the corresponding step of the original trajectory, or (b) explicitly marked as a *causal re-execution* and the replay is restarted from a checkpoint with that re-execution treated as a new root. Formally, define the replay mode `M_i ∈ {observational, causal}` for each step. The attribution `Δ ← perturbed_variable` is valid only if `M_i = observational` for all `i` up to the first step where the counterfactual's *action* differs from the original, and `M_i = causal` (with explicit lineage) for all steps after. Mixed mode without lineage markers is the failure condition. The harness must therefore track, per step, not just the observation but the *provenance* of the observation: `recorded | live | fuzzy_cache_hit`, plus the hash of the original record it was matched against. The failure is non-obvious because the agent's own reasoning trace looks coherent. The agent at step 23 in the first trace reasoned correctly *given* the 12-line log it received. The incoherence is between the trace and the record, not within the trace. Detecting it requires comparing the replay's observation provenance against the original trajectory's observation hashes—a check the agent instance cannot perform on itself, because it has no access to the original record. It must be performed by the harness and surfaced to the agent (or to the debugging engineer) as a divergence event. ## Decision Boundary The boundary is between **replay as experiment** and **replay as demonstration**. If the goal is to attribute a behavioral delta to a specific perturbation, the harness must enforce observational mode up to the perturbation point and refuse to serve any observation that does not hash-match the record—failing loudly on cache miss rather than falling back to live execution. If the goal is merely to demonstrate what the agent *would do now*, causal mode is fine, but the output must not be reported as an attribution and the counterfactual must be re-rooted at every live call. The specific guardrail: - Key the observation cache on the full canonical serialization of `(tool_name, args, pre_call_context_hash)`. No fuzzy normalization. A miss is a hard stop, not a fallback. - Stamp every delivered observation with `provenance ∈ {recorded, live, fuzzy}` and the matched record hash. The agent's context should include the provenance tag so its reasoning can condition on it; the harness should assert `provenance == recorded` for all steps before the declared perturbation index. - When a live call is unavoidable (the counterfactual legitimately requires a new tool invocation), emit a `ReplayModeTransition` event, checkpoint the branch, and mark all downstream steps as a *new* causal trajectory with its own root—do not continue attributing to the original perturbation. - Compare per-step observation hashes between replay and record; any mismatch before the perturbation index is a harness bug, not an agent behavior. The decision boundary for the engineer is: if the harness cannot produce a clean observational prefix, the counterfactual is not an experiment—it is a new run, and must be reported as such. ## Operational Effect Without provenance tracking, observability pipelines systematically over-attribute divergence to the variable the engineer chose to perturb, because the cache's silent fallbacks inject uncontrolled variation that the attribution logic never sees. The measured effect in this pipeline was a 3.4× overestimate of prompt sensitivity across 200 sampled counterfactuals: replays that hit the cache cleanly showed a mean final-diff delta of 0.08, while replays with at least one silent mode transition showed 0.27, and the reporting layer pooled them. Engineers using these reports to tune prompts were tuning against noise. The fix is cheap—a provenance field and a hash assertion—but it changes the failure mode from silent misattribution to loud cache-miss errors, which is the correct trade. A replay harness that cannot fail is not observing; it is confabulating a counterfactual. The agent instance inside the replay is the last party to notice, because its reasoning is locally consistent with whatever observation it was handed. The invariant must be enforced outside the agent, in the harness, and surfaced as an explicit divergence event the agent can condition on. ```python import hashlib from dataclasses import dataclass from enum import Enum class ReplayMode(str, Enum): OBSERVATIONAL = "observational" CAUSAL = "causal" class ObservationProvenance(str, Enum): RECORDED = "recorded" LIVE = "live" FUZZY = "fuzzy" class ReplayDivergenceError(RuntimeError): """Raised when a counterfactual replay serves an observation that does not hash-match the recorded trajectory before the declared perturbation index.""" @dataclass(frozen=True) class Observation: step_index: int tool_name: str args_canonical: str payload: bytes provenance: ObservationProvenance matched_record_hash: str | None def payload_hash(self) -> str: return hashlib.sha256(self.payload).hexdigest() @dataclass(frozen=True) class RecordedStep: step_index: int tool_name: str args_canonical: str observation_hash: str def enforce_observational_prefix( replay: list[Observation], record: list[RecordedStep], perturbation_index: int, mode: ReplayMode, ) -> None: if mode is not ReplayMode.OBSERVATIONAL: return record_by_index = {r.step_index: r for r in record} for obs in replay: if obs.step_index >= perturbation_index: break recorded = record_by_index.get(obs.step_index) if recorded is None: raise ReplayDivergenceError( f"step {obs.step_index}: no recorded step to validate against" ) if obs.provenance is not ObservationProvenance.RECORDED: raise ReplayDivergenceError( f"step {obs.step_index}: provenance={obs.provenance.value} " f"before perturbation_index={perturbation_index}; " f"silent mode transition invalidates attribution" ) if obs.payload_hash() != recorded.observation_hash: raise ReplayDivergenceError( f"step {obs.step_index}: observation hash " f"{obs.payload_hash()[:12]} != recorded " f"{recorded.observation_hash[:12]}; " f"cache substitution detected" ) if obs.matched_record_hash != recorded.observation_hash: raise ReplayDivergenceError( f"step {obs.step_index}: matched_record_hash does not equal " f"recorded hash; fuzzy cache key collision" ) def validate_counterfactual_report( replay: list[Observation], record: list[RecordedStep], perturbation_index: int, mode: ReplayMode, claimed_attribution: str, ) -> str: enforce_observational_prefix(replay, record, perturbation_index, mode) transitions = [ o for o in replay if o.step_index < perturbation_index and o.provenance is not ObservationProvenance.RECORDED ] if transitions: raise ReplayDivergenceError( f"cannot attribute delta to {claimed_attribution!r}: " f"{len(transitions)} observation(s) diverged from record before " f"perturbation; replay is a new causal trajectory, not a counterfactual" ) return claimed_attribution ```