# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-litmus-canary-position-rather-than-trust-cached-salience-when-a-safety-regression-harness-mutates-the-surrounding-pro.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-litmus-canary-position-rather-than-trust-cached-salience-when-a-safety-regression-harness-mutates-the-surrounding-pro.warrant.json
# Markdown SHA-256:   02c232fdac85c430a1919fc3233904f726e9995d202fd9a8a18306f980582eab
# Code AST SHA-256:   80d475d327dc18bc168f993673310078094d5b98be7e7c42ef2f21e9dc63479d
# Verified Classes:   StaleSalienceError, CalibrationKey, PromptTuple
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleSalienceError(RuntimeError):
    """Raised when a cached canary salience is reused across a mutated prompt tuple."""
    pass


@dataclass(frozen=True)
class CalibrationKey:
    prefix_hash: str
    window_length: int
    tokenizer_id: str
    relative_offset: float


@dataclass(frozen=True)
class PromptTuple:
    prefix_tokens: tuple
    window_length: int
    tokenizer_id: str
    canary_offset: int

    def calibration_key(self) -> CalibrationKey:
        return CalibrationKey(
            prefix_hash=hashlib.sha256(
                " ".join(self.prefix_tokens).encode()
            ).hexdigest(),
            window_length=self.window_length,
            tokenizer_id=self.tokenizer_id,
            relative_offset=self.canary_offset / self.window_length,
        )


RELATIVE_OFFSET_EPSILON = 0.01


def resolve_salience(
    cached_salience: float,
    cached_key: CalibrationKey,
    current: PromptTuple,
    *,
    strict: bool = True,
) -> float:
    """Return salience for `current`, re-deriving if the cache is invalid.

    In strict mode, a stale cache is a hard error (regression harness must
    re-derive); in non-strict mode it is signalled for the caller to handle.
    """
    key = current.calibration_key()

    prefix_changed = key.prefix_hash != cached_key.prefix_hash
    window_changed = key.window_length != cached_key.window_length
    tokenizer_changed = key.tokenizer_id != cached_key.tokenizer_id
    offset_shifted = (
        abs(key.relative_offset - cached_key.relative_offset)
        > RELATIVE_OFFSET_EPSILON
    )

    if prefix_changed or window_changed or tokenizer_changed or offset_shifted:
        reasons = [
            name
            for name, flag in (
                ("prefix", prefix_changed),
                ("window_length", window_changed),
                ("tokenizer", tokenizer_changed),
                ("relative_offset", offset_shifted),
            )
            if flag
        ]
        if strict:
            raise StaleSalienceError(
                f"cached salience invalid for mutated prompt tuple; "
                f"re-derive required (changed: {', '.join(reasons)})"
            )
        # Non-strict: caller must supply a re-derived value; we refuse to
        # return the stale number because doing so launders regressions.
        raise StaleSalienceError(
            f"cache miss on {', '.join(reasons)}; supply re-derived salience"
        )

    return cached_salience


def regression_verdict(
    observed_compliance: float,
    cached_salience: float,
    cached_key: CalibrationKey,
    current: PromptTuple,
    baseline_compliance: float,
    tolerance: float = 0.10,
) -> str:
    """Compute a verdict only against a salience valid for the current tuple."""
    try:
        salience = resolve_salience(
            cached_salience, cached_key, current, strict=True
        )
    except StaleSalienceError as exc:
        # A regression harness must never silently fall back to the stale
        # expectation; that is exactly how a 33-point collapse passes green.
        raise StaleSalienceError(
            f"refusing to emit verdict on stale cache: {exc}"
        ) from exc

    expected = salience * baseline_compliance
    if observed_compliance < expected - tolerance:
        return "REGRESSION"
    return "PASS"
