# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-authenticate-when-its-revocation-epoch-advances-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-authenticate-when-its-revocation-epoch-advances-mid-tool-call.warrant.json
# Markdown SHA-256:   42559559efda37257217a30e72bf98fd83e6593b091a14467af26675f0d554d3
# Code AST SHA-256:   bd5d94c55eb13cde15175ad7cb333fd5c4cf5eab669b7d3d9589bc206a172059
# Verified Classes:   EpochStalenessError, Warrant, AuthorityView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class EpochStalenessError(RuntimeError):
    """Raised when a warrant's epoch is older than the authority's current epoch
    at a point where the caller is about to commit a non-idempotent side effect."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    epoch: int
    expires_at: float
    scopes: frozenset
    revocable_deferred: bool = False


@dataclass(frozen=True)
class AuthorityView:
    current_epoch: int
    observed_at: float


def verify_at_commit(
    warrant: Warrant,
    dispatch_epoch: int,
    authority: AuthorityView,
    tool_is_idempotent: bool,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    if now >= warrant.expires_at:
        raise EpochStalenessError(
            f"warrant for {warrant.subject} expired at {warrant.expires_at}, now {now}"
        )

    if warrant.epoch < authority.current_epoch:
        # The warrant itself is older than the authority's view. This is the
        # direct case: the warrant was issued before the current epoch.
        raise EpochStalenessError(
            f"warrant epoch {warrant.epoch} < authority epoch "
            f"{authority.current_epoch} for {warrant.subject}"
        )

    if authority.current_epoch > dispatch_epoch and not tool_is_idempotent:
        # The epoch advanced between dispatch and commit. If the tool is not
        # idempotent and the warrant is not revocable_deferred, the commit is
        # a stale-snapshot commit and must be rejected.
        if not warrant.revocable_deferred:
            raise EpochStalenessError(
                f"epoch advanced {dispatch_epoch}->{authority.current_epoch} "
                f"mid-flight for {warrant.subject}; non-idempotent commit rejected"
            )
        # revocable_deferred: caller must stage, not commit, and re-check.
        raise EpochStalenessError(
            f"epoch advanced mid-flight for {warrant.subject}; "
            f"revocable_deferred commit must be staged and re-verified"
        )


def commit_side_effect(
    warrant: Warrant,
    dispatch_epoch: int,
    authority: AuthorityView,
    tool_is_idempotent: bool,
    apply_fn,
) -> None:
    verify_at_commit(warrant, dispatch_epoch, authority, tool_is_idempotent)
    apply_fn()
