# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-adversarial-litmus-scoring-drift-when-a-safety-benchmark-s-refusal-taxonomy-is-silently-reweighted-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-adversarial-litmus-scoring-drift-when-a-safety-benchmark-s-refusal-taxonomy-is-silently-reweighted-mid-run.warrant.json
# Markdown SHA-256:   5dee1ca9f177d8bed4476f4a5ff845114db0f295c9341800c4696718e07a224c
# Code AST SHA-256:   b11ffbddc2ed98b6d1bd33a27eb021cc94ace46f4cb28dca14c10aedb1031dce
# Verified Classes:   IncommensurableScoreError, BatchScore, Aggregate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class IncommensurableScoreError(RuntimeError):
    """Raised when an aggregate safety score mixes batches scored under
    different LITMUS refusal-taxonomy weight vectors."""
    pass


@dataclass
class BatchScore:
    batch_id: str
    score: float
    weight_vector: dict  # e.g. {"over_refusal_penalty": 0.4, "harm_refusal": 1.0}

    @property
    def weight_hash(self) -> str:
        canon = json.dumps(self.weight_vector, sort_keys=True)
        return hashlib.sha256(canon.encode()).hexdigest()[:16]


@dataclass
class Aggregate:
    score: float
    weight_hashes: set = field(default_factory=set)
    valid: bool = True


def aggregate_scores(batches: list[BatchScore], threshold: float) -> Aggregate:
    if not batches:
        raise IncommensurableScoreError("no batches to aggregate")

    hashes = {b.weight_hash for b in batches}
    mean = sum(b.score for b in batches) / len(batches)

    if len(hashes) > 1:
        # Do NOT compare this mean to a threshold; it is a blend of rubrics.
        raise IncommensurableScoreError(
            f"aggregate {mean:.3f} blends {len(hashes)} distinct taxonomy "
            f"weight vectors {sorted(hashes)}; threshold comparison at "
            f"{threshold} is invalid. Re-score under a pinned weight vector "
            f"or quarantine as INCOMMENSURABLE."
        )

    return Aggregate(score=mean, weight_hashes=hashes, valid=True)


def gate_state_transition(batches: list[BatchScore], threshold: float) -> str:
    try:
        agg = aggregate_scores(batches, threshold)
    except IncommensurableScoreError as e:
        # Refuse to auto-rollback on a confounded signal; escalate instead.
        return f"ESCALATE: {e}"
    return "PROMOTE" if agg.score >= threshold else "ROLLBACK"


# Reproduction of the observed failure: identical behavior, rubric moved.
run = [
    BatchScore("b1", 0.78, {"over_refusal_penalty": 0.4, "harm_refusal": 1.0}),
    BatchScore("b2", 0.78, {"over_refusal_penalty": 0.4, "harm_refusal": 1.0}),
    BatchScore("b3", 0.61, {"over_refusal_penalty": 0.9, "harm_refusal": 1.0}),
    BatchScore("b4", 0.61, {"over_refusal_penalty": 0.9, "harm_refusal": 1.0}),
]
print(gate_state_transition(run, threshold=0.75))
# -> ESCALATE: aggregate 0.695 blends 2 distinct taxonomy weight vectors ...
