# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-federated-aaif-attestation-is-valid-at-ingress-but-its-revocation-epoch-has-already-advanced-at-the-issuing-org.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-federated-aaif-attestation-is-valid-at-ingress-but-its-revocation-epoch-has-already-advanced-at-the-issuing-org.warrant.json
# Markdown SHA-256:   b3eba59d6b09da928ad1e3635c634b64714831fb102133af1d209b6a2c5e339c
# Code AST SHA-256:   970ff3445a026f8235734f24156ea0796b6be8b2af0bba1b193154979a95d731
# Verified Classes:   StaleEpochAdmissionError, RevocationList, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleEpochAdmissionError(RuntimeError):
    """Raised when an attestation's issuer_epoch cannot be trusted because
    the relying party's held revocation epoch is older than the issuer's
    declared propagation SLA."""
    pass


@dataclass(frozen=True)
class RevocationList:
    issuer: str
    epoch: int
    revoked: frozenset
    fetched_at: float


@dataclass(frozen=True)
class Attestation:
    issuer: str
    subject: str
    issuer_epoch: int
    valid_until: float


def admit(
    att: Attestation,
    held: RevocationList,
    max_propagation_lag: float,
    now: float | None = None,
    sync_fetch=None,
) -> bool:
    now = time.time() if now is None else now

    if att.issuer != held.issuer:
        raise StaleEpochAdmissionError(
            f"issuer mismatch: attestation={att.issuer} held={held.issuer}"
        )

    if now >= att.valid_until:
        return False

    # Attestation minted in the future of our knowledge: protocol violation.
    if att.issuer_epoch > held.epoch:
        raise StaleEpochAdmissionError(
            f"attestation epoch {att.issuer_epoch} ahead of held {held.epoch}; "
            f"must fetch, not admit"
        )

    stale = (now - held.fetched_at) > max_propagation_lag
    if stale:
        # Boundary case: predicate passes but watermark is untrustworthy.
        if sync_fetch is None:
            raise StaleEpochAdmissionError(
                f"held epoch {held.epoch} is {now - held.fetched_at:.1f}s old "
                f"(SLA {max_propagation_lag}s) and no sync fetch available; "
                f"failing closed for issuer {att.issuer}"
            )
        fresh = sync_fetch(att.issuer)
        if fresh is None or fresh.epoch < held.epoch:
            raise StaleEpochAdmissionError(
                f"sync fetch failed or regressed for issuer {att.issuer}; "
                f"cannot authorize subject {att.subject}"
            )
        held = fresh

    if att.subject in held.revoked:
        return False

    return True
