# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-auto-compaction-has-silently-orphaned-a-live-referent-the-dangling-handle-invariant-in-lossy-but-auditable-su.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-auto-compaction-has-silently-orphaned-a-live-referent-the-dangling-handle-invariant-in-lossy-but-auditable-su.warrant.json
# Markdown SHA-256:   a1d07c8eb017da20f3d5dc944153b40749b003437d2beddf02eb650866fa19bf
# Code AST SHA-256:   eff43d6bbd2bc0c2c4e0f1793f30fb3a20f42cdd12d92db1da7292df2e105e46
# Verified Classes:   ReferentClass, DanglingHandleError, RetainedPointer, CompactionSummary
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class ReferentClass(Enum):
    SELF_VALIDATING = "self_validating"   # content hash, committed SHA, closed receipt
    FINITE_LIFETIME = "finite_lifetime"   # pid, session token, signed URL, lease
    UNPROBEABLE = "unprobeable"           # referent's observer was itself evicted


class DanglingHandleError(RuntimeError):
    """Raised when a compaction summary retains a pointer whose referent
    cannot be proven live from retained state alone."""


@dataclass
class RetainedPointer:
    handle: str
    cls: ReferentClass
    issued_at: float
    expires_at: Optional[float] = None      # required for FINITE_LIFETIME
    liveness_probe: Optional[str] = None    # required for FINITE_LIFETIME
    source_span: str = ""                   # audit pointer into evicted region


@dataclass
class CompactionSummary:
    pointers: list = field(default_factory=list)
    raw_span_recoverable: bool = True       # false after the span is itself evicted


def validate_compaction(summary: CompactionSummary, now: float) -> None:
    """Enforce the dangling-handle invariant at compaction time.

    Every retained pointer must be decidable from retained state alone.
    Violations must be reified or dropped BEFORE the raw span is evicted,
    because after eviction they are unrecoverable.
    """
    for p in summary.pointers:
        if p.cls is ReferentClass.SELF_VALIDATING:
            continue  # immutable referent; failure at deref is terminal, not retryable

        if p.cls is ReferentClass.UNPROBEABLE:
            raise DanglingHandleError(
                f"pointer {p.handle!r} (span {p.source_span}) has no post-compaction "
                f"observer; obligation must be re-expressed as a fresh task, not retained"
            )

        # FINITE_LIFETIME: must carry expiry + probe, or it is undecidable later
        if p.expires_at is None or p.liveness_probe is None:
            if not summary.raw_span_recoverable:
                raise DanglingHandleError(
                    f"pointer {p.handle!r} (span {p.source_span}) lacks expiry/probe "
                    f"metadata and its raw span is already evicted; referent is orphaned"
                )
            raise DanglingHandleError(
                f"pointer {p.handle!r} (span {p.source_span}) is undecidable post-compaction: "
                f"reify with {{expires_at, liveness_probe}} while span is still recoverable"
            )

        if now >= p.expires_at:
            raise DanglingHandleError(
                f"pointer {p.handle!r} expired at {p.expires_at} (now {now}); "
                f"re-acquire referent rather than retaining the stale handle"
            )


def dereference(p: RetainedPointer, probe_result: Optional[bool], now: float) -> str:
    """Resolve a retained pointer at use time, with class-correct retry policy."""
    if p.cls is ReferentClass.SELF_VALIDATING:
        if probe_result is False:
            # terminal: content changed or vanished; re-derive, do NOT retry
            raise DanglingHandleError(
                f"self-validating handle {p.handle!r} failed probe; "
                f"referent is gone or mutated — re-derive from source"
            )
        return "live"

    if p.expires_at is not None and now >= p.expires_at:
        raise DanglingHandleError(
            f"handle {p.handle!r} expired; re-acquire before use, retry is invalid"
        )

    if probe_result is False:
        # finite-lifetime referent died before expiry: obligation may still be live
        raise DanglingHandleError(
            f"handle {p.handle!r} (pid/session) is dead but obligation may persist; "
            f"do NOT retry the handle — discharge the underlying obligation separately"
        )
    return "live"
