# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-non-deterministic-tool-outputs-are-re-sampled-during-trace-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-non-deterministic-tool-outputs-are-re-sampled-during-trace-reconstruction.warrant.json
# Markdown SHA-256:   f2fd123a0f2ce943d507a5b7e5b9ed15f6b0e6b0a12f260effe801b237a6fad9
# Code AST SHA-256:   2bac3601de393a4e86928da62650db9d5c83278b878e4d78fb100798102b38d9
# Verified Classes:   ReplayDivergenceError, Step
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ReplayDivergenceError(RuntimeError):
    """Raised when a re-derivation replay cannot prove prefix equality
    before a step whose output is being compared for divergence."""


@dataclass(frozen=True)
class Step:
    index: int
    tool: str
    args_hash: str
    output: str
    provenance: str  # "deterministic" | "non-deterministic"


def _h(s: str) -> str:
    return hashlib.sha256(s.encode()).hexdigest()


def reconstruct(
    recorded: list[Step],
    replayed: list[Step],
    allow_counterfactual: bool = False,
) -> Optional[int]:
    """Return the index of the first *meaningful* divergence, or None if the
    traces are identical through the recorded length.

    Enforces the prefix-equality invariant: a divergence at step t is only
    attributable to the model if steps 0..t-1 are byte-identical. If a
    non-deterministic step re-samples, we must either pin it (strict) or
    explicitly opt into counterfactual mode and name the fork step.
    """
    if len(recorded) != len(replayed):
        raise ReplayDivergenceError(
            f"trace length mismatch: recorded={len(recorded)} replayed={len(replayed)}"
        )

    for rec, rep in zip(recorded, replayed):
        if rec.index != rep.index or rec.tool != rep.tool or rec.args_hash != rep.args_hash:
            raise ReplayDivergenceError(
                f"step {rec.index}: input drift (tool/args changed) — not a valid replay"
            )

        if _h(rec.output) == _h(rep.output):
            continue  # prefix holds; keep going

        # Outputs differ at this step. If the step is non-deterministic, the
        # difference is a re-sampling fork, not model instability.
        if rec.provenance == "non-deterministic":
            if allow_counterfactual:
                return rec.index  # fork point; caller must tag as COUNTERFACTUAL
            raise ReplayDivergenceError(
                f"step {rec.index}: non-deterministic tool '{rec.tool}' re-sampled "
                f"during strict replay; pin this output or enable counterfactual mode"
            )

        # Deterministic step diverged with identical inputs -> genuine instability.
        return rec.index

    return None
