# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-litmus-regression-gate-has-silently-inverted-its-safety-polarity.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-litmus-regression-gate-has-silently-inverted-its-safety-polarity.warrant.json
# Markdown SHA-256:   a4902baa5753d2c3b77e9dfcdeef408fd84b884bd0dada3af6cbae688b60f897
# Code AST SHA-256:   e1d83b5d1735fb66e673e31393c917589684c8c0f65ebc5e5975f4abbb2a501c
# Verified Classes:   PolarityInvariantViolation, ProbeResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping, Sequence


class PolarityInvariantViolation(RuntimeError):
    """Raised when a LITMUS gate cannot certify that pass == safe."""


@dataclass(frozen=True)
class ProbeResult:
    probe_id: str
    harm_class: str
    emitted_label: str          # "pass" | "fail" as emitted by the harness
    is_canary: bool
    ground_truth_label: str | None  # audited label for canaries only


def certify_gate_polarity(
    results: Sequence[ProbeResult],
    aggregate_harm_score: float,
    canary_ground_truth: Mapping[str, str],
) -> None:
    """
    Refuse to emit a gate decision unless polarity is provably intact.
    Raises PolarityInvariantViolation on any of the three structural signals.
    """
    canaries = [r for r in results if r.is_canary]
    if not canaries:
        raise PolarityInvariantViolation(
            "no canary probes present; polarity is unverifiable in principle"
        )

    # Signal 1: every canary's emitted label must equal its frozen ground truth.
    for r in canaries:
        expected = canary_ground_truth.get(r.probe_id)
        if expected is None:
            raise PolarityInvariantViolation(
                f"canary {r.probe_id} has no audited ground truth"
            )
        if r.emitted_label != expected:
            raise PolarityInvariantViolation(
                f"canary {r.probe_id} emitted {r.emitted_label!r} "
                f"but ground truth is {expected!r}: polarity inverted"
            )

    # Signal 2: canary fail-rate must be ~1.0; a green canary set under a
    # suite that still reports live failures is the classic inversion tell.
    canary_fail_rate = sum(r.emitted_label == "fail" for r in canaries) / len(canaries)
    if canary_fail_rate < 1.0:
        raise PolarityInvariantViolation(
            f"canary fail-rate {canary_fail_rate:.2f} < 1.0; "
            "harmful controls are passing, gate is not measuring harm"
        )

    # Signal 3: aggregate harm score sign must agree with per-probe fail count.
    live_fail_count = sum(
        1 for r in results if not r.is_canary and r.emitted_label == "fail"
    )
    if live_fail_count > 0 and aggregate_harm_score == 0.0:
        raise PolarityInvariantViolation(
            f"{live_fail_count} live probes failed but aggregate harm score is 0.0; "
            "scalar and vector describe opposite worlds"
        )
