# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-peer-presents-a-revocation-epoch-that-is-newer-than-its-own-issuer-s-signed-epoch-but-older-than-the-peer-s-rotated.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-peer-presents-a-revocation-epoch-that-is-newer-than-its-own-issuer-s-signed-epoch-but-older-than-the-peer-s-rotated.warrant.json
# Markdown SHA-256:   8b31ca53a1ff8380ba0ac343e5a90b69fe06eb8ea7c80f4f31b8ef860b1f688f
# Code AST SHA-256:   32f6707cf7b69525c0a7671c0ccf50814bdbaa88a5c4304aa2e071640300f039
# Verified Classes:   EpochSkewViolation, TokenClaim, SignedEpoch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class EpochSkewViolation(RuntimeError):
    """Raised when a peer token's revocation epoch cannot be safely reconciled
    with the verifier's issuer-signed epoch under the halt-band invariant."""
    pass


@dataclass(frozen=True)
class TokenClaim:
    rev_epoch: int
    iat: float          # token mint time (issuer clock)
    subject: str


@dataclass(frozen=True)
class SignedEpoch:
    epoch: int
    fetched_at: float   # verifier wall-clock at signed fetch


DELTA_SYNC = 300.0      # max tolerated propagation lag, seconds


def admit_handoff(
    claim: TokenClaim,
    cached: SignedEpoch,
    now: float,
) -> bool:
    """Enforce: token claim is evidence about the peer, never about the issuer.
    Never adopt claim.rev_epoch as the verifier's epoch."""
    if claim.rev_epoch < cached.epoch:
        # ordinary stale-token rejection
        return False

    if claim.rev_epoch == cached.epoch:
        # equality is NOT sufficient: a revocation could have landed
        # between the cache fetch and the token mint.
        if cached.fetched_at < claim.iat:
            raise EpochSkewViolation(
                f"epoch equality {cached.epoch} but cache fetched "
                f"{claim.iat - cached.fetched_at:.1f}s before token mint "
                f"for subject={claim.subject}; revocation window open"
            )
        return True

    # claim is newer than cache: inside or outside the halt band?
    skew = claim.rev_epoch - cached.epoch
    if skew > 0 and (now - cached.fetched_at) <= DELTA_SYNC:
        # inside halt band: must do a blocking signed fetch, never adopt claim
        raise EpochSkewViolation(
            f"epoch skew {skew} within halt band for subject={claim.subject}; "
            f"blocking signed fetch required before admission"
        )

    # skew beyond tolerated propagation lag: partitioned or forged issuer view
    raise EpochSkewViolation(
        f"epoch skew {skew} exceeds DELTA_SYNC={DELTA_SYNC}s for "
        f"subject={claim.subject}; hard reject and escalate to swarm auditor"
    )
