# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-trust-warrant-when-a-federated-revocation-arrives-after-the-credential-was-already-consumed-into-a-running-plan.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-trust-warrant-when-a-federated-revocation-arrives-after-the-credential-was-already-consumed-into-a-running-plan.warrant.json
# Markdown SHA-256:   5cc6ef519f3e3a119e6bdc82f18d603e8d4fc937e849db8db1e6d1381738f0e2
# Code AST SHA-256:   02d1de8d6a49567ee492a604c896055fd379e53312c91cc8bc2962bbe740956f
# Verified Classes:   StaleWarrantError, EpochRegressionError, StatusList, EpochKeyedTrustCache, FederatedTrustGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleWarrantError(RuntimeError):
    """Raised when a consumed warrant is used after its status epoch has advanced."""
    pass


class EpochRegressionError(RuntimeError):
    """Raised when an issuer's status epoch moves backwards (replay or fork)."""
    pass


@dataclass
class StatusList:
    epoch: int
    revoked: set[str] = field(default_factory=set)
    next_update: float = 0.0  # monotonic seconds


class EpochKeyedTrustCache:
    """
    Trust cache keyed by (peer_id, status_epoch). A lookup for the *current*
    epoch cannot hit an entry minted under a prior epoch, so revocation in
    epoch N+1 is structurally unable to be shadowed by a cache hit from N.
    """

    def __init__(self, max_ttl: float = 30.0):
        self._entries: dict[tuple[str, int], float] = {}  # key -> verified_at
        self._max_ttl = max_ttl

    def admit(self, peer_id: str, epoch: int, now: float) -> None:
        self._entries[(peer_id, epoch)] = now

    def is_trusted(self, peer_id: str, current_epoch: int, now: float) -> bool:
        key = (peer_id, current_epoch)
        verified_at = self._entries.get(key)
        if verified_at is None:
            return False
        return (now - verified_at) <= self._max_ttl


class FederatedTrustGate:
    def __init__(self, cache: EpochKeyedTrustCache):
        self._cache = cache
        self._last_seen_epoch: int | None = None

    def observe_status_list(self, sl: StatusList) -> None:
        if self._last_seen_epoch is not None and sl.epoch < self._last_seen_epoch:
            raise EpochRegressionError(
                f"issuer epoch regressed {self._last_seen_epoch} -> {sl.epoch}; "
                "possible replay or forked status list"
            )
        self._last_seen_epoch = sl.epoch

    def dispatch(
        self,
        peer_id: str,
        pinned_epoch: int,
        current_status: StatusList,
        now: float,
    ) -> None:
        """
        Called at every sub-task dispatch. Enforces the invariant: a warrant
        consumed under epoch E may only be used while the issuer still asserts
        epoch E and the credential is not revoked under E.
        """
        self.observe_status_list(current_status)

        if pinned_epoch != current_status.epoch:
            raise StaleWarrantError(
                f"plan pinned to epoch {pinned_epoch}, issuer now at "
                f"{current_status.epoch}; suspend plan and revalidate"
            )

        if peer_id in current_status.revoked:
            raise StaleWarrantError(
                f"peer {peer_id} revoked under epoch {current_status.epoch}"
            )

        if not self._cache.is_trusted(peer_id, current_status.epoch, now):
            # Cache miss for the *current* epoch forces fresh verification.
            self._cache.admit(peer_id, current_status.epoch, now)


def run_subtask(gate: FederatedTrustGate, peer_id: str, pinned_epoch: int,
                status: StatusList) -> None:
    now = time.monotonic()
    try:
        gate.dispatch(peer_id, pinned_epoch, status, now)
    except StaleWarrantError as e:
        # Plan-level handler: checkpoint and suspend, do not abort silently.
        raise StaleWarrantError(f"subtask blocked: {e}") from e
