# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-without-a-pinned-span-exclusion-ledger-silent-loss-of-the-load-bearing-fact-under-a-recall-guar.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-without-a-pinned-span-exclusion-ledger-silent-loss-of-the-load-bearing-fact-under-a-recall-guar.warrant.json
# Markdown SHA-256:   26d473a668e0d14d8e21627d08e9c6b4d48c4979c39afd6af9937f99f7935aaf
# Code AST SHA-256:   b770ce1d3a95ce92bcffb9a4a89d057d26fb1a10f03529ef730d9b6cabf97b81
# Verified Classes:   RecallGuaranteeViolation, Span, ExclusionLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class RecallGuaranteeViolation(RuntimeError):
    """Raised when compaction evicts a protected span without a retrievable pointer."""


@dataclass(frozen=True)
class Span:
    span_id: str
    content: str

    @property
    def digest(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()[:16]


@dataclass
class ExclusionLedger:
    """Append-only. The compactor may read it, never mutate it."""
    _protected: dict[str, str] = field(default_factory=dict)  # span_id -> digest

    def pin(self, span: Span) -> None:
        self._protected[span.span_id] = span.digest

    def is_protected(self, span: Span) -> bool:
        return self._protected.get(span.span_id) == span.digest

    def protected_ids(self) -> frozenset[str]:
        return frozenset(self._protected)


def compact(
    spans: list[Span],
    ledger: ExclusionLedger,
    summarize,
    retain_last: int = 4,
) -> tuple[str, dict[str, Span]]:
    """
    Returns (digest_text, retrieval_index).
    Invariant: every ledger-protected span must appear in retrieval_index,
    even if its tokens were evicted from the working window.
    """
    evictable = [s for s in spans if not ledger.is_protected(s)]
    tail = spans[-retain_last:]
    digest = summarize(evictable)

    # Re-pin protected spans into the retrieval index at THIS rollup level.
    index: dict[str, Span] = {s.span_id: s for s in tail}
    for s in spans:
        if ledger.is_protected(s):
            index[s.span_id] = s  # survives transitive rollup

    # Verification probe: the guarantee is only real if it is checked.
    for span_id in ledger.protected_ids():
        if span_id not in index:
            raise RecallGuaranteeViolation(
                f"compaction evicted protected span {span_id!r} with no "
                f"retrievable pointer; recall guarantee void at this rollup level"
            )
    return digest, index


def verify_recall(index: dict[str, Span], ledger: ExclusionLedger, probe: str) -> Span:
    hits = [s for s in index.values() if probe in s.content]
    if not hits:
        raise RecallGuaranteeViolation(
            f"post-compaction probe {probe!r} returned no span; "
            f"protected set {sorted(ledger.protected_ids())} not reachable"
        )
    return hits[0]
