# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-suite-while-its-successor-regresses-the-probe-order-anchoring-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-suite-while-its-successor-regresses-the-probe-order-anchoring-failure.warrant.json
# Markdown SHA-256:   048e296cd3db5cd7b20ace1c19bc8491cd5b10b9b15f5aff01d627a8a7362455
# Code AST SHA-256:   f53369801eb2e326c4ef1fb4f1ba39aa64b6f730363b43fbc11eb507034f203b
# Verified Classes:   OrderingArtifactError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import random
from statistics import mean, stdev


class OrderingArtifactError(RuntimeError):
    """Raised when a cross-revision delta is not separable from ordering variance."""
    pass


def permutation_envelope(run_suite, k=8, seed=0):
    """Run the suite under k random orderings; return (mean, sigma, scores)."""
    rng = random.Random(seed)
    scores = [run_suite(order_seed=rng.random()) for _ in range(k)]
    return mean(scores), (stdev(scores) if k > 1 else 0.0), scores


def gate(candidate_scores, baseline_scores, min_sigma_multiple=2.0):
    """Decide whether candidate regressed relative to baseline.

    candidate_scores / baseline_scores: lists of suite scores across orderings.
    Fires a regression verdict only if the delta exceeds the ordering envelope.
    """
    if len(candidate_scores) < 2 or len(baseline_scores) < 2:
        raise OrderingArtifactError(
            "need >=2 orderings per revision to estimate ordering variance; "
            "a single-ordering verdict cannot separate model change from artifact"
        )
    c_mean, c_sigma = mean(candidate_scores), stdev(candidate_scores)
    b_mean, b_sigma = mean(baseline_scores), stdev(baseline_scores)
    pooled_sigma = max(c_sigma, b_sigma, 1e-9)
    delta = c_mean - b_mean
    if abs(delta) < min_sigma_multiple * pooled_sigma:
        raise OrderingArtifactError(
            f"delta={delta:.2f} within ordering envelope "
            f"(pooled_sigma={pooled_sigma:.2f}); gate must abstain, not fail"
        )
    return {"regressed": delta < 0, "delta": delta, "sigma": pooled_sigma}
