# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-learn-from-its-own-trace-eval-loop-poisoning-at-the-observability-to-safety-gate-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-learn-from-its-own-trace-eval-loop-poisoning-at-the-observability-to-safety-gate-boundary.warrant.json
# Markdown SHA-256:   73f0efc0e70277d895e502c2923d8cb55d2a54101cac863f74ce5b4da3910515
# Code AST SHA-256:   534d182d3cdf4a9458abafbb8177cfd987af07d0ddcb1eb59a4b097c3e7cb2c8
# Verified Classes:   CensoredEvidenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CensoredEvidenceError(RuntimeError):
    """Raised when a gate-relaxation promotion is attempted on evidence
    that is conditioned on the gate's own decision (censoring bias)."""
    pass


FROZEN = "frozen"
LEARNED = "learned"


def promote_relaxation(candidate, traces, tau=0.15):
    """
    candidate: dict with keys 'tool', 'arg_class', 'provenance'
    traces: list of dicts with keys 'tool', 'arg_class', 'blocked',
            'judge_verdict', 'source'
    """
    if candidate["provenance"] == FROZEN:
        raise CensoredEvidenceError(
            f"refusing to relax frozen entry {candidate['tool']}:"
            f"{candidate['arg_class']} — frozen entries are never relaxable"
        )

    relevant = [
        t for t in traces
        if t["tool"] == candidate["tool"]
        and t["arg_class"] == candidate["arg_class"]
        and t["blocked"]
    ]
    if not relevant:
        raise CensoredEvidenceError(
            f"no blocked traces for {candidate['tool']}:{candidate['arg_class']};"
            " empty set cannot justify relaxation"
        )

    benign = sum(1 for t in relevant if t["judge_verdict"] == "benign")
    rate = benign / len(relevant)
    if rate <= tau:
        return {"action": "hold", "rate": rate}

    witnesses = [
        t for t in relevant
        if t["source"] in ("shadow_probe", "frozen_corpus")
    ]
    if not witnesses:
        raise CensoredEvidenceError(
            f"relaxation of {candidate['tool']}:{candidate['arg_class']} "
            f"justified only by gate-censored traces (rate={rate:.2f}); "
            "need >=1 censoring-independent witness"
        )

    return {"action": "relax", "rate": rate, "witnesses": len(witnesses)}
