# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-when-reputation-attestations-outlive-the-revocation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-when-reputation-attestations-outlive-the-revocation-epoch.warrant.json
# Markdown SHA-256:   6ac44d7ab66b9a7cf1c3cca496ce3993dd1d5b54472537a1a0609e99ccae1722
# Code AST SHA-256:   4b66170ce2fff37a144fa5799159b8dc2d6174a206992aa2920e65695f8deece
# Verified Classes:   StaleAttestationError, MissingRevokerEpochError, Attestation, RevocationRecord, EpochMap
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleAttestationError(RuntimeError):
    """Raised when a cached attestation's bound revocation epoch is behind
    the revoker's current epoch, meaning the attestation may describe a
    trust relationship that has since been revoked."""
    pass


class MissingRevokerEpochError(RuntimeError):
    """Raised when an attestation does not bind the epoch of a revoker
    that the receiver knows to be relevant, making cross-issuer
    revocation undetectable for that revoker."""
    pass


@dataclass
class Attestation:
    subject: str
    issuer: str
    score: float
    issued_at: float
    not_after: float
    revoker_epochs: dict = field(default_factory=dict)  # revoker_id -> epoch bound at issuance


@dataclass
class RevocationRecord:
    subject: str
    revoked_at: float
    effective_epoch: int
    effective_from: float  # timestamp from which subject was untrusted


class EpochMap:
    """Local cache of each revoker's current epoch, refreshed on an interval
    shorter than the attestation TTL."""

    def __init__(self, refresh_interval_s: float = 10.0):
        self._epochs: dict = {}
        self._last_refresh: float = 0.0
        self._refresh_interval_s = refresh_interval_s

    def current_epoch(self, revoker: str, now: float) -> int:
        if now - self._last_refresh > self._refresh_interval_s:
            # In production: fetch from revoker's status endpoint.
            self._last_refresh = now
        if revoker not in self._epochs:
            raise MissingRevokerEpochError(
                f"no epoch known for revoker {revoker!r}; cannot verify attestation"
            )
        return self._epochs[revoker]

    def set_epoch(self, revoker: str, epoch: int) -> None:
        self._epochs[revoker] = epoch


def verify_attestation_at_use(
    attestation: Attestation,
    epoch_map: EpochMap,
    required_revokers: set,
    now: float,
) -> None:
    """Called on every use of a cached attestation, not on cache fill.
    Raises if the attestation is stale with respect to any revoker's epoch."""
    if now > attestation.not_after:
        raise StaleAttestationError(
            f"attestation for {attestation.subject!r} expired at {attestation.not_after}"
        )
    for revoker in required_revokers:
        if revoker not in attestation.revoker_epochs:
            raise MissingRevokerEpochError(
                f"attestation for {attestation.subject!r} does not bind epoch of "
                f"revoker {revoker!r}; cross-issuer revocation undetectable"
            )
        bound = attestation.revoker_epochs[revoker]
        current = epoch_map.current_epoch(revoker, now)
        if current > bound:
            raise StaleAttestationError(
                f"attestation for {attestation.subject!r} bound {revoker} epoch "
                f"{bound} but current epoch is {current}; possible revocation "
                f"between issuance and now"
            )


def audit_dispatch_window(
    dispatches: list,
    revocation: RevocationRecord,
) -> list:
    """Reconstruct which past dispatches to a subject occurred after the
    revocation's effective_from. Requires per-dispatch timestamps recorded
    at dispatch time."""
    violations = []
    for d in dispatches:
        if d["subject"] == revocation.subject and d["dispatched_at"] >= revocation.effective_from:
            violations.append(d)
    if violations and not revocation.effective_from:
        raise StaleAttestationError(
            "revocation record lacks effective_from; cannot bound violation window"
        )
    return violations
