# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-benchmark-conformance-drift-when-a-litmus-safety-harness-silently-reclassifies-tool-use-harm-taxonomy-labels-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-benchmark-conformance-drift-when-a-litmus-safety-harness-silently-reclassifies-tool-use-harm-taxonomy-labels-mid-run.warrant.json
# Markdown SHA-256:   9933109715e93fa93c0c6dbc768972c3d3f825d2b686cb08ce2fd4bb257aa817
# Code AST SHA-256:   f9938ca72bba279f1451773228fafdab469c063fe7f45ab83cd6b5b4bbc43c08
# Verified Classes:   ProvenanceDriftError, Provenance, Verdict, ControlSet
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ProvenanceDriftError(RuntimeError):
    """Raised when a verdict cannot be attributed to a stable labeling function."""


@dataclass(frozen=True)
class Provenance:
    taxonomy_version: str
    rubric_version: str
    judge_prompt_hash: str
    span_extractor_version: str

    def key(self) -> str:
        return "|".join([
            self.taxonomy_version,
            self.rubric_version,
            self.judge_prompt_hash,
            self.span_extractor_version,
        ])


@dataclass
class Verdict:
    trace_hash: str
    label: str
    provenance: Provenance


@dataclass
class ControlSet:
    # trace_hash -> frozen label at the pinned provenance
    frozen: dict = field(default_factory=dict)
    pinned: Provenance = None

    def reproduces(self, observed: list) -> bool:
        by_hash = {v.trace_hash: v for v in observed}
        for trace_hash, expected in self.frozen.items():
            v = by_hash.get(trace_hash)
            if v is None or v.label != expected:
                return False
        return True


def assert_comparable(
    prior: list,
    current: list,
    control: ControlSet,
) -> None:
    """Gate cross-run aggregation on provenance-tuple equality and control reproduction.

    Raises ProvenanceDriftError when the comparison is a taxonomy delta masquerading
    as a behavioral delta, or when the harness is non-conformant.
    """
    prior_keys = {v.provenance.key() for v in prior}
    current_keys = {v.provenance.key() for v in current}

    if None in prior_keys or None in current_keys:
        raise ProvenanceDriftError(
            "verdict missing provenance tuple; classify as unattributed and halt aggregation"
        )

    if prior_keys != current_keys:
        # Different labeling functions: this is a taxonomy delta, not a behavior delta.
        if control.pinned is None or not control.reproduces(current):
            raise ProvenanceDriftError(
                f"labeling function changed {prior_keys} -> {current_keys} "
                f"and pinned control set does not reproduce; "
                f"cross-run aggregate is non-conformant"
            )
        # Control reproduces: safe to report, but only as an explicit taxonomy delta.
        return

    # Same tuple: still verify control reproduction to catch extractor/judge drift
    # that was not versioned.
    if control.pinned is not None and not control.reproduces(current):
        raise ProvenanceDriftError(
            "identical provenance tuple but pinned control traces changed labels; "
            "unversioned drift in extractor or judge"
        )


def attribute_flip(
    trace_hash: str,
    prior: Verdict,
    current: Verdict,
    prior_spans: set,
    current_spans: set,
) -> str:
    """Classify a label flip as rubric-change vs extractor-change vs unattributed."""
    if prior.label == current.label:
        return "no_flip"
    if prior.provenance.key() == current.provenance.key():
        raise ProvenanceDriftError(
            f"trace {trace_hash} flipped label under identical provenance; "
            f"unversioned non-determinism in harness"
        )
    if prior_spans == current_spans:
        return "rubric_or_precedence_change"
    if prior_spans != current_spans:
        return "span_extractor_change"
    raise ProvenanceDriftError(f"cannot attribute flip for trace {trace_hash}")
