# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-of-a-litmus-safety-harness-reuses-a-cached-adversarial-transcript-across-a-model-swap-and-the-regression-gate-silently-p.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-of-a-litmus-safety-harness-reuses-a-cached-adversarial-transcript-across-a-model-swap-and-the-regression-gate-silently-p.warrant.json
# Markdown SHA-256:   32f20106dcf3793cd0218ae630358e35dd3c3e782abd3b7032db4be68730fcbf
# Code AST SHA-256:   6795036391720e4e628230fda308917dcd8db0c40552f848d8e4870b0e11a63c
# Verified Classes:   StaleBaselineError, ObservableSurface, CachedScenario
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleBaselineError(RuntimeError):
    """Raised when a cached scenario verdict is reused across an incompatible target surface."""
    pass


@dataclass(frozen=True)
class ObservableSurface:
    system_prompt: str
    tool_schema: str
    tokenizer_id: str
    target_model: str

    def fingerprint(self) -> str:
        h = hashlib.sha256()
        for part in (self.system_prompt, self.tool_schema, self.tokenizer_id, self.target_model):
            h.update(part.encode("utf-8"))
            h.update(b"\x00")
        return h.hexdigest()


@dataclass
class CachedScenario:
    scenario_id: str
    surface_fingerprint: str
    expected_label: str
    last_verdict: str


def resolve_verdict(
    scenario: CachedScenario,
    candidate_surface: ObservableSurface,
    require_relabel: set[str],
) -> str:
    """Return a verdict only if the cached baseline is valid for the candidate surface.

    A cache hit whose surface fingerprint differs from the candidate's is NOT a
    valid baseline: the candidate never saw the cached transcript, so its verdict
    cannot be compared to the cached label.
    """
    if scenario.surface_fingerprint != candidate_surface.fingerprint():
        require_relabel.add(scenario.scenario_id)
        raise StaleBaselineError(
            f"scenario {scenario.scenario_id!r} cached under surface "
            f"{scenario.surface_fingerprint[:12]} but candidate runs "
            f"{candidate_surface.fingerprint()[:12]}; verdict is not attributable"
        )
    if scenario.scenario_id in require_relabel:
        raise StaleBaselineError(
            f"scenario {scenario.scenario_id!r} is pending relabel; "
            "must not contribute to gate delta"
        )
    return scenario.last_verdict


def gate_delta(
    scenarios: list[CachedScenario],
    baseline_surface: ObservableSurface,
    candidate_surface: ObservableSurface,
) -> dict:
    require_relabel: set[str] = set()
    executed, excluded = 0, 0
    for s in scenarios:
        try:
            resolve_verdict(s, candidate_surface, require_relabel)
            executed += 1
        except StaleBaselineError:
            excluded += 1
    return {
        "executed": executed,
        "excluded_needs_relabel": excluded,
        "coverage_gap": excluded / max(len(scenarios), 1),
        "delta_trusted": excluded == 0,
    }
