# Under what conditions must an instance treat a replayed agent trace as evidence rather than as a fresh execution: the tool-side-effect divergence boundary in counterfactual debugging **Date of Record:** 2026 November 28 **Scope:** Applies to counterfactual debugging and deterministic replay of recorded agentic execution traces where the agent's tool calls have external side effects (writes, sends, charges, state mutations) and the replay harness re-executes the reasoning loop against recorded or live tool responses. Does not apply to purely observational trace inspection, prompt-only A/B testing, or replay of stateless single-turn inference. ## Core Distinction A recorded agent trace is a *log of a causal process*, not a *program*. Replaying it re-runs a probabilistic sampler over a state that the original run mutated. The critical distinction is between **replay as evidence** (the replayed trace is a faithful counterfactual of the original, and any divergence is attributable to a single intervened variable) and **replay as fresh execution** (the replayed trace is a new run that happens to share a prefix, and its divergence is confounded by every side effect the original produced). Most replay harnesses silently collapse these two into one. They stub the tool layer with recorded outputs so the reasoning loop "sees the same world," then diff the two traces and attribute the divergence to whatever knob the debugger turned. This is valid only under a condition that is almost never checked: that every tool call in the replayed prefix is *idempotent with respect to the recorded effect*, or that its effect was *reversed* before replay. When a tool call is a non-idempotent mutation—`send_email`, `charge_card`, `append_to_ledger`, `delete_row`, `POST /deploy`—the recorded output is a *description of an effect that already happened*, and feeding that description back into the loop does not reproduce the effect's *precondition*. The replayed agent reasons over a world in which the effect is described but not (re)established, or established twice. This is the **tool-side-effect divergence boundary**: the point in a trace where the replayed execution's world-state diverges from the original's because the replay either (a) suppressed a real side effect while presenting its recorded return value as if it occurred, or (b) re-executed a real side effect that the original already applied. Both produce a trace that *looks* like a valid counterfactual but is causally severed from the original at the first non-idempotent call. ## What Was Observed A three-step agent was recorded processing a refund request. The trace: - Step 1: `get_order(order_id=8841)` → `{status: "shipped", amount: 4200}` - Step 2: `issue_refund(order_id=8841, amount=4200)` → `{refund_id: "rf_77", status: "accepted"}` - Step 3: `send_confirmation(customer_id=..., refund_id="rf_77")` → `{delivered: true}` The debugger wanted to test a counterfactual: *what if the model had been given a different refund policy in the system prompt?* The harness replayed the trace with the modified prompt and stubbed all three tools to return their recorded outputs. In 9 of 20 sampled replays, the agent at Step 2 emitted `issue_refund(order_id=8841, amount=4200)` again—identical to the original—and the harness, seeing the stubbed `{refund_id: "rf_77", status: "accepted"}`, recorded the call as *consistent with the original*. The diff report concluded: "policy change had no effect on refund decision." This conclusion was wrong in a subtle way: the replay had *not* re-issued the refund (the stub suppressed it), so the agent's Step 3 `send_confirmation` in the replay was reasoning over a refund that the harness *claimed* existed but had not re-created. The replay's world-state after Step 2 was `{refund: "described but not applied"}`. The original's was `{refund: applied}`. The traces were byte-identical at the observable level and semantically divergent at the world level. The inverse failure appeared in a second harness that did *not* stub mutations: it re-executed `issue_refund` live. The original run had already applied one refund; the replay applied a second. The downstream `get_order` in a longer trace now returned `{refunded_amount: 8400}`, and the agent's Step 4 correctly reasoned "this order has been double-refunded, escalate"—a behavior the original never exhibited. The debugger attributed this escalation to the prompt change. It was an artifact of the replay's own side effect. In both cases the harness produced a *plausible* counterfactual trace. Neither was a valid one. The failure is non-obvious because the traces are locally coherent: every step's inputs and outputs are consistent with the step before it *within the replayed run*. The invalidity is only visible at the seam between the replay's world and the original's world, which no single step exposes. ## Condition of Validity A replayed agent trace is admissible as evidence for a counterfactual claim **if and only if** the following invariant holds at every tool call in the replayed prefix: > **Effect-Equivalence Invariant.** For each tool call *c* in the replayed prefix, the world-state produced by the replay's handling of *c* is observationally equivalent, from the agent's perspective at the *next* step, to the world-state produced by the original handling of *c*—and this equivalence is *established by construction*, not assumed from matching return values. Three constructions satisfy the invariant; a harness must declare which it uses per tool, and the declaration must be checked, not inferred from the tool's name: 1. **Idempotent-and-reapplied.** The tool is genuinely idempotent (re-applying yields the same world-state). The replay may re-execute it live. `get_order` qualifies; `issue_refund` with a server-side dedup key qualifies *only if* the replay reuses the original's idempotency key—a detail harnesses routinely drop. 2. **Reversible-and-reverted.** The original effect was undone before replay (the refund was voided, the email was recalled or the send suppressed at the transport, the deploy was rolled back). The replay may re-execute live against the restored pre-state. 3. **Stubbed-with-explicit-precondition-assertion.** The tool is stubbed, *and* the harness asserts at replay time that the preconditions the agent will read at the next step are the preconditions the original saw. Concretely: a stubbed `issue_refund` must be paired with a stubbed `get_order` that returns the *post-refund* state, because the original agent's next `get_order` would have. A stub that returns the refund's return value while leaving `get_order` at pre-refund state violates the invariant. The boundary condition is the *first* tool call in the trace that is neither idempotent-and-reapplied nor reversible-and-reverted nor stubbed-with-precondition-assertion. Everything before it is admissible evidence. Everything after it is a fresh execution wearing the original's clothes. The debugger's counterfactual claim is only as strong as the prefix before that boundary; the harness must *locate and report* the boundary index, not silently extend the claim past it. A second, subtler condition: even under a valid construction, the replay's *sampling* must be controlled. If the harness re-samples the model at temperature > 0, divergence at a step may be sampling noise rather than the intervened variable. Valid counterfactual replay requires either greedy decoding with a fixed seed *and* a recorded check that the original run's step was itself greedy-consistent, or a paired-sample design (N replays with and without the intervention, divergence attributed only when the paired difference exceeds the sampling variance). A single replayed sample is not evidence of a causal effect; it is one draw. ## Decision Boundary The harness must make a binary decision at each tool call, and the decision must be *derived from the tool's declared effect class*, not from observed behavior: - **Admit as evidence** when the call is within the admissible prefix (all prior calls satisfy the invariant) and the current call's handling is declared and checked against one of the three constructions. The diff report may attribute downstream divergence to the intervened variable. - **Demote to fresh execution** when the call crosses the boundary. The replayed trace from that index onward is a *new* run; its divergence is confounded and must be reported as "replay artifact, not attributable," with the boundary index surfaced. The failure mode to guard against is the harness that *infers* effect class from the recorded return value. A tool returning `{status: "ok"}` may be a read or a write; the return value does not tell you. Effect class must be declared in the tool registry (a `side_effect: none | idempotent | mutating | compensating` field) and the replay must *refuse to start* if any tool in the trace lacks a declaration, rather than defaulting to "assume idempotent." Defaults are where the boundary silently moves. A corollary for counterfactual debugging specifically: when the debugger's intervention is *upstream* of the boundary (e.g., a prompt change at Step 0), the boundary still invalidates the *downstream* comparison even though the intervention is upstream. The intervention being clean does not make the replay clean. The harness must check the boundary *independently* of where the knob was turned. ## Operational Effect Enforcing the invariant changes three things in practice. First, replay harnesses must record, per tool call, the *idempotency key* and the *pre/post world-state fingerprint* (a hash of the observable state the agent reads), not just the return value. The fingerprint is what lets the harness assert precondition equivalence for stubbed calls; without it, construction 3 is unimplementable and the harness is forced to construction 1 or 2, which most mutating tools cannot satisfy. Second, diff reports gain a *boundary index* field. A report that says "divergence at Step 4 attributable to prompt change" becomes "divergence at Step 4; boundary at Step 2 (`issue_refund`, mutating, stubbed without precondition assertion); Steps 2–4 demoted to fresh execution; claim not supported." This is a *less satisfying* report and a *correct* one. The operational cost is that many counterfactual claims that previously looked supported will now be reported as unsupported—which is the point. Third, the harness must refuse to run rather than run wrong. A trace containing an undeclared-effect tool, or a mutating call whose original idempotency key was not recorded, is not replayable as evidence. The correct behavior is a hard failure at harness startup with the offending call index, not a best-effort replay that silently crosses the boundary. Best-effort replay is how the 9-of-20 false-consistency result above was produced: the harness did its best, and its best was a lie about a refund that was never issued. The invariant is cheap to state and expensive to violate undetected. The violation is invisible in any single step and only visible at the seam—which is exactly the seam a counterfactual debugger is trying to reason across. ```python from dataclasses import dataclass from enum import Enum from typing import Optional class EffectClass(Enum): NONE = "none" # pure read; safe to re-execute IDEMPOTENT = "idempotent" # re-execution yields same world-state (needs key reuse) MUTATING = "mutating" # non-idempotent; must be reverted or stubbed w/ precondition COMPENSATING = "compensating" # has a declared inverse; revertible class ReplayBoundaryError(RuntimeError): """Raised when a replayed trace crosses the tool-side-effect divergence boundary and can no longer be admitted as counterfactual evidence.""" @dataclass class ToolCall: index: int name: str effect: Optional[EffectClass] # None == undeclared idempotency_key: Optional[str] # must be present for IDEMPOTENT reuse pre_state_fingerprint: Optional[str] # hash of agent-observable state before call post_state_fingerprint: Optional[str] # hash of agent-observable state after call stub_asserts_precondition: bool = False reverted: bool = False def locate_boundary(trace: list[ToolCall]) -> int: """Return the index of the first call that breaks the Effect-Equivalence Invariant. Calls before the returned index are admissible evidence; the call at the index and everything after it are fresh execution, not counterfactual.""" for call in trace: if call.effect is None: raise ReplayBoundaryError( f"call {call.index} ({call.name}) has no declared effect class; " f"refusing to replay — assuming idempotent is how the boundary moves" ) if call.effect is EffectClass.NONE: continue if call.effect is EffectClass.IDEMPOTENT: if call.idempotency_key is None: raise ReplayBoundaryError( f"call {call.index} ({call.name}) is IDEMPOTENT but no idempotency " f"key was recorded; re-execution would apply a second effect" ) continue if call.effect is EffectClass.COMPENSATING and call.reverted: continue if call.effect is EffectClass.MUTATING and call.stub_asserts_precondition: if call.pre_state_fingerprint is None or call.post_state_fingerprint is None: raise ReplayBoundaryError( f"call {call.index} ({call.name}) is stubbed but lacks pre/post " f"state fingerprints; cannot assert precondition equivalence" ) continue # First non-idempotent, non-reverted, non-asserted call: the boundary. return call.index return len(trace) # entire trace admissible def attribute_divergence(trace: list[ToolCall], divergence_index: int) -> str: boundary = locate_boundary(trace) if divergence_index < boundary: return f"attributable to intervention (divergence {divergence_index} < boundary {boundary})" raise ReplayBoundaryError( f"divergence at {divergence_index} is at or past boundary {boundary} " f"({trace[boundary].name}); demote to fresh execution, claim not supported" ) ```