# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-litmus-safety-benchmark-harness-has-silently-degraded-into-a-no-op-gate-when-its-adversarial-probe-set-is-being-s.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-litmus-safety-benchmark-harness-has-silently-degraded-into-a-no-op-gate-when-its-adversarial-probe-set-is-being-s.warrant.json
# Markdown SHA-256:   6d8114c329be7fca9935127f6da2fd68820d7d151a96c92262b246a39df77a62
# Code AST SHA-256:   66c49216cfbce6cbf398a22703b765047641d1acd91d1694f0d540052d8898c8
# Verified Classes:   GateAccountingError, GateManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class GateAccountingError(RuntimeError):
    """Raised when a LITMUS gate run's accounting is internally inconsistent."""
    pass


@dataclass(frozen=True)
class GateManifest:
    corpus_size: int
    evaluated: int
    foreign_cache_hits: int
    excluded: int          # skipped + errored + truncated
    build_hash: str
    cache_key_build_hash: str


def validate_gate_run(manifest: GateManifest, reported_score: float) -> float:
    """
    Return the gate score only if the run's accounting is sound.
    A score is admissible iff every probe in the frozen corpus was
    evaluated against the current build with no foreign cache reuse
    and no silent denominator shrinkage.
    """
    if manifest.cache_key_build_hash != manifest.build_hash:
        raise GateAccountingError(
            f"cache keyed on build {manifest.cache_key_build_hash!r} but "
            f"candidate is {manifest.build_hash!r}: responses are foreign"
        )

    if manifest.foreign_cache_hits > 0:
        raise GateAccountingError(
            f"{manifest.foreign_cache_hits} cache hits from a non-candidate "
            f"build; score reflects prior model behavior"
        )

    if manifest.excluded > 0:
        raise GateAccountingError(
            f"{manifest.excluded} probes excluded (skipped/truncated/errored); "
            f"denominator shrinkage is not a valid pass"
        )

    if manifest.evaluated != manifest.corpus_size:
        raise GateAccountingError(
            f"evaluated {manifest.evaluated} of {manifest.corpus_size} probes; "
            f"gate did not cover the frozen corpus"
        )

    if not (0.0 <= reported_score <= 1.0):
        raise GateAccountingError(f"score {reported_score} out of range")

    return reported_score


def gate_promotion(manifest: GateManifest, reported_score: float,
                   threshold: float) -> bool:
    score = validate_gate_run(manifest, reported_score)  # raises on corruption
    return score >= threshold
