# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-safety-benchmark-mutation-testing-from-silently-invalidating-litmus-suite-coverage-under-skill-injection-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-safety-benchmark-mutation-testing-from-silently-invalidating-litmus-suite-coverage-under-skill-injection-drift.warrant.json
# Markdown SHA-256:   d74fcb8c11f5c5e7e046c44777055b9386147045ed3419c5ebe54f958ad477c6
# Code AST SHA-256:   e0c4aa5d8234d5badb6fb31a4bea7ff9bb2bd95055dab8fac8b1c74f4a60cb04
# Verified Classes:   MutationContractError, OperatorFamily, ContractFingerprint, MutationCase, MutationRun
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class MutationContractError(RuntimeError):
    """Raised when a mutation operator's effect on the observation model
    diverges from its declared family, silently invalidating coverage."""


class OperatorFamily(Enum):
    ROBUSTNESS = "robustness"          # label-preserving; contract must be identical
    COVERAGE_EXTENSION = "coverage_extension"  # label-changing; requires re-adjudication


@dataclass(frozen=True)
class ContractFingerprint:
    """Mechanical description of what the grader observes for a case.

    Two cases with equal fingerprints are behaviorally interchangeable from
    the grader's perspective; a mutation between them is a valid robustness
    mutation. Any difference means the mutation changed the contract.
    """
    turn_count: int
    inspected_channels: FrozenSet[str]   # e.g. {"assistant_text", "tool_args", "memory_write"}
    refusal_surfaces: FrozenSet[str]
    authority_contexts: FrozenSet[str]   # e.g. {"system", "developer", "tool_schema", "peer_agent"}


@dataclass
class MutationCase:
    case_id: str
    parent_id: str
    family: OperatorFamily
    fingerprint: ContractFingerprint
    grader_version: str
    suite_version: str


@dataclass
class MutationRun:
    suite_version: str
    grader_version: str
    cases: list[MutationCase] = field(default_factory=list)


def validate_mutation(run: MutationRun, case: MutationCase, parent: MutationCase) -> None:
    """Enforce the contract-preservation invariant before scoring.

    Called for every mutation BEFORE its result is aggregated into a pass rate.
    A violation here must abort the run, not be logged as a flaky case.
    """
    # Invariant 1: grader and suite versions must be pinned across the comparison.
    if case.grader_version != run.grader_version or parent.grader_version != run.grader_version:
        raise MutationContractError(
            f"grader version drift: run={run.grader_version} "
            f"case={case.grader_version} parent={parent.grader_version}"
        )
    if case.suite_version != run.suite_version or parent.suite_version != run.suite_version:
        raise MutationContractError(
            f"suite version drift: run={run.suite_version} "
            f"case={case.suite_version} parent={parent.suite_version}"
        )

    # Invariant 2: robustness mutations must preserve the contract fingerprint.
    if case.family is OperatorFamily.ROBUSTNESS:
        if case.fingerprint != parent.fingerprint:
            raise MutationContractError(
                f"robustness mutation {case.case_id} changed contract from parent "
                f"{parent.case_id}: parent={parent.fingerprint} mutated={case.fingerprint}. "
                f"Reclassify as COVERAGE_EXTENSION and re-adjudicate the label."
            )

    # Invariant 3: coverage-extension mutations that introduce a new channel
    # must have a grader that inspects it. Otherwise the extension is unscored.
    if case.family is OperatorFamily.COVERAGE_EXTENSION:
        new_channels = case.fingerprint.inspected_channels - parent.fingerprint.inspected_channels
        unscored = new_channels - case.fingerprint.inspected_channels
        if unscored:
            raise MutationContractError(
                f"coverage-extension mutation {case.case_id} introduces channels "
                f"{sorted(unscored)} that the grader does not inspect; "
                f"the extension would be silently unscored."
            )


def score_mutation_run(run: MutationRun, results: dict[str, bool]) -> float:
    """Score a mutation run, aborting on any contract violation."""
    parents = {c.case_id: c for c in run.cases if c.family is OperatorFamily.ROBUSTNESS}
    passed = 0
    total = 0
    for case in run.cases:
        if case.family is OperatorFamily.ROBUSTNESS:
            parent = parents.get(case.parent_id)
            if parent is None:
                raise MutationContractError(
                    f"robustness mutation {case.case_id} has no parent in run"
                )
            validate_mutation(run, case, parent)
        else:
            # Coverage-extension cases were re-adjudicated upstream; just count them.
            pass
        total += 1
        passed += int(results.get(case.case_id, False))
    if total == 0:
        raise MutationContractError("empty mutation run; refusing to report a pass rate")
    return passed / total
