# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-lossy-summarization-fidelity-floor-and-the-rehydration-orphan-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-lossy-summarization-fidelity-floor-and-the-rehydration-orphan-boundary.warrant.json
# Markdown SHA-256:   db2eb15e154c84aebb90776f7f693cf7467e18e0ec00173c9d3043dfd3c0d9b7
# Code AST SHA-256:   5a865dabc7eda335a92255a7af4334bd6de49cc7f03e34fd9366d4ad6e23a482
# Verified Classes:   UnrehydratableCompactionError, Span, RehydrationIndex
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable, Optional


class UnrehydratableCompactionError(RuntimeError):
    """Raised when a compaction would evict a literal-bearing span that the
    instance cannot re-fetch using a summary-derivable key. Refusing here is
    the correct behavior: it converts silent corruption into a loud, recoverable
    budget failure."""
    pass


# Literal classes that are load-bearing and must survive the boundary verbatim
# or remain rehydratable. Narrative classes may be lossily summarized.
LOAD_BEARING_MARKERS = (
    "region", "zone", "hash", "sha", "id", "token", "threshold",
    "must not", "do not", "only if", "unless", "==", "!=",
)


@dataclass
class Span:
    step_index: int
    text: str
    content_hash: str = field(init=False)

    def __post_init__(self):
        self.content_hash = hashlib.sha256(self.text.encode()).hexdigest()[:16]

    def load_bearing_literals(self) -> list[str]:
        lowered = self.text.lower()
        return [m for m in LOAD_BEARING_MARKERS if m in lowered]


@dataclass
class RehydrationIndex:
    # Keyed by stable identifiers that survive summarization: step index,
    # content hash, and any literal the summary is forbidden to paraphrase.
    store: dict[str, Span] = field(default_factory=dict)

    def register(self, span: Span, keys: list[str]) -> None:
        for k in keys:
            self.store[k] = span

    def resolve(self, query_key: str) -> Optional[Span]:
        return self.store.get(query_key)


def compact_span(
    span: Span,
    summary_tokens_available: int,
    summarize: Callable[[Span, int], str],
    index: RehydrationIndex,
    summary_derivable_keys: list[str],
) -> str:
    """Two-phase commit: prove rehydratability BEFORE eviction commits.

    summary_derivable_keys are the keys the instance could construct from the
    summary text alone. If a load-bearing literal exists and none of these
    keys resolves back to the original span, the eviction is refused.
    """
    literals = span.load_bearing_literals()

    if literals:
        # Phase 2: prove we can get the span back from a summary-derivable key.
        rehydratable = any(
            (resolved := index.resolve(k)) is not None
            and resolved.content_hash == span.content_hash
            for k in summary_derivable_keys
        )
        if not rehydratable:
            # The span is an orphan: present in principle, unreachable by query.
            # Refuse to compact. Caller must pin the span or checkpoint verbatim.
            raise UnrehydratableCompactionError(
                f"step {span.step_index} carries load-bearing literals {literals} "
                f"but no summary-derivable rehydration key resolves to "
                f"hash={span.content_hash}; refusing lossy compaction."
            )

    # Narrative-only, or proven rehydratable: safe to summarize and evict.
    summary = summarize(span, summary_tokens_available)
    return summary


def run_compaction_cycle(
    spans: list[Span],
    budget: int,
    summarize: Callable[[Span, int], str],
    index: RehydrationIndex,
    keys_for: Callable[[Span], list[str]],
) -> list[str]:
    summaries = []
    for span in spans:
        try:
            summaries.append(compact_span(span, budget, summarize, index, keys_for(span)))
        except UnrehydratableCompactionError:
            # Surface as a budget-pressure signal, not silent corruption.
            # The span stays resident; narrative elsewhere must yield instead.
            raise
    return summaries
