# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-reconcile-a-litmus-safety-benchmark-verdict-it-did-not-itself-produce-the-cross-run-verdict-stitching-boundary-in-con.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-reconcile-a-litmus-safety-benchmark-verdict-it-did-not-itself-produce-the-cross-run-verdict-stitching-boundary-in-con.warrant.json
# Markdown SHA-256:   83202025d73fb7e308cb97cd467de686805de18bf34b8df1f922ecbdd3fbebbb
# Code AST SHA-256:   97134e51f98fc96f86093fa2c3a42676dcb175f8f182eb141797e394bae59b98
# Verified Classes:   VerdictTupleMismatch, VerdictTuple, LitmusVerdict, SafetyProfile
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class VerdictTupleMismatch(RuntimeError):
    """Raised when a LITMUS verdict is aggregated into a profile whose
    (target_version, probe_set_version, judge_model_version) tuple differs.
    Carrying such a verdict forward would produce an unfalsifiable profile."""
    pass


@dataclass(frozen=True)
class VerdictTuple:
    target_version: str
    probe_set_version: str
    judge_model_version: str


@dataclass(frozen=True)
class LitmusVerdict:
    tuple_id: VerdictTuple
    fails: FrozenSet[str]
    run_id: str


@dataclass
class SafetyProfile:
    tuple_id: VerdictTuple
    fails: set = field(default_factory=set)
    quarantined: list = field(default_factory=list)

    def ingest(self, verdict: LitmusVerdict) -> None:
        if verdict.tuple_id != self.tuple_id:
            # Boundary: non-comparable verdict. Quarantine, do not union.
            self.quarantined.append(verdict)
            raise VerdictTupleMismatch(
                f"verdict {verdict.run_id} tuple {verdict.tuple_id} "
                f"!= profile tuple {self.tuple_id}; quarantined, not unioned"
            )
        self.fails |= verdict.fails

    def pass_rate(self, n_probes: int) -> float:
        if n_probes <= 0:
            raise VerdictTupleMismatch(f"invalid probe count {n_probes}")
        return 1.0 - len(self.fails) / n_probes


def build_profile(verdicts: list, n_probes: int) -> SafetyProfile:
    if not verdicts:
        raise VerdictTupleMismatch("cannot build profile from empty verdict list")
    profile = SafetyProfile(tuple_id=verdicts[0].tuple_id)
    for v in verdicts:
        if v.tuple_id != profile.tuple_id:
            # Explicitly quarantine and signal; caller decides whether to
            # reset the profile or split it per tuple.
            profile.quarantined.append(v)
            raise VerdictTupleMismatch(
                f"mixed-tuple aggregation refused: {v.run_id} "
                f"({v.tuple_id}) vs profile ({profile.tuple_id})"
            )
        profile.fails |= v.fails
    return profile
