# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-brokered-trust-warrant-whose-policy-closure-is-satisfiable-only-under-a-stale-peer-capability-advertis.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-brokered-trust-warrant-whose-policy-closure-is-satisfiable-only-under-a-stale-peer-capability-advertis.warrant.json
# Markdown SHA-256:   20e5e99890caeb82ebcb9d4a2dbdce698a84aae0c69304b54365dc53828ccc27
# Code AST SHA-256:   01e6cc7fc9f9ed6b46386d02711b9b5b7e6a8e8b1cdaed5ba2333a011fa43601
# Verified Classes:   StaleCapabilityWarrantError, CapabilityAdvertisement, Warrant, BrokerCache
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class StaleCapabilityWarrantError(RuntimeError):
    """Raised when a brokered warrant's capability snapshot is not provably
    current at the peer, or when a policy denial against a validly-signed
    warrant is treated as retryable instead of as a stale-snapshot signal."""


@dataclass(frozen=True)
class CapabilityAdvertisement:
    seq: int
    model_version: str
    max_rows_per_query: int
    residency_tag: str
    valid_until: float


@dataclass(frozen=True)
class Warrant:
    requester: str
    peer: str
    action: str
    constraints: dict
    capability_seq: int
    valid_until: float
    signature_valid: bool = True


@dataclass
class BrokerCache:
    peer: str
    advertisement: CapabilityAdvertisement
    fetched_at: float
    ttl_seconds: float = 900.0

    def is_fresh(self, now: float) -> bool:
        return (now - self.fetched_at) < self.ttl_seconds


def mint_warrant(
    cache: BrokerCache,
    requester: str,
    action: str,
    constraints: dict,
    now: float,
) -> Warrant:
    if not cache.is_fresh(now):
        raise StaleCapabilityWarrantError(
            f"broker cache for {cache.peer} expired; refusing to mint against "
            f"advertisement seq={cache.advertisement.seq}"
        )
    adv = cache.advertisement
    if constraints.get("rows", 0) > adv.max_rows_per_query:
        raise StaleCapabilityWarrantError(
            f"requested rows={constraints['rows']} exceed advertised "
            f"max_rows_per_query={adv.max_rows_per_query} at seq={adv.seq}"
        )
    return Warrant(
        requester=requester,
        peer=cache.peer,
        action=action,
        constraints=constraints,
        capability_seq=adv.seq,
        valid_until=min(now + 600.0, adv.valid_until),
    )


def present_warrant(
    warrant: Warrant,
    peer_current: CapabilityAdvertisement,
    now: float,
    retry_budget_for_policy_denial: int = 0,
) -> None:
    if not warrant.signature_valid:
        raise StaleCapabilityWarrantError("warrant signature invalid")

    if now >= warrant.valid_until:
        raise StaleCapabilityWarrantError("warrant expired")

    if warrant.capability_seq != peer_current.seq:
        # The peer has superseded the advertisement the broker minted against.
        # This is a stale-snapshot signal, not a transient fault.
        raise StaleCapabilityWarrantError(
            f"warrant minted against capability_seq={warrant.capability_seq} "
            f"but peer is at seq={peer_current.seq}; force cache-bypass refresh "
            f"before re-minting"
        )

    rows = warrant.constraints.get("rows", 0)
    if rows > peer_current.max_rows_per_query:
        # Policy denial against a validly-signed warrant. Retry budget MUST be
        # zero: retrying reproduces the failure deterministically.
        if retry_budget_for_policy_denial > 0:
            raise StaleCapabilityWarrantError(
                "policy denial against valid warrant treated as retryable; "
                "this is the denial-storm failure mode"
            )
        raise StaleCapabilityWarrantError(
            f"peer policy denies rows={rows} > {peer_current.max_rows_per_query}"
        )
