# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-peer-s-revocation-epoch-advances-mid-session-and-its-own-attestation-cache-still-validates-the-stale-key.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-peer-s-revocation-epoch-advances-mid-session-and-its-own-attestation-cache-still-validates-the-stale-key.warrant.json
# Markdown SHA-256:   64209f865064b517aed738caf89766009dc12318e77105810e1b69c89b818428
# Code AST SHA-256:   af50fbd62cbf62ca559f8a5498cba8bb6a67663ac14d56e6fc87a173f762b06c
# Verified Classes:   RevocationEpochDivergence, Authority, Attestation, InboundMessage, AttestationGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class RevocationEpochDivergence(RuntimeError):
    """Raised when a cached attestation predates an observed epoch advance
    and the peer's current authority cannot be confirmed. This is a halt
    condition for acts of authority, not for evidence collection."""


class Authority(Enum):
    PROVENANCED = "provenanced"   # signature valid at signing epoch; may be logged
    AUTHORIZED = "authorized"     # valid for the *current* epoch; may act
    QUARANTINED = "quarantined"   # provenance ok, current authority unknown/revoked


@dataclass
class Attestation:
    peer_id: str
    key_fingerprint: str
    capabilities: frozenset
    verified_at_epoch: int
    ttl_seconds: int
    age_seconds: int = 0


@dataclass
class InboundMessage:
    peer_id: str
    key_fingerprint: str
    claimed_epoch: int
    signature_valid: bool
    payload: bytes


class AttestationGate:
    """Two-phase gate: provenance (cached, cheap) vs authority (current)."""

    def __init__(self, local_epoch_witness: int, propagation_bound_s: int):
        self.local_epoch_witness = local_epoch_witness
        self.propagation_bound_s = propagation_bound_s
        self._cache: dict[tuple[str, str], Attestation] = {}

    def observe_epoch(self, epoch: int) -> None:
        if epoch > self.local_epoch_witness:
            # We were partitioned from the revocation feed. Degrade until
            # the witness catches up; do not trust cached authority meanwhile.
            self.local_epoch_witness = epoch

    def _cache_key(self, msg: InboundMessage) -> tuple[str, str]:
        # Keyed on attested key material, NOT peer_id alone, so a re-keyed
        # peer cannot inherit its predecessor's cached capabilities.
        return (msg.peer_id, msg.key_fingerprint)

    def classify(self, msg: InboundMessage, is_act_of_authority: bool) -> Authority:
        if not msg.signature_valid:
            return Authority.QUARANTINED

        # Detection event: message epoch ahead of our witness => we are stale.
        if msg.claimed_epoch > self.local_epoch_witness:
            self.observe_epoch(msg.claimed_epoch)

        entry: Optional[Attestation] = self._cache.get(self._cache_key(msg))
        if entry is None:
            # Cache miss: must fetch fresh before any authority grant.
            if is_act_of_authority:
                raise RevocationEpochDivergence(
                    f"no cached attestation for {msg.peer_id}/{msg.key_fingerprint}; "
                    "fresh fetch required before granting authority"
                )
            return Authority.PROVENANCED

        # Provenance is always answerable from cache.
        if entry.age_seconds > entry.ttl_seconds:
            if is_act_of_authority:
                raise RevocationEpochDivergence(
                    f"attestation for {msg.peer_id} expired (age={entry.age_seconds}s "
                    f"> ttl={entry.ttl_seconds}s); re-verify before acting"
                )
            return Authority.PROVENANCED

        if not is_act_of_authority:
            return Authority.PROVENANCED

        # Authority requires current epoch to match the attestation epoch.
        if self.local_epoch_witness > entry.verified_at_epoch:
            raise RevocationEpochDivergence(
                f"epoch advanced {entry.verified_at_epoch}->{self.local_epoch_witness} "
                f"while attestation for {msg.peer_id} was cached; current authority "
                "unconfirmed, quarantining act"
            )
        return Authority.AUTHORIZED

    def record(self, msg: InboundMessage, verified_at_epoch: int) -> None:
        # TTL must be bounded by measured revocation propagation, not convenience.
        ttl = min(300, self.propagation_bound_s)
        self._cache[self._cache_key(msg)] = Attestation(
            peer_id=msg.peer_id,
            key_fingerprint=msg.key_fingerprint,
            capabilities=frozenset(),
            verified_at_epoch=verified_at_epoch,
            ttl_seconds=ttl,
        )
