# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-a-delegated-warrant-whose-revocation-arrives-after-the-sub-agent-has-already-committed-its-first-side-effecting-tool-cal.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-a-delegated-warrant-whose-revocation-arrives-after-the-sub-agent-has-already-committed-its-first-side-effecting-tool-cal.warrant.json
# Markdown SHA-256:   b5b62767d711372a20b221254819072bf8966bd8961f2820b4cc79e1f1251af9
# Code AST SHA-256:   6f4f6e6288faf6354af7aa8fd9b0b3487dcd77df5a7ebbb693f8e0ae07d73c4e
# Verified Classes:   WarrantState, StalePositiveCommitError, RevocationFence, CachedWarrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum


class WarrantState(Enum):
    VALID = "valid"
    REVOKED = "revoked"
    UNKNOWN = "unknown"


class StalePositiveCommitError(RuntimeError):
    """Raised when a non-idempotent side effect is about to commit under a
    cached authorization whose revocation state cannot be fenced."""


@dataclass
class RevocationFence:
    warrant_id: str
    tool_call_id: str
    issued_at: datetime
    expires_at: datetime
    issuer_domain: str


@dataclass
class CachedWarrant:
    warrant_id: str
    state: WarrantState
    cached_at: datetime
    poll_interval: timedelta


def commit_side_effect(
    warrant: CachedWarrant,
    tool_call_id: str,
    idempotent: bool,
    fence: RevocationFence | None,
    now: datetime,
) -> None:
    if warrant.state is WarrantState.REVOKED:
        raise StalePositiveCommitError(
            f"warrant {warrant.warrant_id} revoked; refusing commit of {tool_call_id}"
        )

    if idempotent:
        # Compensable: allow cached authorization, but the audit record must
        # carry the cache timestamp so replay can detect the stale window.
        return

    if fence is None:
        raise StalePositiveCommitError(
            f"non-idempotent commit {tool_call_id} under cached warrant "
            f"{warrant.warrant_id} cached_at={warrant.cached_at.isoformat()} "
            f"requires a revocation fence from the issuer; none supplied"
        )

    if fence.warrant_id != warrant.warrant_id or fence.tool_call_id != tool_call_id:
        raise StalePositiveCommitError(
            f"fence {fence.warrant_id}/{fence.tool_call_id} does not bind to "
            f"commit {warrant.warrant_id}/{tool_call_id}"
        )

    if now >= fence.expires_at:
        raise StalePositiveCommitError(
            f"fence for {tool_call_id} expired at {fence.expires_at.isoformat()}; "
            f"re-fence or abort"
        )

    if now - warrant.cached_at > warrant.poll_interval:
        raise StalePositiveCommitError(
            f"cached warrant {warrant.warrant_id} is older than poll interval; "
            f"state may be stale-positive"
        )
