# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-keep-trusting-a-revoked-capability-when-the-revocation-was-signed-propagated-and-acknowledged.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-keep-trusting-a-revoked-capability-when-the-revocation-was-signed-propagated-and-acknowledged.warrant.json
# Markdown SHA-256:   e9f965c3f927df22d4d32a673be1cb33f4d6e975e010b3bd724fb61a4e8e2617
# Code AST SHA-256:   8ab0557342f035078087ecb9122e5fb9250d345b880539397607b5c4e14f17a6
# Verified Classes:   RevocationCoherenceError, CapabilityTuple, AdmissionCacheEntry, RevocationRecord, FederatedAdmissionGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Optional, Set


class RevocationCoherenceError(RuntimeError):
    """Raised when an admission decision would rely on a revoked capability."""
    pass


@dataclass(frozen=True)
class CapabilityTuple:
    issuer: str
    subject: str
    capability: str


@dataclass
class AdmissionCacheEntry:
    decision: bool
    s_create: int          # bundle sequence at which this entry was created
    expiry: float          # wall-clock TTL, NOT a substitute for s_create


@dataclass
class RevocationRecord:
    capability_tuple: CapabilityTuple
    revocation_seq: int    # authority sequence, not mirror sequence
    acknowledged: bool = False
    committed: bool = False


class FederatedAdmissionGate:
    def __init__(self) -> None:
        self._cache: Dict[CapabilityTuple, AdmissionCacheEntry] = {}
        self._revocations: Dict[CapabilityTuple, RevocationRecord] = {}

    def register_revocation(self, rec: RevocationRecord) -> None:
        # Revocation events MUST carry the tuple; claim-ID-only events cannot
        # compute an invalidation key and silently leave the cache warm.
        self._revocations[rec.capability_tuple] = rec
        rec.acknowledged = True

    def commit_revocation(self, tup: CapabilityTuple) -> None:
        rec = self._revocations.get(tup)
        if rec is None:
            raise RevocationCoherenceError(
                f"cannot commit revocation for unknown tuple {tup}"
            )
        # Sweep the admission cache for this tuple before committing.
        self._cache.pop(tup, None)
        rec.committed = True

    def admit(self, tup: CapabilityTuple, now: float) -> bool:
        entry = self._cache.get(tup)
        if entry is None or entry.expiry <= now:
            # Cold path: fetch a fresh bundle from the authority sequence.
            entry = AdmissionCacheEntry(decision=True, s_create=self._authority_seq(), expiry=now + 900.0)
            self._cache[tup] = entry

        rec = self._revocations.get(tup)
        if rec is not None and rec.revocation_seq > entry.s_create:
            # The revocation-closure invariant is violated: the cached entry
            # predates a revocation the instance has already acknowledged.
            raise RevocationCoherenceError(
                f"admission for {tup} would rely on claim revoked at seq "
                f"{rec.revocation_seq} but cached at seq {entry.s_create}; "
                f"acknowledged={rec.acknowledged} committed={rec.committed}"
            )
        return entry.decision

    def _authority_seq(self) -> int:
        # Placeholder: real implementations read R_auth's sequence, never R_peer's.
        return 4471
