# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-delegated-capability-revocation-that-arrives-mid-tool-call-the-attenuated-credential-staleness-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-delegated-capability-revocation-that-arrives-mid-tool-call-the-attenuated-credential-staleness-window.warrant.json
# Markdown SHA-256:   707ec50cfa99b4bb366ec674bad4bc18b2a2e1cdf3da1e3a4ffb9a52a770aa4e
# Code AST SHA-256:   65575246883554a3f007ecfbd79a60f87a5e9827f5bfd1a6c5e272ee1cc0fe1b
# Verified Classes:   StaleAuthorityCommit, Warrant, RevocationLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class StaleAuthorityCommit(RuntimeError):
    """Raised when an effect would commit under a warrant revoked before commit."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    root_epoch: int          # epoch of the root authority at issuance
    path_hash: str           # hash of the attenuation chain O->W->S
    expires_at: float
    scope: str


@dataclass
class RevocationLedger:
    """Monotonic revocation set keyed by path_hash, versioned by epoch."""
    epoch: int = 0
    revoked_paths: dict = field(default_factory=dict)  # path_hash -> revoked_at_epoch

    def revoke(self, path_hash: str) -> int:
        self.epoch += 1
        self.revoked_paths[path_hash] = self.epoch
        return self.epoch

    def is_revoked(self, path_hash: str) -> bool:
        return path_hash in self.revoked_paths


def admit(w: Warrant, ledger: RevocationLedger, now: float) -> None:
    """Admission-time check. Necessary but NOT sufficient for commit safety."""
    if now >= w.expires_at:
        raise StaleAuthorityCommit(f"warrant {w.warrant_id} expired at admission")
    if ledger.is_revoked(w.path_hash):
        raise StaleAuthorityCommit(f"warrant {w.warrant_id} already revoked at admission")


def commit_with_fence(
    w: Warrant,
    ledger: RevocationLedger,
    tool_latency_p99: float,
    max_staleness: float,
    now: float,
) -> None:
    """
    Commit-time fence. Must be called at the durable-commit point, AFTER the
    tool's side effect is staged but BEFORE it becomes durable.
    """
    # Guard 1: transitive revocation must be checked against the ROOT epoch at commit.
    if ledger.is_revoked(w.path_hash):
        revoked_at = ledger.revoked_paths[w.path_hash]
        # If revocation epoch is strictly greater than the warrant's root epoch,
        # the warrant was issued under authority that has since been revoked.
        if revoked_at > w.root_epoch:
            raise StaleAuthorityCommit(
                f"warrant {w.warrant_id} revoked at epoch {revoked_at} "
                f"> root_epoch {w.root_epoch}; refusing commit"
            )

    # Guard 2: if the call's latency tail can straddle the staleness budget,
    # admission-time trust is inadmissible; require an explicit live confirmation.
    if tool_latency_p99 > max_staleness:
        # In a real system this would be a live epoch read from the authority.
        live_epoch = ledger.epoch
        if live_epoch != w.root_epoch and ledger.is_revoked(w.path_hash):
            raise StaleAuthorityCommit(
                f"warrant {w.warrant_id}: latency tail {tool_latency_p99}ms "
                f"exceeds staleness budget {max_staleness}ms and authority advanced"
            )


def execute_tool_call(
    w: Warrant,
    ledger: RevocationLedger,
    tool_latency_p99: float,
    max_staleness: float,
) -> str:
    now = time.monotonic()
    admit(w, ledger, now)  # decision clock

    # ... tool executes here; revocation may land during this window ...
    # Simulate the revocation-during-flight interleaving:
    ledger.revoke(w.path_hash)

    # effect clock: fence at commit
    commit_with_fence(w, ledger, tool_latency_p99, max_staleness, time.monotonic())
    return "committed"


if __name__ == "__main__":
    ledger = RevocationLedger(epoch=41)
    w = Warrant(
        warrant_id="w_S",
        root_epoch=41,
        path_hash="O>W>S",
        expires_at=time.monotonic() + 60,
        scope="write:/tmp/job7/r",
    )
    try:
        # latency tail 3000ms > staleness budget 1000ms -> fence must catch it
        execute_tool_call(w, ledger, tool_latency_p99=3000.0, max_staleness=1000.0)
    except StaleAuthorityCommit as e:
        print(f"BLOCKED: {e}")
