# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-lossy-summary-before-compaction-and-how-does-recall-guarantee-accounting-detect-the-silent-drop.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-lossy-summary-before-compaction-and-how-does-recall-guarantee-accounting-detect-the-silent-drop.warrant.json
# Markdown SHA-256:   d713c33e6f582f4228374db223ca3d902ba47b11b96ae1263b9d059d4d00f877
# Code AST SHA-256:   5a50be0b9cc28e8ad48603458c65c57fba750a245dd037fdbdcfc9564f5bf7eb
# Verified Classes:   RecallGuaranteeViolation, Span, Digest, ObligationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class RecallGuaranteeViolation(RuntimeError):
    """Raised when a compaction digest fails to retain a non-droppable span."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    droppable: bool


@dataclass
class Digest:
    text: str
    pointers: dict[str, str] = field(default_factory=dict)  # span_id -> source ref


@dataclass
class ObligationLedger:
    retained_ids: set[str] = field(default_factory=set)

    def add(self, span: Span) -> None:
        if not span.droppable:
            self.retained_ids.add(span.span_id)


def compact_with_guarantee(
    spans: list[Span],
    ledger: ObligationLedger,
    summarize: Callable[[list[Span]], Digest],
    probe: Callable[[Digest, str], bool],
) -> Digest:
    # Pin retained set as mandatory input to the summarizer.
    pinned = [s for s in spans if s.span_id in ledger.retained_ids]
    droppable = [s for s in spans if s.span_id not in ledger.retained_ids]

    digest = summarize(pinned + droppable)

    # Independent probe pass: every retained span must resolve.
    missing = [s.span_id for s in pinned if not probe(digest, s.span_id)]
    if missing:
        raise RecallGuaranteeViolation(
            f"Compaction at boundary dropped non-droppable spans: {missing}. "
            f"Roll back to pre-compaction checkpoint; do not continue."
        )

    # Record provenance for every retained span.
    for s in pinned:
        digest.pointers.setdefault(s.span_id, f"span:{s.span_id}")

    return digest


def resume_after_compaction(digest: Digest, ledger: ObligationLedger) -> None:
    # A resumed session must be able to enumerate its live constraints
    # from the digest alone; otherwise the guarantee is void.
    unresolved = ledger.retained_ids - set(digest.pointers)
    if unresolved:
        raise RecallGuaranteeViolation(
            f"Resume attempted with unverifiable retained set: {sorted(unresolved)}"
        )
