# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-consensus-backed-revocation-warrant-as-stale-when-the-quorum-that-signed-it-has-since-rotated-its-aaif-sign.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-consensus-backed-revocation-warrant-as-stale-when-the-quorum-that-signed-it-has-since-rotated-its-aaif-sign.warrant.json
# Markdown SHA-256:   307b140670d8bf89f8b54c4f8b672673104834a37864528267e8b46bab851361
# Code AST SHA-256:   0229b287394441766d94612a0bb16c4c0d45d75dc8e81193f0a33346655d0add
# Verified Classes:   StaleRevocationWarrantError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleRevocationWarrantError(RuntimeError):
    """Raised when a revocation warrant's signing quorum has rotated away
    and a later-epoch admission credential exists for the subject."""
    pass


def apply_revocation(warrant, admission_log, current_epoch, authorized_quorum):
    """
    warrant: dict with keys 'subject', 'epoch', 'signers', 'signature'
    admission_log: dict subject -> list of admission records {'epoch': int}
    current_epoch: int, the verifier's operating epoch
    authorized_quorum: set of key ids authorized at current_epoch
    """
    e_w = warrant["epoch"]
    subject = warrant["subject"]

    if e_w > current_epoch:
        raise StaleRevocationWarrantError(
            f"warrant epoch {e_w} is future-dated relative to verifier epoch {current_epoch}"
        )

    # Condition 1: same epoch, quorum must match current authorization.
    if e_w == current_epoch:
        if not set(warrant["signers"]).issubset(authorized_quorum):
            raise StaleRevocationWarrantError(
                f"warrant signers {warrant['signers']} not authorized at epoch {current_epoch}"
            )
        return "applied"

    # Condition 2: rotation-surviving attestation present.
    if warrant.get("quorum_handoff") and set(warrant["quorum_handoff"]).issubset(authorized_quorum):
        return "applied"

    # Condition 3: stale epoch — check for later re-admission.
    later_admissions = [
        a for a in admission_log.get(subject, [])
        if e_w < a["epoch"] <= current_epoch
    ]
    if later_admissions:
        raise StaleRevocationWarrantError(
            f"warrant for {subject} at epoch {e_w} shadowed by re-admission at "
            f"epoch {later_admissions[-1]['epoch']}; escalate to quorum reconciliation"
        )

    # Stale but uncontradicted: provisional, require re-attestation.
    return "provisional"
