# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-a-revocation-shadow-window-when-a-federated-peer-s-capability-grant-is-withdrawn-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-a-revocation-shadow-window-when-a-federated-peer-s-capability-grant-is-withdrawn-mid-handoff.warrant.json
# Markdown SHA-256:   f774ceffd970ebc58ef71590a88fded473bf41fd7c2d5b39b23be65111b00974
# Code AST SHA-256:   60717a6fda1057ef9333762fb8645d8d136a28a3b92c8b5571547aa014f3f173
# Verified Classes:   RevocationShadowError, Warrant, VerifierState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class RevocationShadowError(RuntimeError):
    """Raised when a capability or derived artifact is used under a warrant
    whose revocation epoch is stale relative to the verifier's known epoch,
    or when an artifact cannot be attributed to an authorizing warrant."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    authority: str          # org that issued the root grant
    epoch: int              # revocation epoch at issuance
    expires_at: float
    capability: str
    parent_epoch: Optional[int] = None  # epoch of the delegating warrant


@dataclass
class VerifierState:
    known_epoch: dict       # authority -> latest observed epoch
    cache_ttl: float


def validate_warrant(w: Warrant, state: VerifierState, now: float) -> None:
    if now >= w.expires_at:
        raise RevocationShadowError(
            f"warrant {w.warrant_id} expired at {w.expires_at}, now {now}"
        )
    latest = state.known_epoch.get(w.authority)
    if latest is None:
        raise RevocationShadowError(
            f"no revocation epoch observed for authority {w.authority}; "
            f"refusing to trust warrant {w.warrant_id} (fail closed)"
        )
    if w.epoch < latest:
        raise RevocationShadowError(
            f"warrant {w.warrant_id} carries epoch {w.epoch} but authority "
            f"{w.authority} is at epoch {latest}; revocation-shadow window"
        )
    if w.parent_epoch is not None and w.parent_epoch < latest:
        raise RevocationShadowError(
            f"warrant {w.warrant_id} was delegated under stale parent epoch "
            f"{w.parent_epoch} (authority at {latest}); stale-epoch delegation"
        )


def tag_artifact(w: Warrant, state: VerifierState, payload: bytes) -> dict:
    # Called before any durable write derived from a capability use.
    validate_warrant(w, state, now=__import__("time").time())
    return {
        "payload": payload,
        "authorized_by": w.warrant_id,
        "authority": w.authority,
        "epoch": w.epoch,
    }


def purge_on_revocation(store, authority: str, revoked_epoch: int) -> int:
    # Quarantine every artifact whose authorizing epoch is now stale.
    purged = 0
    for artifact in store.scan(authority=authority):
        if artifact["epoch"] < revoked_epoch:
            store.quarantine(artifact)
            purged += 1
    return purged
