# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-salience-floor-invariant-and-the-reconstruction-proof-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-salience-floor-invariant-and-the-reconstruction-proof-obligation.warrant.json
# Markdown SHA-256:   cd27f5440d8fce8b0c2025380f97ce0ce2c60a08f0c72f447931eb2ded66503e
# Code AST SHA-256:   2cbb019e150b0fb19b9ddf91c13eed89e3d7774f7fb99075f339565f2a87a3e3
# Verified Classes:   CompactionRefused, Span, CompactionResult
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionRefused(RuntimeError):
    """Raised when automatic compaction cannot satisfy the reconstruction-proof obligation."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    literals: frozenset[str]          # identifiers, numeric bounds, negations, entities
    salience: float                    # ranking hint only; never authorizes eviction
    is_dead: bool = False             # R1: provably not queryable by any future step
    external_handle: Optional[str] = None  # R3: resolvable pointer to verbatim store


@dataclass
class CompactionResult:
    retained: list[Span] = field(default_factory=list)
    externalized: list[Span] = field(default_factory=list)
    summarized: list[Span] = field(default_factory=list)


def literal_preserved(span: Span, summary_text: str) -> bool:
    """R2 check: every literal in the span must appear verbatim in the summary."""
    return span.literals.issubset(set(summary_text.split()))


def compact(
    spans: list[Span],
    summarize,
    committed: bool,
    window_full: bool,
) -> CompactionResult:
    """
    Enforce: no span evicted unless covered by R1 (dead), R2 (literals preserved),
    or R3 (externalized with resolvable handle). Salience orders candidates only.
    """
    result = CompactionResult()

    for span in sorted(spans, key=lambda s: s.salience):
        # R1: dead-span proof — safe to drop outright.
        if span.is_dead:
            continue

        # R3: already externalized with a resolvable handle — safe to drop from window.
        if span.external_handle is not None:
            result.externalized.append(span)
            continue

        # R2: only attempt summarization when the task has committed to a query set.
        if committed:
            summary_text = summarize(span.text)
            if literal_preserved(span, summary_text):
                result.summarized.append(span)
                continue
            # Summary dropped a load-bearing literal: reject, externalize instead.
            span.external_handle = f"store://{span.span_id}"
            result.externalized.append(span)
            continue

        # Pre-commitment and uncovered: cannot prove safety. Retain or refuse.
        result.retained.append(span)

    if window_full and not committed:
        uncovered = [s for s in result.retained if s.external_handle is None]
        if uncovered:
            raise CompactionRefused(
                f"window saturated before commitment with {len(uncovered)} uncovered "
                f"spans (e.g. {uncovered[0].span_id}); refusing lossy compaction, "
                f"checkpoint required"
            )

    return result
