# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-deterministic-replay-of-an-agentic-session-as-unsound-the-nondeterministic-tool-output-divergence-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-deterministic-replay-of-an-agentic-session-as-unsound-the-nondeterministic-tool-output-divergence-boundary.warrant.json
# Markdown SHA-256:   5fc6cc357c4e3d7db45bfe9541785916419805b1d75faf207ebb2351b56c689c
# Code AST SHA-256:   898cb255b704a625daf46e478481d194fc7a7b4e076d765f5901af8868f835bb
# Verified Classes:   ReplayDivergence, CassetteMiss, Step, ReplayResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any


class ReplayDivergence(RuntimeError):
    """Raised when a replayed step does not byte-match the recorded trace."""
    pass


class CassetteMiss(RuntimeError):
    """Raised when a recorded step has no pinned cassette entry."""
    pass


@dataclass
class Step:
    index: int
    tool: str
    args: dict[str, Any]
    output: Any


@dataclass
class ReplayResult:
    causal_horizon: int
    counterfactual_from: int | None
    divergences: list[dict] = field(default_factory=list)


def _hash(obj: Any) -> str:
    return hashlib.sha256(repr(obj).encode()).hexdigest()


def replay_session(
    recorded: list[Step],
    cassette: dict[tuple[str, str, int], Any],
    invoke,
    *,
    strict: bool = True,
) -> ReplayResult:
    """
    Re-execute a session against a frozen cassette.

    strict=True  -> evidence regime: any divergence or cassette miss raises.
    strict=False -> counterfactual regime: truncate causal horizon at first
                    divergence and mark downstream steps counterfactual.
    """
    divergences: list[dict] = []
    first_div: int | None = None

    for step in recorded:
        key = (step.tool, _hash(step.args), step.index)
        if key not in cassette:
            raise CassetteMiss(
                f"step {step.index} tool={step.tool} has no pinned output; "
                f"replay would fall through to live backend"
            )
        pinned = cassette[key]
        replayed = invoke(step.tool, step.args)

        if _hash(pinned) != _hash(replayed):
            divergences.append({
                "step": step.index,
                "tool": step.tool,
                "recorded_hash": _hash(pinned),
                "replayed_hash": _hash(replayed),
            })
            if first_div is None:
                first_div = step.index
            if strict:
                raise ReplayDivergence(
                    f"step {step.index} tool={step.tool} diverged from recorded "
                    f"trace; replay is counterfactual from this point and "
                    f"cannot support causal claims beyond step {step.index - 1}"
                )

    return ReplayResult(
        causal_horizon=(first_div - 1) if first_div is not None else len(recorded) - 1,
        counterfactual_from=first_div,
        divergences=divergences,
    )
