# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-workload-token-during-a-mid-call-re-exchange-against-a-warm-mcp-peer.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-workload-token-during-a-mid-call-re-exchange-against-a-warm-mcp-peer.warrant.json
# Markdown SHA-256:   3a24f8df9dc5914a7dd73650bf2d40fc5c0d4107dcf9d474153fae532bc56426
# Code AST SHA-256:   5d453d08b67e9e14e260d006948ad3927f445ed877b6414cb9f076efef8fd831
# Verified Classes:   RevocationWindowViolation, PeerAuthCache
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RevocationWindowViolation(RuntimeError):
    """Raised when a peer serves a cached authorization decision whose
    revocation epoch predates the current epoch, i.e. the cache outlived
    the revocation it was supposed to respect."""
    pass


class PeerAuthCache:
    def __init__(self, revocation_propagation_budget_s: float):
        self.budget = revocation_propagation_budget_s
        self._entries: dict[tuple, dict] = {}

    def admit(self, subject: str, actor: str, scope: str,
              jti: str, rev_epoch: int, token_remaining_s: float,
              now: float, current_rev_epoch: int) -> bool:
        key = (subject, actor, scope)
        entry = self._entries.get(key)

        if entry is not None:
            # The invariant: a cached allow may not outlive its rev_epoch.
            if entry["rev_epoch"] < current_rev_epoch:
                # Stale decision under an older epoch: must not be served.
                raise RevocationWindowViolation(
                    f"cached allow for {key} minted at rev_epoch="
                    f"{entry['rev_epoch']} but current epoch is "
                    f"{current_rev_epoch}; serving would admit a revoked "
                    f"identity for up to {entry['valid_until'] - now:.1f}s"
                )
            if now < entry["valid_until"] and entry["jti"] == jti:
                return True
            # jti mismatch or expiry: fall through to revalidate.

        # Fresh admission: cap TTL at the revocation propagation budget.
        ttl = min(token_remaining_s, self.budget)
        if ttl <= 0:
            raise RevocationWindowViolation(
                f"cannot cache decision for {key}: ttl={ttl:.1f}s "
                f"(budget={self.budget}s, token_remaining={token_remaining_s}s)"
            )
        self._entries[key] = {
            "jti": jti,
            "rev_epoch": rev_epoch,
            "valid_until": now + ttl,
        }
        return True
