# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revocation-warrant-arrives-mid-handoff-across-a-federated-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revocation-warrant-arrives-mid-handoff-across-a-federated-trust-boundary.warrant.json
# Markdown SHA-256:   9068c0e1a9d3be22fc526abbe065cd26871fb6c239d1b8d6c27668dcac9a2086
# Code AST SHA-256:   b69ad7ce74744cd759bfb2c371f7510e2852804cbb51def3936de68bfeb5a768
# Verified Classes:   RevocationPropagationError, WarrantState, WarrantView, Checkpoint
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class RevocationPropagationError(RuntimeError):
    """Raised when an instance attempts to advance or resume under authority
    that has been revoked at origin but not yet reconciled at the verifier."""


class WarrantState(Enum):
    VALID = "valid"
    REVOKED = "revoked"
    UNVERIFIABLE = "unverifiable"  # origin unreachable; NOT the same as revoked


@dataclass(frozen=True)
class WarrantView:
    warrant_id: str
    state: WarrantState
    observed_epoch: int          # origin revocation-list version at last check
    last_checked_at: float


@dataclass
class Checkpoint:
    warrant_id: str
    step_id: str
    authority_epoch: int         # epoch under which contents were produced
    produced_under_revoked_authority: bool = False
    payload: dict = field(default_factory=dict)


def may_initiate_step(view: WarrantView, step_requires_capability: bool) -> bool:
    """Prospective gate: revocation forbids NEW capability-bearing steps."""
    if not step_requires_capability:
        return True
    if view.state is WarrantState.REVOKED:
        return False
    if view.state is WarrantState.UNVERIFIABLE:
        # Fail-closed on new privileged work, but do not claim revocation.
        return False
    return True


def resume_checkpoint(cp: Checkpoint, view: WarrantView) -> Checkpoint:
    """Resume must re-validate against origin epoch, not the checkpoint snapshot."""
    if cp.warrant_id != view.warrant_id:
        raise RevocationPropagationError(
            f"checkpoint warrant {cp.warrant_id!r} != view warrant {view.warrant_id!r}"
        )
    if view.state is WarrantState.REVOKED:
        if cp.authority_epoch < view.observed_epoch:
            # Stale authority: quarantine, do not replay. Prevents step-5 double-write.
            raise RevocationPropagationError(
                f"refusing to resume checkpoint {cp.step_id!r}: produced at epoch "
                f"{cp.authority_epoch} but warrant revoked at epoch {view.observed_epoch}"
            )
        cp.produced_under_revoked_authority = True
        return cp
    if view.state is WarrantState.UNVERIFIABLE:
        raise RevocationPropagationError(
            f"cannot resume {cp.step_id!r}: warrant unverifiable, refusing to extend authority"
        )
    return cp


def commit_side_effect(
    cp: Checkpoint,
    view: WarrantView,
    committed_keys: set[tuple[str, str, int]],
) -> tuple[str, str, int]:
    """Idempotency key binds (warrant, step, epoch) so a stale-epoch retry collides."""
    key = (cp.warrant_id, cp.step_id, cp.authority_epoch)
    if key in committed_keys:
        raise RevocationPropagationError(
            f"duplicate side effect for {key}: stale-epoch replay rejected"
        )
    if view.state is WarrantState.REVOKED and cp.authority_epoch < view.observed_epoch:
        raise RevocationPropagationError(
            f"side effect for {cp.step_id!r} would commit under revoked authority"
        )
    committed_keys.add(key)
    return key
