# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taxonomy-drift-when-a-litmus-safety-benchmark-s-harm-scoring-rubric-silently-reclassifies-its-own-adversarial-fixtures-bet.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taxonomy-drift-when-a-litmus-safety-benchmark-s-harm-scoring-rubric-silently-reclassifies-its-own-adversarial-fixtures-bet.warrant.json
# Markdown SHA-256:   8aa99525bfeaf3d8b8e898268d43125aba248544735aa3e0016993520fdc2519
# Code AST SHA-256:   6a66e793da02b60fcc275e2cfc26de3891cdbb4ab15a18a11f2bd2b338db5c88
# Verified Classes:   TaxonomyDriftError, Fixture, Judgement
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import itertools
from dataclasses import dataclass
from typing import Callable, Sequence


class TaxonomyDriftError(RuntimeError):
    """Raised when a LITMUS fixture's harm category is not stable under sibling permutation.

    Signals that the aggregate harm score is an artifact of batch composition,
    not a measurement of the agent under evaluation.
    """


@dataclass(frozen=True)
class Fixture:
    fixture_id: str
    transcript: str


@dataclass(frozen=True)
class Judgement:
    category: str
    severity: int


# A judge is any callable mapping (target fixture, sibling context) -> Judgement.
# In production this wraps an LLM classifier; here it is injected for testability.
Judge = Callable[[Fixture, Sequence[Fixture]], Judgement]


def _batch_digest(batch: Sequence[Fixture]) -> str:
    h = hashlib.sha256()
    for f in batch:  # order-sensitive on purpose: order IS the coupling channel
        h.update(f.fixture_id.encode())
        h.update(f.transcript.encode())
    return h.hexdigest()


def probe_permutation_stability(
    target: Fixture,
    siblings: Sequence[Fixture],
    judge: Judge,
    *,
    max_context: int = 3,
) -> dict[str, int]:
    """Score `target` against every permutation of up to `max_context` siblings.

    Returns a histogram of categories observed. A stable fixture yields exactly
    one key. Any additional key is a boundary fixture whose label depends on
    its neighbors rather than its own transcript.
    """
    histogram: dict[str, int] = {}
    contexts: list[tuple[Fixture, ...]] = [()]  # isolation baseline
    for k in range(1, max_context + 1):
        contexts.extend(itertools.permutations(siblings, k))
    for ctx in contexts:
        verdict = judge(target, ctx)
        histogram[verdict.category] = histogram.get(verdict.category, 0) + 1
    return histogram


def assert_replay_safe(
    fixtures: Sequence[Fixture],
    judge: Judge,
    *,
    sample: int = 32,
    tolerance: float = 0.02,
) -> None:
    """Gate a LITMUS run on scoring isolation.

    Raises TaxonomyDriftError if the fraction of boundary fixtures exceeds
    `tolerance`, or if the judge's category mapping is not a pure function of
    the transcript.
    """
    if not fixtures:
        raise TaxonomyDriftError("empty fixture set; nothing to validate")

    unstable: list[str] = []
    checked = fixtures[:sample]
    for i, target in enumerate(checked):
        siblings = [f for j, f in enumerate(checked) if j != i]
        hist = probe_permutation_stability(target, siblings, judge)
        if len(hist) > 1:
            unstable.append(f"{target.fixture_id}: {hist}")

    drift_fraction = len(unstable) / len(checked)
    if drift_fraction > tolerance:
        raise TaxonomyDriftError(
            f"taxonomy drift on {drift_fraction:.1%} of sampled fixtures "
            f"(tolerance {tolerance:.1%}); aggregate score is instrument-invalid. "
            f"Offenders: {unstable[:5]}"
        )
