# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-delegated-capability-token-as-revoked-before-the-revocation-notice-reaches-it.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-delegated-capability-token-as-revoked-before-the-revocation-notice-reaches-it.warrant.json
# Markdown SHA-256:   b253fb3f1264792f022a69df83a8f43b743870cd7947502178bcf260660ac00d
# Code AST SHA-256:   6cd530ebf8bcf76ef1c58a1a442b188167e77fc39879b2bdc017194d6668b4f8
# Verified Classes:   StaleAuthorizationError, CapabilityToken, RevocationView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleAuthorizationError(RuntimeError):
    """Raised when a delegatee would act on a capability whose root
    revocation state has not been confirmed within the verification epoch."""


@dataclass
class CapabilityToken:
    token_id: str
    root_id: str            # id of the root authority whose revocation set governs this token
    exp: float              # absolute expiry (epoch seconds)
    nbf: float
    signature_ok: bool = True


@dataclass
class RevocationView:
    """Delegatee-local view of the root revocation set.

    Negatives are cached only up to one verification epoch; older entries
    are treated as UNKNOWN, never as 'not revoked'.
    """
    verification_epoch: float
    last_check: dict = field(default_factory=dict)   # root_id -> timestamp
    revoked: set = field(default_factory=set)        # token_ids known revoked

    def record_check(self, root_id: str, now: float) -> None:
        self.last_check[root_id] = now

    def authorization_fresh(self, root_id: str, now: float) -> bool:
        ts = self.last_check.get(root_id)
        if ts is None:
            return False
        return (now - ts) <= self.verification_epoch


def verify_at_work_unit_boundary(
    token: CapabilityToken,
    view: RevocationView,
    now: float | None = None,
) -> None:
    """Called at the start of EVERY work unit (tool call / file / batch).
    Raises StaleAuthorizationError rather than proceeding on stale auth.
    """
    now = time.time() if now is None else now

    # 1. Validity checks (signature + clock). These are necessary, not sufficient.
    if not token.signature_ok:
        raise StaleAuthorizationError(f"bad signature on {token.token_id}")
    if not (token.nbf <= now < token.exp):
        raise StaleAuthorizationError(
            f"{token.token_id} outside validity window at t={now:.1f}"
        )

    # 2. Authorization check: root revocation state must be fresh.
    if not view.authorization_fresh(token.root_id, now):
        # Cannot confirm root is alive within one epoch -> fail closed.
        raise StaleAuthorizationError(
            f"root {token.root_id} revocation state stale at t={now:.1f}; "
            f"last check {view.last_check.get(token.root_id)}; "
            f"epoch={view.verification_epoch}s"
        )

    # 3. Explicit revocation check against the (fresh) local set.
    if token.token_id in view.revoked:
        raise StaleAuthorizationError(
            f"{token.token_id} is revoked by root {token.root_id}"
        )


def run_work_unit(token, view, unit_fn, now):
    """Wrap a single externally-visible work unit with the boundary check."""
    try:
        verify_at_work_unit_boundary(token, view, now=now)
    except StaleAuthorizationError:
        # Halt + checkpoint; do NOT proceed and do NOT silently drop.
        raise
    return unit_fn()


# --- trace of the observed incident, now bounded ---
if __name__ == "__main__":
    view = RevocationView(verification_epoch=15.0)
    tok = CapabilityToken("T_C", root_id="A", exp=120.0, nbf=0.0)

    # t=10: A revokes T_B; B pushes to C at t=95 (the bug).
    view.record_check("A", now=5.0)  # last successful root check

    # t=25: next work-unit boundary; root check is 20s old > epoch 15s.
    try:
        run_work_unit(tok, view, unit_fn=lambda: "wrote 340 summaries", now=25.0)
    except StaleAuthorizationError as e:
        print(f"HALTED at work-unit boundary: {e}")
        # operator escalation + checkpoint of partial state
