# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-federated-identity-is-still-honored-by-a-peer-s-cached-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-federated-identity-is-still-honored-by-a-peer-s-cached-warrant.warrant.json
# Markdown SHA-256:   01e53e22e8ffe536e26333130d7a5073da55abf36b88d85f84a6b03f1c73a2e9
# Code AST SHA-256:   d86dfc155b93c87c6a46161786dfde1fc88151c615b4ef65955f01ca417ac578
# Verified Classes:   StaleWarrantCacheError, CachedVerdict, RevocationFencedVerifier
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleWarrantCacheError(RuntimeError):
    """Raised when a cached warrant verdict is consumed across a revocation-epoch increment."""
    pass


@dataclass(frozen=True)
class CachedVerdict:
    warrant_id: str
    issuer: str
    valid: bool
    written_epoch: int
    delegation_path: tuple[str, ...]


class RevocationFencedVerifier:
    def __init__(self, current_epoch: int, revoked_warrants: set[str],
                 revoked_issuers: set[str], cache_ttl: int, propagation_p99: int):
        if cache_ttl > propagation_p99:
            raise StaleWarrantCacheError(
                f"cache_ttl={cache_ttl}s exceeds revocation propagation p99={propagation_p99}s; "
                "authorization shadow is unbounded by propagation budget"
            )
        self.current_epoch = current_epoch
        self.revoked_warrants = revoked_warrants
        self.revoked_issuers = revoked_issuers
        self.cache: dict[str, CachedVerdict] = {}

    def consult(self, warrant_id: str, live_check) -> bool:
        cached: Optional[CachedVerdict] = self.cache.get(warrant_id)

        # Precedence: revocation set is checked BEFORE cache consultation.
        if warrant_id in self.revoked_warrants:
            self.cache.pop(warrant_id, None)
            return False

        if cached is not None:
            # Issuer-path closure: revoking the issuer poisons all delegated warrants.
            if any(iss in self.revoked_issuers for iss in cached.delegation_path):
                self.cache.pop(warrant_id, None)
                return False
            # Epoch fence: any observed revocation since write invalidates the cache entry.
            if cached.written_epoch != self.current_epoch:
                raise StaleWarrantCacheError(
                    f"cached verdict for {warrant_id} written at epoch {cached.written_epoch}, "
                    f"current epoch {self.current_epoch}; halt and re-verify before tool execution"
                )
            return cached.valid

        verdict = live_check(warrant_id)
        self.cache[warrant_id] = CachedVerdict(
            warrant_id=warrant_id,
            issuer=verdict["issuer"],
            valid=verdict["valid"],
            written_epoch=self.current_epoch,
            delegation_path=tuple(verdict["delegation_path"]),
        )
        return verdict["valid"]
