# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-attest-its-capability-warrant-after-a-trust-broker-rotates-and-why-policy-negotiated-routing-silently-accepts-the-stale-one.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-attest-its-capability-warrant-after-a-trust-broker-rotates-and-why-policy-negotiated-routing-silently-accepts-the-stale-one.warrant.json
# Markdown SHA-256:   57aefb90d246f80037dbba22fafd6f7f863fdb5576e2060a72eb6ac9ccb9f54e
# Code AST SHA-256:   b029fe0d91bffcb6147561567e4572a17bb4e7e984acd5d150f9980e08531414
# Verified Classes:   StaleEpochWarrantError, CachedDecision, EpochAwareGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleEpochWarrantError(RuntimeError):
    """Raised when a cached authorization decision is bound to a broker epoch
    that is no longer current, so the decision cannot be honored without
    full re-validation against the live epoch."""
    pass


@dataclass(frozen=True)
class CachedDecision:
    broker_id: str
    broker_epoch: int          # epoch under which the decision was derived
    warrant_serial: str
    subject_agent: str
    capability: str
    policy_id: str
    policy_hash: str
    not_after: float


class EpochAwareGate:
    def __init__(self, epoch_source):
        # epoch_source.current_epoch(broker_id) -> int, cheap, seconds-cached
        self._epoch_source = epoch_source
        self._cache: dict[tuple, CachedDecision] = {}

    def admit(self, decision: CachedDecision, now: float) -> None:
        if now >= decision.not_after:
            raise StaleEpochWarrantError(
                f"warrant {decision.warrant_serial} expired at {decision.not_after}"
            )

        current = self._epoch_source.current_epoch(decision.broker_id)

        if decision.broker_epoch != current:
            # The decision was derived under a superseded epoch. It is not
            # "invalid" -- it is unverified. Force full re-validation against
            # the current epoch's keys, revocation list, and policy hash.
            raise StaleEpochWarrantError(
                f"cached decision for {decision.subject_agent}->{decision.capability} "
                f"derived under broker {decision.broker_id}@{decision.broker_epoch}, "
                f"but current epoch is {current}; re-validate before execution"
            )

    def revalidate_and_store(self, fresh: CachedDecision, now: float) -> None:
        # Caller must have re-verified signature against current-epoch keys,
        # checked revocation for fresh.warrant_serial, and confirmed
        # policy_hash matches the negotiated policy under the current epoch.
        current = self._epoch_source.current_epoch(fresh.broker_id)
        if fresh.broker_epoch != current:
            raise StaleEpochWarrantError(
                f"revalidation produced warrant under epoch {fresh.broker_epoch}, "
                f"expected {current}; refusing to cache"
            )
        key = (fresh.broker_id, fresh.broker_epoch, fresh.warrant_serial)
        self._cache[key] = fresh
