# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-prove-that-compaction-is-reversible-before-it-may-drop-the-original-turns.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-prove-that-compaction-is-reversible-before-it-may-drop-the-original-turns.warrant.json
# Markdown SHA-256:   d54caae25670fc35d6d7c228c6c7b264037a9700634e563904d6605fd1d944f8
# Code AST SHA-256:   60e6e4dca90ad4f322ae09b92c58f27f6e07fa81cace48040ff2b7fed6a73900
# Verified Classes:   CompactionReversibilityError, Span, Summary, Index
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionReversibilityError(RuntimeError):
    """Raised when an eviction set cannot be restored through the retrieval interface."""


@dataclass
class Span:
    span_id: str
    text: str
    structured: bool  # machine-generated artifact: schema dump, stack trace, exact diff, etc.


@dataclass
class Summary:
    text: str
    keys: dict[str, str] = field(default_factory=dict)  # key -> span_id


@dataclass
class Index:
    # similarity pool: query -> ranked span_ids (summary chunks included here)
    ranked: dict[str, list[str]] = field(default_factory=dict)
    # direct fetch table: span_id -> Span (budget-exempt pointer resolution)
    fetch: dict[str, Span] = field(default_factory=dict)
    # provenance: span_id -> "summary" | "raw"
    provenance: dict[str, str] = field(default_factory=dict)

    def resolve_key(self, key: str, summary: Summary) -> Span:
        span_id = summary.keys.get(key)
        if span_id is None:
            raise CompactionReversibilityError(f"summary names no span for key {key!r}")
        span = self.fetch.get(span_id)
        if span is None:
            raise CompactionReversibilityError(
                f"key {key!r} -> span {span_id!r} not fetchable (pointer resolution is budget-exempt)"
            )
        if self.provenance.get(span_id) != "raw":
            raise CompactionReversibilityError(
                f"key {key!r} resolves to {self.provenance.get(span_id)!r} provenance; "
                f"a summary must not shadow its own source"
            )
        return span


def assert_reversible(evicted: Iterable[Span], summary: Summary, index: Index, top_k: int = 3) -> None:
    """
    Invariant: every decision-bearing evicted span is reachable via a distinctive key,
    through a summary-excluding pool, under a budget-exempt fetch.
    """
    for span in evicted:
        if not span.structured:
            continue  # display-bearing: plain summary is legal
        # Condition 1: a key must exist for this span and be distinctive in the summary.
        matching = [k for k, sid in summary.keys.items() if sid == span.span_id]
        if not matching:
            raise CompactionReversibilityError(
                f"decision-bearing span {span.span_id!r} evicted without a retrieval key"
            )
        for key in matching:
            # Condition 2 + 3: resolve key; resolution must not depend on top-k ranking.
            resolved = index.resolve_key(key, summary)
            if resolved.span_id != span.span_id:
                raise CompactionReversibilityError(
                    f"key {key!r} resolves to {resolved.span_id!r}, not {span.span_id!r}"
                )
            # Verify the key is not shadowed: the raw span must outrank its own summary
            # for a query in the summary register, or the fetch must bypass ranking entirely.
            hits = index.ranked.get(key, [])
            if hits and hits[0] != span.span_id and index.provenance.get(hits[0]) == "summary":
                raise CompactionReversibilityError(
                    f"key {key!r} is shadowed by summary chunk {hits[0]!r} in the ranked pool"
                )


def compact(evicted: list[Span], summary: Summary, index: Index) -> Summary:
    try:
        assert_reversible(evicted, summary, index)
    except CompactionReversibilityError:
        # Refuse the eviction: keep decision-bearing spans in context rather than
        # commit a silently-contaminated state transition.
        raise
    return summary
