# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-brokered-capability-warrant-whose-issuer-chain-has-already-expired-at-the-moment-of-first-use.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-brokered-capability-warrant-whose-issuer-chain-has-already-expired-at-the-moment-of-first-use.warrant.json
# Markdown SHA-256:   4231a5758e210c2d4c1eb31df06e850b6cbd68cefcb8816d884a3577c523ec73
# Code AST SHA-256:   2614c99c217b3ee102bb89ae65ad2c74a7750d2a4e20a46d94d13cc5ef73c305
# Verified Classes:   StaleAttestationError, BrokeredWarrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAttestationError(RuntimeError):
    """Raised when a brokered warrant is used past its broker attestation window,
    or when the peer's revocation timestamp postdates the attestation issuance."""


@dataclass(frozen=True)
class BrokeredWarrant:
    sub: str
    cap: str
    broker_iat: float
    broker_exp: float
    peer_iat: float
    peer_exp: float


def validate_inbound_brokered_call(
    warrant: BrokeredWarrant,
    now: float,
    peer_revocation_ts: dict[tuple[str, str], float],
) -> None:
    # Condition 1: broker attestation must still be live.
    if now >= warrant.broker_exp:
        raise StaleAttestationError(
            f"broker attestation for {warrant.sub}/{warrant.cap} expired at "
            f"{warrant.broker_exp}; now={now}"
        )

    # Condition 4: peer must reject warrants whose attestation predates
    # its own latest revocation for this capability.
    last_revoked = peer_revocation_ts.get((warrant.sub, warrant.cap))
    if last_revoked is not None and last_revoked > warrant.broker_iat:
        raise StaleAttestationError(
            f"capability {warrant.sub}/{warrant.cap} was revoked at "
            f"{last_revoked}, after warrant attestation iat={warrant.broker_iat}"
        )

    # Condition 2: peer's own claim must still be live.
    if now >= warrant.peer_exp:
        raise StaleAttestationError(
            f"peer capability claim for {warrant.sub}/{warrant.cap} expired at "
            f"{warrant.peer_exp}; now={now}"
        )


def effective_ttl(warrant: BrokeredWarrant, now: float) -> float:
    # The only correct cache TTL: the shorter of the two windows.
    return min(warrant.broker_exp, warrant.peer_exp) - now


# --- reproduction of the observed trace ---
w = BrokeredWarrant(
    sub="B.summarizer", cap="summarize:corpus",
    broker_iat=1000.0, broker_exp=1090.0,
    peer_iat=1000.0, peer_exp=4600.0,
)
revocations = {("B.summarizer", "summarize:corpus"): 1050.0}

# Naive cache-by-longest-field would have served this at t=1200.
validate_inbound_brokered_call(w, now=1200.0, peer_revocation_ts=revocations)
# -> raises StaleAttestationError: attestation expired at 1090.0
