# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-trust-broker-re-attestation-skew-when-federated-policy-routing-silently-widens-a-peer-s-effective-scope-mid.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-trust-broker-re-attestation-skew-when-federated-policy-routing-silently-widens-a-peer-s-effective-scope-mid.warrant.json
# Markdown SHA-256:   52fb2f3f23a99e78b9b06396caeea1b66b0447333c3bdec3dac01fe40208195c
# Code AST SHA-256:   7a2ab09a12bee18e93a5ecc07a07a5508d58c53a63f0279bb19ec3735834b595
# Verified Classes:   StalePeerEpochError, WarrantView, FederatedRouter
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StalePeerEpochError(RuntimeError):
    """Raised when a routed message's peer-epoch claim is older than the
    receiver's authoritative warrant epoch, or when the epoch gap exceeds
    the configured tolerance and a re-attestation is required."""


@dataclass(frozen=True)
class WarrantView:
    peer_id: str
    epoch: int
    scope: frozenset[str]


class FederatedRouter:
    def __init__(self, broker_epochs: dict[str, int], tolerance: int = 2):
        self._broker_epochs = broker_epochs  # peer_id -> latest published epoch
        self._cache: dict[str, WarrantView] = {}
        self._tolerance = tolerance

    def cache_warrant(self, view: WarrantView) -> None:
        self._cache[view.peer_id] = view

    def _gap(self, peer_id: str) -> int:
        cached = self._cache.get(peer_id)
        if cached is None:
            raise StalePeerEpochError(f"no cached warrant for peer {peer_id!r}")
        published = self._broker_epochs.get(peer_id)
        if published is None:
            raise StalePeerEpochError(
                f"broker has no epoch publication for peer {peer_id!r}; "
                "epoch stream may have lapsed"
            )
        return published - cached.epoch

    def route(self, peer_id: str, capability: str) -> dict:
        gap = self._gap(peer_id)
        if gap < 0:
            # Broker epoch went backwards: broker rollback or epoch recycling.
            raise StalePeerEpochError(
                f"epoch regression for peer {peer_id!r}: cached={self._cache[peer_id].epoch} "
                f"published={self._broker_epochs[peer_id]}"
            )
        if gap > self._tolerance:
            raise StalePeerEpochError(
                f"epoch gap {gap} exceeds tolerance {self._tolerance} for peer "
                f"{peer_id!r}; synchronous re-attestation required before routing"
            )
        cached = self._cache[peer_id]
        if capability not in cached.scope:
            raise StalePeerEpochError(
                f"capability {capability!r} not in cached scope for peer {peer_id!r} "
                f"at epoch {cached.epoch}"
            )
        # Route with the epoch claim attached so the receiver can validate.
        return {"peer_id": peer_id, "capability": capability, "x_peer_epoch": cached.epoch}
