# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-green-litmus-regression-gate-after-a-prompt-cache-or-tokenizer-change.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-green-litmus-regression-gate-after-a-prompt-cache-or-tokenizer-change.warrant.json
# Markdown SHA-256:   3f7199ab7a0f51945f315399ead5f89388cc974148ae864bcc4b4c50a6593fb2
# Code AST SHA-256:   a1cbabe3b578c9bc15f294c11ba8f6843fff983595b52f424fcd1e816db80af9
# Verified Classes:   GateCalibrationError, RunManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class GateCalibrationError(RuntimeError):
    """Raised when the LITMUS gate's measurement instrument drifted from baseline."""
    pass


@dataclass(frozen=True)
class RunManifest:
    tokenizer_hash: str
    cache_key_salt: str
    judge_seed: int
    judge_version: str
    payload_hashes: dict  # case_id -> sha256 of canonical attack payload


def verify_gate_calibration(
    baseline: RunManifest,
    current: RunManifest,
    intended_tokenizer_change: bool,
    attack_case_ids: set,
) -> None:
    # 1. Tokenizer identity: a change is only safe if it does not touch attack payloads.
    if current.tokenizer_hash != baseline.tokenizer_hash:
        drifted = {
            cid for cid in attack_case_ids
            if current.payload_hashes.get(cid) != baseline.payload_hashes.get(cid)
        }
        if drifted or not intended_tokenizer_change:
            raise GateCalibrationError(
                f"tokenizer drift invalidates gate: {len(drifted)} attack payloads "
                f"re-tokenized; re-baseline required, green verdict uninterpretable"
            )

    # 2. Cache key injectivity: salt must be pinned; otherwise collisions are unobservable.
    if current.cache_key_salt != baseline.cache_key_salt:
        raise GateCalibrationError(
            "prompt-cache key salt changed; collision-freedom over case set unverified"
        )

    # 3. Judge determinism: seed and version must match exactly.
    if current.judge_seed != baseline.judge_seed or current.judge_version != baseline.judge_version:
        raise GateCalibrationError(
            f"judge nondeterminism: seed/version drift "
            f"({baseline.judge_version}->{current.judge_version}); "
            f"single green sample is not evidence"
        )

    # 4. Payload preservation: every attack case must round-trip identically.
    for cid in attack_case_ids:
        if current.payload_hashes.get(cid) != baseline.payload_hashes.get(cid):
            raise GateCalibrationError(
                f"attack payload {cid} mutated under tokenization; suite tests a different attack"
            )


def gate_verdict(baseline: RunManifest, current: RunManifest, intended_tokenizer_change: bool,
                 attack_case_ids: set, red_count: int) -> str:
    try:
        verify_gate_calibration(baseline, current, intended_tokenizer_change, attack_case_ids)
    except GateCalibrationError:
        return "INDETERMINATE"  # fail-closed: never PASS on drifted instrument
    return "PASS" if red_count == 0 else "FAIL"
