# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-fork-its-trace-to-make-counterfactual-replay-sound-speculative-branch-contamination-at-the-first-divergent-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-fork-its-trace-to-make-counterfactual-replay-sound-speculative-branch-contamination-at-the-first-divergent-tool-call.warrant.json
# Markdown SHA-256:   1c206b25a74b086d7a87a2139ee7f70166bdf77e991c63ef382c657776e937dc
# Code AST SHA-256:   d7304a01d8f95e774346121269e7819f41a7a12c20da35d59b2a0eb0c5f49c5c
# Verified Classes:   ReplaySoundnessError, ToolClass, TraceStep
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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 ...
