# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-brokered-trust-warrant-outlives-the-policy-revision-that-minted-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-brokered-trust-warrant-outlives-the-policy-revision-that-minted-it.warrant.json
# Markdown SHA-256:   56554000ceb2350c41a56abcca80927f45f24bec824cd190c5dfaf4df10e1f9e
# Code AST SHA-256:   27fec26f86e1144a753a5b514677517757835ca174b70aa68cb9dd8719bb935a
# Verified Classes:   PolicyRevisionSkew, Warrant, PeerResourceAgent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import FrozenSet


class PolicyRevisionSkew(RuntimeError):
    """Raised when a warrant's mint-time policy revision is not in the
    peer's accepted-revision set, or when the warrant's predicate set
    cannot be reconciled with the peer's current rules."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    scope: str
    policy_revision: int
    predicate_set: FrozenSet[str]
    minted_at: float
    ttl_seconds: int

    def is_expired(self, now: float) -> bool:
        return now > self.minted_at + self.ttl_seconds


@dataclass
class PeerResourceAgent:
    accepted_revisions: FrozenSet[int]
    # Predicates the peer is willing to honor, keyed by revision.
    honored_predicates: dict = field(default_factory=dict)

    def admit(self, warrant: Warrant, now: float) -> bool:
        if warrant.is_expired(now):
            raise PolicyRevisionSkew(
                f"warrant {warrant.warrant_id} expired; requester must re-mint"
            )
        if warrant.policy_revision not in self.accepted_revisions:
            # Distinguishable from generic 403 so the orchestrator re-mints
            # instead of retrying the same stale warrant.
            raise PolicyRevisionSkew(
                f"warrant {warrant.warrant_id} minted under policy revision "
                f"{warrant.policy_revision}, not in accepted set "
                f"{sorted(self.accepted_revisions)}"
            )
        honored = self.honored_predicates.get(warrant.policy_revision, frozenset())
        ungranted = warrant.predicate_set - honored
        if ungranted:
            raise PolicyRevisionSkew(
                f"warrant {warrant.warrant_id} asserts predicates "
                f"{sorted(ungranted)} not honored under peer revision "
                f"{warrant.policy_revision}"
            )
        return True


def brokered_read(peer: PeerResourceAgent, warrant: Warrant, now: float) -> bool:
    try:
        return peer.admit(warrant, now)
    except PolicyRevisionSkew:
        # Re-mint path is the caller's responsibility; surface, do not retry.
        raise
