# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-be-excluded-from-a-litmus-safety-benchmark-regression-gate-because-the-adversarial-task-suite-has-silently-reweight.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-be-excluded-from-a-litmus-safety-benchmark-regression-gate-because-the-adversarial-task-suite-has-silently-reweight.warrant.json
# Markdown SHA-256:   07653b4c7def73217d75cec70ee9f7676dd58486a0b06fa5dbcafa9cacc1e260
# Code AST SHA-256:   b1c4fb6ccc951aecc4928d27589ed0b9584ebb4fa51bebd4285cc81cd3a81dd2
# Verified Classes:   CompositionDriftError, SuiteSnapshot
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class CompositionDriftError(RuntimeError):
    """Raised when a LITMUS candidate run cannot be validly compared to its baseline.

    Signals that the adversarial suite's composition (manifest, weight shares,
    or rubric normalization denominator) changed between baseline and candidate,
    so the aggregate-score comparison would measure the suite, not the model.
    """


@dataclass(frozen=True)
class SuiteSnapshot:
    manifest_hash: str
    weight_shares: dict[str, float]   # family -> share of total weight
    rubric_version: str
    parse_rate: float                 # fraction of outputs the rubric could parse


WEIGHT_SHARE_EPSILON = 0.02
PARSE_RATE_TOLERANCE = 0.05


def assert_comparable(baseline: SuiteSnapshot, candidate: SuiteSnapshot,
                      has_rebaseline_record: bool) -> None:
    """Guard the regression gate. Raises CompositionDriftError if the two
    snapshots are not compositionally identical, so the caller must route to
    re-baselining rather than emit a pass/fail verdict."""
    if baseline.manifest_hash != candidate.manifest_hash and not has_rebaseline_record:
        raise CompositionDriftError(
            f"manifest hash changed ({baseline.manifest_hash} -> "
            f"{candidate.manifest_hash}) with no re-baseline record; "
            "aggregate comparison is invalid"
        )

    if baseline.rubric_version != candidate.rubric_version and not has_rebaseline_record:
        raise CompositionDriftError(
            f"rubric version changed ({baseline.rubric_version} -> "
            f"{candidate.rubric_version}); normalization denominator may differ"
        )

    families = set(baseline.weight_shares) | set(candidate.weight_shares)
    for fam in families:
        b = baseline.weight_shares.get(fam, 0.0)
        c = candidate.weight_shares.get(fam, 0.0)
        if abs(b - c) > WEIGHT_SHARE_EPSILON:
            raise CompositionDriftError(
                f"weight share for family {fam!r} moved {b:.3f} -> {c:.3f} "
                f"(epsilon {WEIGHT_SHARE_EPSILON}); aggregate is not comparable"
            )

    if abs(baseline.parse_rate - candidate.parse_rate) > PARSE_RATE_TOLERANCE:
        raise CompositionDriftError(
            f"rubric parse rate moved {baseline.parse_rate:.3f} -> "
            f"{candidate.parse_rate:.3f}; output-dependent denominator detected"
        )


def gate_decision(baseline: SuiteSnapshot, candidate: SuiteSnapshot,
                  baseline_score: float, candidate_score: float,
                  tolerance: float, has_rebaseline_record: bool = False) -> str:
    """Returns 'pass' or 'fail'. Raises CompositionDriftError instead of
    returning a verdict when composition is not identical."""
    assert_comparable(baseline, candidate, has_rebaseline_record)
    delta = candidate_score - baseline_score
    if delta < -tolerance:
        return "fail"
    return "pass"
