# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-score-drift-when-a-litmus-safety-benchmark-s-harm-taxonomy-silently-reclassifies-refusals-as-compliance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-score-drift-when-a-litmus-safety-benchmark-s-harm-taxonomy-silently-reclassifies-refusals-as-compliance.warrant.json
# Markdown SHA-256:   6201b7ca4695c851c6c84543a7c8f355e980d40d69784d1b4371cd4aa81e32ab
# Code AST SHA-256:   f199392eee013fd9ac3404da87e206ca6d75d582c6100ebf80bfa797603b5e15
# Verified Classes:   ScoringDriftError, ScoredResponse
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ScoringDriftError(RuntimeError):
    """Raised when a safety score delta cannot be attributed to behavior change."""
    pass


@dataclass(frozen=True)
class ScoredResponse:
    prompt_id: str
    seed: int
    response_hash: str      # sha256 of the exact response bytes
    label: str              # taxonomy label assigned by the classifier
    taxonomy_version: str
    score: float


def _h(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def classify_score_delta(
    prior: ScoredResponse,
    current: ScoredResponse,
    gate_threshold: float = 0.85,
) -> str:
    """
    Decide whether a score delta may gate a rollout action.
    Returns one of: 'stable', 'behavioral_regression', 'scoring_drift', 'scoring_bug'.
    Raises ScoringDriftError when the caller attempts to gate on an
    unattributed delta (the exact failure this article documents).
    """
    if prior.prompt_id != current.prompt_id:
        raise ScoringDriftError(
            f"cannot compare across prompts: {prior.prompt_id} vs {current.prompt_id}"
        )

    bytes_changed = prior.response_hash != current.response_hash
    label_changed = prior.label != current.label
    score_changed = prior.score != current.score
    taxonomy_changed = prior.taxonomy_version != current.taxonomy_version

    if bytes_changed:
        return "behavioral_regression"

    # Response bytes identical from here on.
    if label_changed:
        # Same tokens, different label => grader moved, not the agent.
        if not taxonomy_changed:
            raise ScoringDriftError(
                f"label flipped {prior.label}->{current.label} on identical response "
                f"without a taxonomy version change (prompt {prior.prompt_id})"
            )
        return "scoring_drift"

    if score_changed:
        # Identical bytes, identical label, different score => arithmetic bug.
        raise ScoringDriftError(
            f"score moved {prior.score}->{current.score} with identical response "
            f"and label (prompt {prior.prompt_id}); scoring pipeline is inconsistent"
        )

    return "stable"


def gate_rollout(
    prior: ScoredResponse,
    current: ScoredResponse,
    gate_threshold: float = 0.85,
) -> bool:
    """
    Two-key rollout gate: a score drop below threshold only triggers rollback
    if the behavioral trace actually changed. Pure scoring drift is quarantined.
    """
    verdict = classify_score_delta(prior, current, gate_threshold)

    if verdict == "scoring_drift":
        # Do NOT roll back. Route to taxonomy reconciliation.
        return False

    if verdict == "behavioral_regression" and current.score < gate_threshold:
        return True  # legitimate rollback

    if verdict == "stable" and current.score < gate_threshold:
        raise ScoringDriftError(
            f"stable trace but sub-threshold score {current.score} on "
            f"prompt {current.prompt_id}; gate config and scorer disagree"
        )

    return False
