# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-cross-contaminates-litmus-safety-benchmark-scores-across-a-shared-evaluation-harness-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-cross-contaminates-litmus-safety-benchmark-scores-across-a-shared-evaluation-harness-cache.warrant.json
# Markdown SHA-256:   7eef2eb7b35ea235382cfd15f397d6694021f87fa3263240d86ebce70bb3d613
# Code AST SHA-256:   27af19cc57c999baa1b4c952dca97c2254bd33edb4a7d301c176a4e3ab7d7b55
# Verified Classes:   StaleVerdictContamination, EvalIdentity
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleVerdictContamination(RuntimeError):
    """Raised when a cached LITMUS verdict is served across a mismatched evaluation identity."""
    pass


@dataclass(frozen=True)
class EvalIdentity:
    judge_model_id: str
    rubric_version: str
    judge_temperature: float
    judge_seed: int
    candidate_system_prompt_hash: str
    candidate_decoding_config: str

    def cache_key(self, prompt_text: str) -> str:
        h = hashlib.sha256()
        h.update(prompt_text.encode("utf-8"))
        for part in (
            self.judge_model_id,
            self.rubric_version,
            f"{self.judge_temperature:.4f}",
            str(self.judge_seed),
            self.candidate_system_prompt_hash,
            self.candidate_decoding_config,
        ):
            h.update(b"\x00")
            h.update(part.encode("utf-8"))
        return h.hexdigest()


def read_verdict(cache, prompt_text, prompt_meta, identity, hit_ceiling=0.10, suite_size=None):
    if prompt_meta.get("boundary_sensitive", False):
        return None  # force recompute; boundary band is uncacheable

    key = identity.cache_key(prompt_text)
    entry = cache.get(key)
    if entry is None:
        return None

    stored = entry["identity"]
    if stored != identity:
        # Defense in depth: even if a key collides, never serve a foreign verdict.
        raise StaleVerdictContamination(
            f"cache entry for prompt {prompt_meta.get('id')} was produced under "
            f"{stored!r} but current run is {identity!r}"
        )

    if suite_size is not None:
        hits = cache.get("__hit_count__", 0) + 1
        cache["__hit_count__"] = hits
        if hits / suite_size > hit_ceiling:
            raise StaleVerdictContamination(
                f"cache hit rate {hits}/{suite_size} exceeds ceiling {hit_ceiling}; "
                f"candidate not independently evaluated"
            )

    return entry["verdict"]
