# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-a-hierarchical-summary-and-evicts-the-wrong-stratum-under-a-lossy-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-a-hierarchical-summary-and-evicts-the-wrong-stratum-under-a-lossy-budget.warrant.json
# Markdown SHA-256:   ad0adf63c156e2e6724331d0ede76e83da22fdba5b2c7bc33a6f3fa077a8bd77
# Code AST SHA-256:   afd74e4e6b667f63666ccf8ec2d9c13335e7fccabcffcd2bdea26ce9f2c14643
# Verified Classes:   CheckpointUnreachable, EvictionOrphansHandle, Stratum
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CheckpointUnreachable(RuntimeError):
    """Raised when a resume is attempted against a token no surviving stratum preserves verbatim."""


class EvictionOrphansHandle(RuntimeError):
    """Raised when a candidate eviction set would orphan a dereferenceable token."""


@dataclass
class Stratum:
    id: str
    tokens: int
    # tokens this stratum introduces and preserves VERBATIM (dereferenceable later)
    preserves: set[str] = field(default_factory=set)
    # tokens this stratum merely paraphrases (NOT safely dereferenceable)
    paraphrases: set[str] = field(default_factory=set)


def plan_eviction(strata: list[Stratum], must_reclaim: int) -> list[str]:
    """Return stratum ids to evict, honoring token-closure pinning over weight."""
    # closure of tokens that some stratum preserves verbatim
    survivors_closure: set[str] = set()
    for s in strata:
        survivors_closure |= s.preserves

    evict: list[str] = []
    reclaimed = 0
    # weight-first, but skip any stratum that is a sole verbatim carrier
    for s in sorted(strata, key=lambda x: x.tokens):
        if reclaimed >= must_reclaim:
            break
        orphans = {
            t for t in s.preserves
            if not any(t in o.preserves for o in strata if o.id != s.id)
        }
        if orphans:
            # pinning rule dominates weight rule
            continue
        evict.append(s.id)
        reclaimed += s.tokens

    if reclaimed < must_reclaim:
        # cannot satisfy budget without orphaning a handle -> forced distillation required
        blocked = [
            t for s in strata
            for t in s.preserves
            if not any(t in o.preserves for o in strata if o.id != s.id)
        ]
        if blocked:
            raise EvictionOrphansHandle(
                f"budget short by {must_reclaim - reclaimed} tokens; "
                f"cannot evict without orphaning handles {sorted(blocked)}; "
                f"rewrite these verbatim into a pinned depth-1 digest first"
            )
    return evict


def resume_from_checkpoint(strata: Iterable[Stratum], checkpoint_id: str) -> str:
    reachable = any(checkpoint_id in s.preserves for s in strata)
    if not reachable:
        # do NOT reconstruct from paraphrase prose
        raise CheckpointUnreachable(
            f"checkpoint_id {checkpoint_id!r} absent from all surviving strata' "
            f"verbatim-preservation sets; refusing to reconstruct"
        )
    return checkpoint_id
