# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-replay-divergence-when-a-forensic-audit-re-executes-a-trajectory-under-a-different-sampling-seed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-replay-divergence-when-a-forensic-audit-re-executes-a-trajectory-under-a-different-sampling-seed.warrant.json
# Markdown SHA-256:   087acdba3c734bf2360e41dcdc3dcf810a1a7b618d25bab86c88e6885ed6e73a
# Code AST SHA-256:   2eb66c1dfc03702b640567128c7f8babbc97b7edde9b87fe972ebb2c6192c076
# Verified Classes:   ReplayContractError, Verdict, NumericsFingerprint, StepRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class ReplayContractError(RuntimeError):
    """Raised when a forensic replay is attempted under an unmeetable contract."""


class Verdict(str, Enum):
    REPLAY_UNINFORMATIVE = "REPLAY_UNINFORMATIVE"
    SAMPLING_VARIANCE = "SAMPLING_VARIANCE"
    REPLAY_DEFECT = "REPLAY_DEFECT"


@dataclass(frozen=True)
class NumericsFingerprint:
    weights_hash: str
    tokenizer_hash: str
    decoding_config_hash: str
    batch_size: int
    hardware_class: str

    def reproduces(self, other: "NumericsFingerprint") -> bool:
        return (
            self.weights_hash == other.weights_hash
            and self.tokenizer_hash == other.tokenizer_hash
            and self.decoding_config_hash == other.decoding_config_hash
            and self.batch_size == other.batch_size
            and self.hardware_class == other.hardware_class
        )


@dataclass(frozen=True)
class StepRecord:
    step_index: int
    recorded_action: str
    replayed_action: str
    admissible_actions: frozenset[str]  # reconstructed from RECORDED state


def adjudicate_replay(
    recorded: NumericsFingerprint,
    audit: NumericsFingerprint,
    control_flow_matches: bool,
    steps: list[StepRecord],
) -> tuple[Verdict, int | None]:
    if not control_flow_matches:
        # Tier 1 failure is deterministic and always informative.
        first = next(
            (s.step_index for s in steps if s.recorded_action != s.replayed_action),
            None,
        )
        return Verdict.REPLAY_DEFECT, first

    if not recorded.reproduces(audit):
        # Tier 2 is not trustworthy; do not diff outputs.
        return Verdict.REPLAY_UNINFORMATIVE, None

    for s in steps:
        if s.recorded_action == s.replayed_action:
            continue
        # Load-bearing check: test replayed action against RECORDED admissible set.
        if s.replayed_action in s.admissible_actions:
            return Verdict.SAMPLING_VARIANCE, s.step_index
        return Verdict.REPLAY_DEFECT, s.step_index

    return Verdict.SAMPLING_VARIANCE, None


def run_forensic_audit(
    recorded: NumericsFingerprint,
    audit: NumericsFingerprint,
    control_flow_matches: bool,
    steps: list[StepRecord],
    require_informative: bool = True,
) -> Verdict:
    verdict, first_step = adjudicate_replay(
        recorded, audit, control_flow_matches, steps
    )
    if require_informative and verdict is Verdict.REPLAY_UNINFORMATIVE:
        raise ReplayContractError(
            f"Replay is uninformative: numerics precondition unmet "
            f"(recorded={recorded}, audit={audit}). "
            f"Quarantine the trajectory; do not escalate a diff-based finding."
        )
    return verdict
