# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-hierarchical-summarization-loss-budgets-and-the-irreversible-eviction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-hierarchical-summarization-loss-budgets-and-the-irreversible-eviction-boundary.warrant.json
# Markdown SHA-256:   1913d2de2634b17e0dbec72763a9b113f735325fbb5782ba760d2a6ff9a7abd3
# Code AST SHA-256:   02e2b04f2dd5d6962e7f513255941e950788ade14bf5606923b540ef59be733f
# Verified Classes:   CompactionRefused, TokenClass, Span, StructuredStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CompactionRefused(RuntimeError):
    """Raised when a span carries unmirrored non-compactable state and must not be summarized."""
    pass


class TokenClass(Enum):
    EXACT_IDENTITY = "exact_identity"   # IDs, hashes, keys, amounts
    NEGATION = "negation"               # do not / never / unless / except
    QUALIFIER = "qualifier"             # units, ordering, quantifier scope


@dataclass
class Span:
    text: str
    tokens: dict[TokenClass, list[str]] = field(default_factory=dict)


@dataclass
class StructuredStore:
    """Verbatim, out-of-band copy that survives every compaction tier."""
    mirrored: set[str] = field(default_factory=set)

    def has(self, token: str) -> bool:
        return token in self.mirrored

    def mirror(self, tokens: list[str]) -> None:
        self.mirrored.update(tokens)


def compact_span(span: Span, store: StructuredStore, *, allow_extraction: bool = True) -> str:
    """
    Enforce the irreversible-eviction invariant before summarizing.

    Admissible iff every non-compactable token in the span is already mirrored
    into the structured store (recoverable_after holds). Otherwise: extract-then-compact,
    or refuse. Never summarize a span whose load-bearing tokens have no surviving copy.
    """
    unmirrored: list[str] = []
    for cls, toks in span.tokens.items():
        for tok in toks:
            if not store.has(tok):
                unmirrored.append(f"{cls.value}:{tok}")

    if not unmirrored:
        return _summarize(span)  # safe: all load-bearing state survives out-of-band

    if allow_extraction:
        # Deterministic mirror pass — NOT a summarization. Verbatim copy into the store.
        store.mirror([t.split(":", 1)[1] for t in unmirrored])
        return _summarize(span)

    # No extraction budget and unmirrored load-bearing state: refuse rather than destroy.
    raise CompactionRefused(
        "refusing to compact span: unmirrored non-compactable state "
        f"{unmirrored!r} would be irreversibly evicted with no post-hoc detector. "
        "Extract to structured store or pin the span verbatim."
    )


def _summarize(span: Span) -> str:
    # Placeholder for the hierarchical summarizer call.
    return f"[summary of {len(span.text)} chars]"
