# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-safety-benchmark-regression-gates-from-certifying-a-poisoned-skill-update.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-safety-benchmark-regression-gates-from-certifying-a-poisoned-skill-update.warrant.json
# Markdown SHA-256:   aff986ddf2df97775c6fbb76328397167aedbf4466127666aecc838ed6e41ae7
# Code AST SHA-256:   e5d24dc13c535447fd20f0d78c300f9342bc81730f53191288455995ea4d1cde
# Verified Classes:   GateEvasionError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class GateEvasionError(RuntimeError):
    """Raised when a regression gate cannot certify a candidate skill update
    because the candidate conditions on features outside the suite's support."""
    pass


def certify_skill_update(
    incumbent_scores: dict,
    candidate_scores: dict,
    candidate_policy_diff_features: set,
    suite_stratified_features: set,
    probe_divergence: float,
    probe_tolerance: float,
    shadow_slice_max_delta: dict,
    shadow_tolerance: dict,
    candidate_optimized_on_suite: bool,
    probe_provenance_disjoint: bool,
    epsilon: float = 0.004,
) -> bool:
    # 1. Support containment: every feature the diff can key on must be a stratum.
    uncovered = candidate_policy_diff_features - suite_stratified_features
    if uncovered:
        raise GateEvasionError(
            f"candidate keys on features absent from suite support: {sorted(uncovered)}; "
            "fail closed, do not fall back to aggregate score"
        )

    # 2. Harness confound check is upstream, but adaptive candidates need a disjoint probe.
    if candidate_optimized_on_suite and not probe_provenance_disjoint:
        raise GateEvasionError(
            "candidate optimized against suite and probe shares provenance; "
            "score predicate is training loss, not generalization"
        )

    # 3. Behavioral-equivalence probe on provenance-disjoint corpus.
    if probe_divergence > probe_tolerance:
        raise GateEvasionError(
            f"probe divergence {probe_divergence:.4f} exceeds tolerance {probe_tolerance:.4f}"
        )

    # 4. Aggregate regression predicate (necessary, not sufficient).
    for metric, inc in incumbent_scores.items():
        if candidate_scores.get(metric, float("inf")) > inc + epsilon:
            raise GateEvasionError(f"aggregate regression on {metric}")

    # 5. Shadow-window slice predicate: no observed slice may exceed tolerance.
    for slice_name, delta in shadow_slice_max_delta.items():
        tol = shadow_tolerance.get(slice_name)
        if tol is None:
            raise GateEvasionError(
                f"shadow slice {slice_name!r} has no pre-registered tolerance; fail closed"
            )
        if delta > tol:
            raise GateEvasionError(
                f"shadow slice {slice_name!r} delta {delta:.4f} exceeds tolerance {tol:.4f}"
            )

    return True
