# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-revoked-warrant-mid-tool-call-and-why-short-lived-credential-rotation-in-aaif-flows-fails-at-the-execution-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-revoked-warrant-mid-tool-call-and-why-short-lived-credential-rotation-in-aaif-flows-fails-at-the-execution-boundary.warrant.json
# Markdown SHA-256:   4ccde2454e8b9f40c94a27a6cf2fe1e8f07971749a8dde0092a88e9951b932b2
# Code AST SHA-256:   d49c98a39e5566a39a8523bd2747af10c5d2c073abff42ef28854fa97a572a6c
# Verified Classes:   RevokedWarrantEffectError, Warrant, RevocationCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class RevokedWarrantEffectError(RuntimeError):
    """Raised when an effect is about to commit under a warrant that is
    revoked, expired, or whose revocation check is staler than the
    propagation bound."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    expires_at: float
    revoked_at: float | None = None


@dataclass
class RevocationCache:
    # maps warrant_id -> revocation timestamp (authority write time)
    revoked: dict[str, float] = field(default_factory=dict)
    last_sync: float = 0.0
    propagation_bound: float = 30.0  # d_p: max staleness of this cache

    def sync(self, authority_list: dict[str, float], now: float) -> None:
        self.revoked.update(authority_list)
        self.last_sync = now

    def check_fresh(self, warrant_id: str, now: float) -> tuple[bool, float | None]:
        """Returns (is_revoked, revoked_at). Raises if cache is stale."""
        if now - self.last_sync > self.propagation_bound:
            raise RevokedWarrantEffectError(
                f"revocation cache stale: last sync {now - self.last_sync:.1f}s "
                f"ago, bound {self.propagation_bound}s"
            )
        return (warrant_id in self.revoked, self.revoked.get(warrant_id))


def commit_effect(
    warrant: Warrant,
    cache: RevocationCache,
    effect_fn,
    now: float,
    abort_token: dict,
) -> None:
    """Effect-time gate. Must be called immediately before committing any
    state mutation. Re-verifies revocation freshness on the effect path."""
    if abort_token.get("aborted"):
        raise RevokedWarrantEffectError(
            f"effect aborted by in-flight revocation for {warrant.warrant_id}"
        )
    if now >= warrant.expires_at:
        raise RevokedWarrantEffectError(
            f"warrant {warrant.warrant_id} expired at {warrant.expires_at}, "
            f"effect attempted at {now}"
        )
    is_revoked, revoked_at = cache.check_fresh(warrant.warrant_id, now)
    if is_revoked:
        raise RevokedWarrantEffectError(
            f"warrant {warrant.warrant_id} revoked at {revoked_at}, "
            f"effect attempted at {now} ({now - revoked_at:.1f}s after revocation)"
        )
    # Effect-time check passed within propagation bound; commit.
    effect_fn()


# --- Reproduction of the observed trace ---
def _trace() -> None:
    w = Warrant(warrant_id="W_sub", expires_at=120.0)
    cache = RevocationCache(propagation_bound=30.0)
    cache.sync({}, now=-30.0)  # initial sync at t=-30

    # t=5: admitted (admission-time check passed, not shown here)
    # t=41: authority revokes
    authority = {"W_sub": 41.0}
    # t=60: cache syncs
    cache.sync(authority, now=60.0)

    # t=95: effect attempts to commit
    try:
        commit_effect(w, cache, effect_fn=lambda: None, now=95.0,
                      abort_token={"aborted": True})
    except RevokedWarrantEffectError as e:
        print(f"blocked: {e}")


if __name__ == "__main__":
    _trace()
