# Where must an instance fork its trace to make counterfactual replay sound: speculative-branch contamination at the first divergent tool call **Date of Record:** 2026 November 27 **Scope:** Applies to multi-agent systems that record speculative execution traces (branching rollouts, parallel candidate plans, or draft-then-verify pipelines) and later replay them for counterfactual analysis, root-cause attribution, or audit. Does not apply to single-shot, non-branching agent invocations where no speculative state is ever merged back into a canonical trace. ## Core Distinction There is a difference between *replaying a trace* and *replaying a trace soundly*. Replay is the mechanical re-execution of recorded steps. Soundness is the guarantee that every observation fed to the replayer at step *k* is a function only of the branch's own ancestry up to step *k* — not of a sibling branch that happened to share a mutable resource. The failure mode lives exactly at this seam: speculative branches that share a tool executor, a scratchpad, a vector-store write buffer, or a rate-limited API client will *cross-contaminate* at the first side-effecting tool call that is not idempotent and not branch-scoped. The canonical trace then records a step whose inputs are reproducible but whose *outputs* are not, because the sibling branch mutated the world between the original execution and the replay. Counterfactual divergence analysis — "what would have happened if branch B had taken action X instead of Y?" — silently returns a number that is not attributable to X at all. It is attributable to interleaving order. ## What Was Observed A planner agent emits three candidate plans (A, B, C) over the same task. A router dispatches them to a shared pool of workers. Each worker calls the same `write_memory` tool against a single episodic store keyed by `(task_id, slot)`. The branches were intended to be independent — each was supposed to write to its own slot namespace — but the slot key was derived from a hash of the *task*, not the *branch*, so all three branches raced on the same three slots. The recorded trace for branch A shows, at step 7: ``` step 7 | tool=write_memory | args={slot: "s2", value: "deadline=Friday"} step 8 | tool=read_memory | args={slot: "s2"} -> "deadline=Friday" ``` Replay of A is faithful. Now run the counterfactual: "what if A had written `deadline=Monday` at step 7?" The replayer re-executes A with the modified write, then reads `s2` at step 8 and gets `deadline=Friday` — because branch B's original write landed after A's replay write and before A's replay read. The divergence delta comes back as *zero*: the counterfactual appears to have no effect, when in fact the effect was overwritten by a sibling that should not exist in A's causal past. The analyst concludes the deadline choice was causally inert. It was not; the measurement was corrupted by a write that belongs to a different branch's lineage. The tell is subtle: the replay is *deterministic* (same inputs, same interleaving on a single-threaded replayer) but *not sound* (the interleaving is not part of A's ancestry). Determinism without causal isolation produces reproducible lies. ## Condition of Validity Counterfactual replay of a speculative branch is sound if and only if all three hold: 1. **Write isolation.** Every side-effecting tool call in a branch writes to a namespace partitioned by `(task_id, branch_id, generation)`. A branch may *read* its own ancestry's writes and any frozen pre-task snapshot; it may not read a sibling's writes, even if the sibling is "earlier" in wall-clock time. 2. **Fork-point monotonicity.** The replay fork must occur at or before the first step whose behavior depends on a shared mutable resource. If the original trace's first shared-resource touch is step 7, forking at step 9 is already unsound — steps 7 and 8 in the replayed prefix must be re-derived from the isolated namespace, not copied from the canonical trace. 3. **Idempotency or recorded external effects.** For tools that mutate state outside the agent's control (sending email, charging a card, calling a third-party API), the trace must record the *observed output* of the original call and the replayer must substitute that output rather than re-invoke. Otherwise the replay's counterfactual is contaminated by a live external effect the original never saw. Violating (1) is the contamination above. Violating (2) is the "fork too late" error: the replayer trusts a canonical prefix that was itself shaped by sibling interference. Violating (3) is the "double-spend" error: the counterfactual charges the card twice and the divergence delta includes a real-world side effect. ## Decision Boundary The boundary is not "isolate everything" — that is prohibitively expensive and destroys the sharing that makes speculative execution worth doing. The boundary is: **isolate exactly up to the first non-idempotent, non-branch-scoped effect, and no further.** Concretely, a trace is replayable-for-counterfactuals iff its recorded fork point `f` satisfies `f <= min(step indices of shared-resource touches)`. Compute this as a per-branch scan over the trace: for each step, classify the tool as `PURE`, `BRANCH_SCOPED`, or `SHARED_MUTABLE`. The fork point must precede the first `SHARED_MUTABLE`. If the trace was recorded without branch-scoped namespaces, no fork point satisfies the invariant and the trace must be marked non-replayable rather than replayed approximately. This is a hard refusal, not a warning. An approximate replay of a contaminated trace is worse than no replay, because it produces a confident causal attribution that is actually an artifact of scheduling. ## Operational Effect Downstream, three things change: - **Trace schema gains a `causal_epoch` field** on every side-effecting step, and the replayer refuses to fork after the minimum `causal_epoch` of any `SHARED_MUTABLE` step in the branch. This is the guardrail that makes the invariant enforceable at write time, not just diagnosable at read time. - **Counterfactual deltas become attributable.** When the invariant holds, a zero delta genuinely means "this choice did not matter," and a nonzero delta is bounded by the branch's own ancestry. Analysts can trust the sign of the effect even when the magnitude is noisy. - **Speculative execution gets more expensive, correctly.** Branch-scoped namespaces cost memory. Recording external effects costs storage. The system pays this to buy soundness, and the cost is bounded by the number of live branches, not the number of steps. The failure this prevents is the quiet one: a replay that runs clean, returns a number, and is wrong because a sibling branch reached into the causal past and rewrote it. ```python from dataclasses import dataclass from enum import Enum from typing import Sequence class ReplaySoundnessError(RuntimeError): """Raised when a counterfactual fork point violates causal isolation.""" class ToolClass(Enum): PURE = "pure" BRANCH_SCOPED = "branch_scoped" SHARED_MUTABLE = "shared_mutable" @dataclass(frozen=True) class TraceStep: index: int tool_class: ToolClass causal_epoch: int # monotonic counter of shared-resource touches at record time def validate_fork_point(steps: Sequence[TraceStep], fork_at: int) -> None: """Enforce: fork_at <= first SHARED_MUTABLE step's causal_epoch boundary. A trace is replayable-for-counterfactuals only if the fork precedes any step whose output could have been shaped by a sibling branch. """ shared = [s for s in steps if s.tool_class is ToolClass.SHARED_MUTABLE] if not shared: return # no shared effects; any fork is sound first_shared = min(shared, key=lambda s: s.index) if fork_at > first_shared.index: raise ReplaySoundnessError( f"fork_at={fork_at} is after first SHARED_MUTABLE step " f"(index={first_shared.index}, epoch={first_shared.causal_epoch}); " f"counterfactual would be contaminated by sibling-branch writes" ) # Additionally: the replayed prefix must be re-derived, not copied, from # the isolated namespace for every step at or after the first shared touch. for s in steps: if s.index >= first_shared.index and s.causal_epoch < first_shared.causal_epoch: raise ReplaySoundnessError( f"step {s.index} has causal_epoch {s.causal_epoch} < " f"first-shared epoch {first_shared.causal_epoch}; " f"trace was recorded without branch-scoped isolation" ) def replay_counterfactual(steps: Sequence[TraceStep], fork_at: int) -> None: validate_fork_point(steps, fork_at) # ... re-execute from fork_at against branch-scoped namespace ... ```