# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-hierarchical-compaction-as-a-lossy-transform-and-gate-its-own-continuation-on-retrieval-verifiable-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-hierarchical-compaction-as-a-lossy-transform-and-gate-its-own-continuation-on-retrieval-verifiable-eviction.warrant.json
# Markdown SHA-256:   60ad391540125ad72c77caf6068f3620bf81a8279d26ae1edc9e756dc0bbce48
# Code AST SHA-256:   e2bef62a69fe2536c52ef2d1e7991026b4827e0f554940d283459f6bfbaf165a
# Verified Classes:   CompactionAuthorizationError, ActionClass, FactSource, PendingAction
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class CompactionAuthorizationError(RuntimeError):
    """Raised when an irreversible action is authorized by a summary instead of a raw span."""


class ActionClass(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"


class FactSource(Enum):
    SUMMARY = "summary"
    RAW_SPAN = "raw_span"
    UNVERIFIED = "unverified"


@dataclass(frozen=True)
class PendingAction:
    name: str
    action_class: ActionClass
    depends_on_epoch: int          # compaction epoch the fact predates
    current_epoch: int
    fact_source: FactSource
    span_id: str | None            # pinned handle, present only if retrieved


def authorize(action: PendingAction) -> None:
    stale = action.depends_on_epoch < action.current_epoch

    if action.action_class is ActionClass.REVERSIBLE:
        return  # summary-level belief is acceptable for reversible work

    # Irreversible: summary authorization is a category error.
    if action.fact_source is FactSource.SUMMARY:
        raise CompactionAuthorizationError(
            f"action '{action.name}' is irreversible but authorized by a "
            f"summary at epoch {action.current_epoch}; fact predates epoch "
            f"{action.depends_on_epoch}. Retrieve the raw span before commit."
        )

    if stale and action.fact_source is not FactSource.RAW_SPAN:
        raise CompactionAuthorizationError(
            f"action '{action.name}' depends on a pre-epoch fact with no "
            f"verified raw-span retrieval (source={action.fact_source.value}); "
            f"falling back to summary is forbidden."
        )

    if action.fact_source is FactSource.RAW_SPAN and not action.span_id:
        raise CompactionAuthorizationError(
            f"action '{action.name}' claims raw-span provenance but carries no "
            f"pinned span_id; retrieval cannot be replay-verified."
        )


# Failure trace from the record: retry policy lost its negation across two
# summarization levels, so the agent retried an endpoint that said NOT to.
try:
    authorize(PendingAction(
        name="retry_upstream_429",
        action_class=ActionClass.IRREVERSIBLE,
        depends_on_epoch=0,
        current_epoch=2,
        fact_source=FactSource.SUMMARY,
        span_id=None,
    ))
except CompactionAuthorizationError as e:
    # Conservative branch: do not retry; re-fetch ground truth or escalate.
    print(f"BLOCKED: {e}")
