# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-hierarchical-summary-whose-eviction-set-is-not-retrieval-reconstructable.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-hierarchical-summary-whose-eviction-set-is-not-retrieval-reconstructable.warrant.json
# Markdown SHA-256:   12f72bb5d85c0333c99ee1a5b1577ac0df8ce78083db1fb95a02b375c0cac57b
# Code AST SHA-256:   71bcb3561333a0642f387d7b4b4de205947aabac50be1f1c8ef278bbc802e72e
# Verified Classes:   UnreconstructableEvictionError, Summary, RetrievalProbe
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnreconstructableEvictionError(RuntimeError):
    """Raised when a compaction pass would evict spans whose summary
    cannot generate a retrieval query resolving to a non-summary span."""


@dataclass
class Summary:
    text: str
    anchors: list[str]          # identifiers, versions, timestamps preserved verbatim
    load_bearing_claims: list[str]


@dataclass
class RetrievalProbe:
    query: str
    resolved_span_id: Optional[str]
    resolved_is_summary_echo: bool


def probe_reconstruction(summary: Summary, retrieval) -> list[RetrievalProbe]:
    probes: list[RetrievalProbe] = []
    for claim in summary.load_bearing_claims:
        query = build_query(claim, summary.anchors)
        hit = retrieval.get(query)
        probes.append(
            RetrievalProbe(
                query=query,
                resolved_span_id=hit.span_id if hit else None,
                resolved_is_summary_echo=bool(hit and hit.is_summary_echo),
            )
        )
    return probes


def commit_eviction(summary: Summary, retrieval, backing_retention_ok: bool) -> None:
    if not backing_retention_ok:
        raise UnreconstructableEvictionError(
            "backing store retention is not coupled to agent lifetime; "
            "evicted spans may be swept independently of this compaction"
        )

    for probe in probe_reconstruction(summary, retrieval):
        if probe.resolved_span_id is None:
            raise UnreconstructableEvictionError(
                f"load-bearing claim unanchored: query {probe.query!r} "
                f"resolves to nothing; summary would be sole surviving record"
            )
        if probe.resolved_is_summary_echo:
            raise UnreconstructableEvictionError(
                f"retrieval for {probe.query!r} returned the summary itself; "
                f"reconstruction is echo, not evidence — refusing eviction"
            )

    # All probes resolved to distinct, non-echo spans; eviction is reversible.
    retrieval.evict(summary)
