# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-with-a-lossy-summarizer-and-trusts-the-summary-as-a-retrieval-key.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-with-a-lossy-summarizer-and-trusts-the-summary-as-a-retrieval-key.warrant.json
# Markdown SHA-256:   59ebbc6bd4ebbbf04294c594bd9c443aad1ceac83dc632f60771a67433119398
# Code AST SHA-256:   693fb4266c9e53de83dac8998c0ac6fab71089f0bdd6f31b87bbb75889e8c3a8
# Verified Classes:   ReconstructionKeyLossError, PinnedKeySet
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ReconstructionKeyLossError(RuntimeError):
    """Raised when a compacted block cannot index a fact it replaced."""


@dataclass
class PinnedKeySet:
    identifiers: set[str] = field(default_factory=set)
    numerics: set[str] = field(default_factory=set)
    polarities: set[str] = field(default_factory=set)

    def covers(self, key: str) -> bool:
        return (
            key in self.identifiers
            or key in self.numerics
            or key in self.polarities
        )


def compact_with_index(source_turns: list[str], summarizer) -> tuple[str, PinnedKeySet]:
    """Summarize, but pin every reconstruction key outside rewrite scope."""
    pinned = extract_keys(source_turns)  # identifiers, exact numerics, polarity
    summary = summarizer(source_turns)   # lossy, paraphrasing, untrusted for index
    return summary, pinned


def reconstruct(summary: str, pinned: PinnedKeySet, need: str, retrieve) -> str:
    """Retrieve the source fact behind `need`, or fail loudly."""
    if not pinned.covers(need):
        # The summary paraphrased away the only handle to this fact.
        raise ReconstructionKeyLossError(
            f"key {need!r} was elided during compaction; "
            f"summary cannot index its source. Refusing to fall through "
            f"to a semantically-similar default."
        )
    hits = retrieve(need)
    if not hits:
        raise ReconstructionKeyLossError(
            f"pinned key {need!r} returned no source above threshold; "
            f"treating as unreconstructable rather than approximating."
        )
    return hits[0]


def assert_index_parity(pinned: PinnedKeySet, summary: str) -> None:
    """Mechanical coverage check — the summarizer does not grade itself."""
    missing = [k for k in pinned.identifiers | pinned.numerics if k not in summary]
    if missing:
        # Keys must survive into the carry-forward footer verbatim.
        raise ReconstructionKeyLossError(
            f"compaction dropped pinned keys {missing!r} from carry-forward block"
        )
