# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-litmus-benchmark-verdicts-from-silently-inverting-during-ci-red-team-re-registration.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-litmus-benchmark-verdicts-from-silently-inverting-during-ci-red-team-re-registration.warrant.json
# Markdown SHA-256:   607e01f1039198eed1c0ba900dbe3993857a3b293b180e16c835d9fe4c1cc87b
# Code AST SHA-256:   b33347953377c62874f3f97346cfe9f56beb4f4ecc1085768c810fbdf29fd1e0
# Verified Classes:   VerdictTupleMismatch, RegistrationTuple
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class VerdictTupleMismatch(RuntimeError):
    """Raised when a cached verdict's registration tuple does not match the
    current AUT registration. The gate must fail closed, never fall back to
    the most recent row for the probe_id."""


@dataclass(frozen=True)
class RegistrationTuple:
    aut_artifact_digest: str
    probe_payload_hash: str
    judge_config_hash: str
    judge_rng_seed: int

    def key(self) -> str:
        material = "|".join([
            self.aut_artifact_digest,
            self.probe_payload_hash,
            self.judge_config_hash,
            str(self.judge_rng_seed),
        ])
        return hashlib.sha256(material.encode("utf-8")).hexdigest()


def resolve_verdict(
    current: RegistrationTuple,
    verdict_store: dict,
    probe_id: str,
) -> str:
    """Return the verdict for the current registration, or raise if no
    verdict exists under the exact tuple. Never returns a verdict keyed to
    a different tuple, even if a row exists for the same probe_id."""
    key = current.key()
    row: Optional[dict] = verdict_store.get((probe_id, key))
    if row is None:
        stale = verdict_store.get((probe_id, None))  # any tuple for this probe
        if stale is not None:
            raise VerdictTupleMismatch(
                f"probe {probe_id}: cached verdict exists under a different "
                f"registration tuple (cached={stale.get('tuple_key')}, "
                f"current={key}); refusing to reuse. Gate fails closed."
            )
        raise VerdictTupleMismatch(
            f"probe {probe_id}: no verdict for tuple {key}; "
            f"re-run required before gate can pass."
        )
    return row["verdict"]


def gate(
    current: RegistrationTuple,
    verdict_store: dict,
    probe_ids: list,
) -> dict:
    results = {}
    for pid in probe_ids:
        try:
            results[pid] = resolve_verdict(current, verdict_store, pid)
        except VerdictTupleMismatch as e:
            results[pid] = "ERROR"
            # surface the mismatch; do not coerce to PASS
            print(f"[gate] {e}")
    if any(v == "ERROR" for v in results.values()):
        raise VerdictTupleMismatch(
            "gate blocked: at least one probe has no verdict under the "
            "current registration tuple; re-run required."
        )
    if any(v == "FAIL" for v in results.values()):
        raise VerdictTupleMismatch("gate blocked: safety probe failure.")
    return results
