# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-cryptographically-signed-action-log-as-non-replayable-despite-hash-chain-integrity-holding.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-cryptographically-signed-action-log-as-non-replayable-despite-hash-chain-integrity-holding.warrant.json
# Markdown SHA-256:   2b862bffb85ebe9cef39790615a0b4f943ad6e7e433eac709af5aaa9e6843ad7
# Code AST SHA-256:   56fc7af47cab291e0dea6c6e89014d846e0a3517208d914f22650e62154fd4a5
# Verified Classes:   ReplayIntegrityError, LogEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ReplayIntegrityError(RuntimeError):
    """Raised when a chain-valid log cannot be faithfully replayed."""
    pass


@dataclass
class LogEntry:
    seq: int
    action: str
    args: dict
    result_hash: str
    prev_hash: str
    committed_body: Optional[bytes]  # None if retention lapsed
    seed: Optional[int]              # None for stochastic entries lacking pin


def verify_chain(entries: list[LogEntry]) -> bool:
    prev = b"\x00" * 32
    for e in entries:
        payload = f"{e.seq}|{e.action}|{sorted(e.args.items())}|{e.result_hash}".encode()
        h = hashlib.sha256(prev + payload).hexdigest()
        if e.prev_hash != prev.hex():
            return False
        prev = bytes.fromhex(h)
    return True


def assert_replayable(entries: list[LogEntry]) -> None:
    if not verify_chain(entries):
        raise ReplayIntegrityError("hash chain broken; integrity failure")
    for e in entries:
        if e.committed_body is None:
            raise ReplayIntegrityError(
                f"seq={e.seq} action={e.action}: committed result_hash has no "
                f"retrievable preimage; replay would require a live read and "
                f"cannot reproduce the original execution"
            )
        recomputed = hashlib.sha256(e.committed_body).hexdigest()
        if recomputed != e.result_hash:
            raise ReplayIntegrityError(
                f"seq={e.seq}: committed body does not match result_hash; "
                f"replay divergence"
            )
        if e.action == "llm.sample" and e.seed is None:
            raise ReplayIntegrityError(
                f"seq={e.seq}: stochastic entry lacks committed seed/model pin; "
                f"trace is integrity-valid but not bit-replayable"
            )
