# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-caches-a-peer-s-trust-anchor-past-a-revocation-epoch-stale-warrant-replay-in-cross-organization-agent-federations.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-caches-a-peer-s-trust-anchor-past-a-revocation-epoch-stale-warrant-replay-in-cross-organization-agent-federations.warrant.json
# Markdown SHA-256:   4e6cf2bc90f83e033a5123926ce30d6ee4c85ab43211b316e343106990d94903
# Code AST SHA-256:   eabc81dd447c358e2e0581a84cfbfda4890e25d7096d00be89377de1ecc3ab79
# Verified Classes:   StaleAnchorEpochError, FederationTrustStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleAnchorEpochError(RuntimeError):
    """Raised when a warrant's issuer epoch is superseded by an observed anchor revocation."""
    pass


class FederationTrustStore:
    def __init__(self, max_staleness_seconds: int):
        self.max_staleness = max_staleness_seconds
        self.last_seen_epoch: dict[str, int] = {}      # issuer -> highest epoch observed
        self.anchor_fetched_at: dict[str, float] = {}  # issuer -> monotonic timestamp

    def observe_revocation(self, issuer: str, revoked_epoch: int) -> None:
        # Any observed anchor revocation advances the watermark immediately,
        # regardless of cache TTL. This is the trigger that closes the replay window.
        self.last_seen_epoch[issuer] = max(
            self.last_seen_epoch.get(issuer, -1), revoked_epoch
        )

    def validate_warrant(self, warrant: dict, now: float) -> None:
        issuer = warrant["issuer"]
        issuer_epoch = warrant["issuer_epoch"]

        watermark = self.last_seen_epoch.get(issuer)
        if watermark is None:
            raise StaleAnchorEpochError(
                f"no anchor epoch observed for issuer={issuer}; fail closed"
            )

        # Core invariant: a warrant minted under a superseded anchor epoch is
        # inadmissible even if its signature verifies and its ID was never revoked.
        if issuer_epoch < watermark:
            raise StaleAnchorEpochError(
                f"warrant {warrant['id']} minted at epoch={issuer_epoch} "
                f"but issuer={issuer} has observed revocation through epoch={watermark}"
            )

        fetched = self.anchor_fetched_at.get(issuer)
        if fetched is None or (now - fetched) > self.max_staleness:
            raise StaleAnchorEpochError(
                f"anchor for issuer={issuer} exceeds max staleness "
                f"({self.max_staleness}s); refusing to validate against a stale anchor"
            )
        # signature check omitted here; it is necessary but NOT sufficient
