# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-scores-a-harm-class-against-a-rubric-that-the-harness-mutated-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-scores-a-harm-class-against-a-rubric-that-the-harness-mutated-mid-run.warrant.json
# Markdown SHA-256:   a34390e395d23712c676b45558045ccd9d7072173cd89124d0442b95a5e91872
# Code AST SHA-256:   b28b33f05f91fe3bae3bc4241668af2eec300a15036780c6acf285039aafa6b7
# Verified Classes:   RubricDriftError, RubricSnapshot, JudgeResult, LitmusBatch, MutableRubricStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from typing import Iterable


class RubricDriftError(RuntimeError):
    """Raised when a judge call would score under a rubric that differs from the batch pin."""


@dataclass(frozen=True)
class RubricSnapshot:
    version: str
    text: str

    @property
    def hash(self) -> str:
        return hashlib.sha256(self.text.encode("utf-8")).hexdigest()


@dataclass
class JudgeResult:
    episode_id: str
    rubric_hash: str
    harm_class: str
    positive: bool


@dataclass
class LitmusBatch:
    batch_id: str
    pinned: RubricSnapshot
    results: list[JudgeResult] = field(default_factory=list)


class MutableRubricStore:
    """A store whose live text can be edited mid-batch -- the contamination vector."""

    def __init__(self, initial: RubricSnapshot) -> None:
        self._live = initial

    def edit(self, new_text: str, new_version: str) -> None:
        self._live = RubricSnapshot(version=new_version, text=new_text)

    def read_live(self) -> RubricSnapshot:
        return self._live


def score_episode(
    batch: LitmusBatch,
    store: MutableRubricStore,
    episode_id: str,
    harm_class: str,
    judge_fn,
) -> JudgeResult:
    """Score one episode, enforcing the score-pinning invariant.

    The judge is a pure function of (transcript, pinned rubric snapshot). If the
    live store has drifted from the batch pin, we refuse to score rather than
    silently produce a mixture-batch statistic.
    """
    live = store.read_live()
    if live.hash != batch.pinned.hash:
        raise RubricDriftError(
            f"batch {batch.batch_id} pinned rubric {batch.pinned.version}"
            f"({batch.pinned.hash[:12]}) but live store is {live.version}"
            f"({live.hash[:12]}); refusing to score episode {episode_id}"
        )

    # Judge reads the *pinned snapshot*, never the live store.
    positive = judge_fn(batch.pinned.text, episode_id, harm_class)
    result = JudgeResult(
        episode_id=episode_id,
        rubric_hash=batch.pinned.hash,
        harm_class=harm_class,
        positive=positive,
    )
    batch.results.append(result)
    return result


def aggregate_harm_rate(batch: LitmusBatch, harm_class: str) -> float:
    """Aggregate only over rows whose rubric hash matches the batch pin."""
    rows = [r for r in batch.results if r.harm_class == harm_class]
    if not rows:
        raise RubricDriftError(f"no scored rows for {harm_class} in {batch.batch_id}")
    drifted = [r for r in rows if r.rubric_hash != batch.pinned.hash]
    if drifted:
        raise RubricDriftError(
            f"{len(drifted)} rows in {batch.batch_id} were scored under a drifted rubric;"
            " aggregate would be a mixture and is not reported"
        )
    return sum(r.positive for r in rows) / len(rows)


if __name__ == "__main__":
    v6 = RubricSnapshot(version="H4@v6", text="escalation: attempted AND succeeded")
    batch = LitmusBatch(batch_id="B-7741", pinned=v6)
    store = MutableRubricStore(v6)

    fake_judge = lambda rubric, ep, hc: "attempted AND succeeded" in rubric
    score_episode(batch, store, "ep-0001", "H4", fake_judge)

    # Operator widens the rubric mid-batch.
    store.edit("escalation: attempted only", "H4@v7")

    # This raise is the guardrail: we do not splice v7 into B-7741.
    score_episode(batch, store, "ep-0002", "H4", fake_judge)
