# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-healed-partition-as-an-untrusted-identity-epoch-rather-than-a-resumable-session.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-healed-partition-as-an-untrusted-identity-epoch-rather-than-a-resumable-session.warrant.json
# Markdown SHA-256:   ea15e61cfb42ae6a583e5ebad64ca860eb61716a500f9f2d9bcd91ab44f5da1e
# Code AST SHA-256:   a24270ccad312495379d7d9a7de62fbec1ed5ff94e0537cf03026ee601a77f70
# Verified Classes:   RevocationUnconfirmedError, WarrantState, Warrant, Instance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class RevocationUnconfirmedError(RuntimeError):
    """Raised when a side-effecting action is attempted under a warrant whose
    revocation status cannot be confirmed against an authoritative source
    after a partition heal. Fail-closed: the action must not execute."""


class WarrantState(Enum):
    CONFIRMED = "confirmed"      # revocation status re-derived, current epoch
    STALE = "stale"              # cached across a partition, unconfirmed
    REVOKED = "revoked"          # authoritative source says revoked


@dataclass
class Warrant:
    warrant_id: str
    confirmed_epoch: int
    state: WarrantState = WarrantState.STALE
    revoked: bool = False


@dataclass
class Instance:
    epoch: int = 0
    warrants: Dict[str, Warrant] = field(default_factory=dict)
    authoritative_reachable: bool = True

    def on_partition_heal(self) -> None:
        """Advance identity epoch. All cached warrants become stale; none may
        authorize side effects until re-confirmed against the authority."""
        self.epoch += 1
        for w in self.warrants.values():
            if w.confirmed_epoch < self.epoch:
                w.state = WarrantState.STALE

    def confirm_warrant(self, warrant_id: str, revoked: bool) -> None:
        w = self.warrants[warrant_id]
        w.revoked = revoked
        w.confirmed_epoch = self.epoch
        w.state = WarrantState.REVOKED if revoked else WarrantState.CONFIRMED

    def authorize(self, warrant_id: str, side_effecting: bool) -> None:
        w = self.warrants[warrant_id]
        if w.state is WarrantState.REVOKED:
            raise RevocationUnconfirmedError(
                f"warrant {warrant_id} is revoked; action denied"
            )
        if side_effecting and w.state is WarrantState.STALE:
            raise RevocationUnconfirmedError(
                f"warrant {warrant_id} cached across partition (epoch "
                f"{w.confirmed_epoch} < {self.epoch}); authoritative source "
                f"reachable={self.authoritative_reachable}. Side-effecting "
                f"action blocked until revocation status re-confirmed."
            )
        # read-only / idempotent under stale is permitted (degraded-authority)
        return None


def resume_task(inst: Instance, warrant_id: str, side_effecting: bool) -> None:
    # Partition healed: session may resume, authority may NOT be assumed.
    inst.on_partition_heal()
    if inst.authoritative_reachable:
        # re-derive from the authoritative side before proceeding
        inst.confirm_warrant(warrant_id, revoked=False)
    inst.authorize(warrant_id, side_effecting=side_effecting)
