# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-nondeterministic-divergence-during-replay-of-its-own-prior-session-and-why-does-the-replay-of-a-tool-call-transcript-silen.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-nondeterministic-divergence-during-replay-of-its-own-prior-session-and-why-does-the-replay-of-a-tool-call-transcript-silen.warrant.json
# Markdown SHA-256:   5710c6a87f25bda4baeec76b17d6ffb6d5da2a9418254c43629720ee6a47fb3e
# Code AST SHA-256:   b33e3748239f63909760143ba13a9b2636d4ee39de86db6793817d4e45cf6ea5
# Verified Classes:   ReplayVerdictError, RecordedStep, ReplaySample
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Sequence


class ReplayVerdictError(RuntimeError):
    """Raised when a replay harness attempts to certify a session whose
    sampling channel was never validated, or whose recorded action falls
    outside the containment bound under a faithful prefix."""


@dataclass(frozen=True)
class RecordedStep:
    step_index: int
    seed: int
    prefix_hash: str
    action: str
    recorded_logprob: float
    tool_output: str


@dataclass(frozen=True)
class ReplaySample:
    action: str
    logprob: float


CONTAINMENT_TAU = 0.05
CONTAINMENT_K = 5
MIN_SAMPLES = 20


def _prefix_hash(prefix: str) -> str:
    return hashlib.sha256(prefix.encode("utf-8")).hexdigest()


def validate_sampling_containment(
    recorded: RecordedStep,
    replay_prefix: str,
    samples: Sequence[ReplaySample],
) -> str:
    if len(samples) < MIN_SAMPLES:
        raise ReplayVerdictError(
            f"step {recorded.step_index}: only {len(samples)} replay samples; "
            f"need >= {MIN_SAMPLES} to estimate containment"
        )

    if _prefix_hash(replay_prefix) != recorded.prefix_hash:
        raise ReplayVerdictError(
            f"step {recorded.step_index}: replay prefix hash "
            f"{_prefix_hash(replay_prefix)[:12]} != recorded "
            f"{recorded.prefix_hash[:12]}; distribution is conditioned on a "
            f"different world and the verdict is uninterpretable"
        )

    ranked = sorted(samples, key=lambda s: s.logprob, reverse=True)
    rank = next(
        (i for i, s in enumerate(ranked) if s.action == recorded.action),
        len(ranked),
    )
    empirical_p = sum(1 for s in samples if s.action == recorded.action) / len(samples)

    if empirical_p < CONTAINMENT_TAU and rank >= CONTAINMENT_K:
        return "INCONCLUSIVE_SAMPLING"
    if rank == 0:
        return "REPRODUCED_DETERMINISTIC"
    return "REPRODUCED_STOCHASTIC"


def certify_session(
    steps: Sequence[RecordedStep],
    replay_prefixes: Sequence[str],
    replay_samples: Sequence[Sequence[ReplaySample]],
) -> str:
    verdicts = [
        validate_sampling_containment(step, prefix, samples)
        for step, prefix, samples in zip(steps, replay_prefixes, replay_samples)
    ]

    if "INCONCLUSIVE_SAMPLING" in verdicts:
        decisive = verdicts.index("INCONCLUSIVE_SAMPLING")
        raise ReplayVerdictError(
            f"session cannot be certified REPRODUCED: decisive step {decisive} "
            f"is a low-probability excursion under a faithful prefix. "
            f"Root-cause attribution to external steering is not licensed."
        )

    if all(v == "REPRODUCED_DETERMINISTIC" for v in verdicts):
        return "REPRODUCED_DETERMINISTIC"
    return "REPRODUCED_STOCHASTIC"
