# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-summary-that-was-already-produced-under-a-lossy-eviction-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-summary-that-was-already-produced-under-a-lossy-eviction-budget.warrant.json
# Markdown SHA-256:   a86dce0d46bb1e290c43acab28c201dec72d59bf5c119cdb72fd58cf864820a8
# Code AST SHA-256:   971e02dec0f1d4fc5c1c5c208d6e5e0805ff77f0e98f5c06209ac973357d0a16
# Verified Classes:   CompactionGuaranteeError, SummaryArtifact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionGuaranteeError(RuntimeError):
    """Raised when a compaction pass would silently invalidate a recall guarantee."""


@dataclass
class SummaryArtifact:
    text: str
    reference_corpus: Optional[str]      # identity of the raw corpus the guarantee is against
    hop_from_source: int                 # 0 == produced directly from raw records
    recall_floor: Optional[float]        # guarantee vs. reference_corpus, None if dropped
    provenance: list = field(default_factory=list)  # pointers to source spans, if any


def compact(inputs: list[SummaryArtifact], *, lossy: bool, has_provenance: bool) -> SummaryArtifact:
    """Roll up summary artifacts, enforcing the source-grounded vs summary-grounded boundary."""
    if not inputs:
        raise CompactionGuaranteeError("cannot compact empty input set")

    max_hop = max(a.hop_from_source for a in inputs)
    corpora = {a.reference_corpus for a in inputs}
    if len(corpora) > 1:
        raise CompactionGuaranteeError(
            f"inputs reference multiple corpora {corpora}; guarantee cannot be rebased"
        )
    corpus = corpora.pop()

    summary_grounded = max_hop >= 1
    inherited_floor = min(
        (a.recall_floor for a in inputs if a.recall_floor is not None),
        default=None,
    )

    if summary_grounded and lossy and not has_provenance:
        # The dangerous case: lossy rollup over summaries with no way to re-ground
        # salience on source. We may proceed only by dropping the guarantee.
        if inherited_floor is not None:
            raise CompactionGuaranteeError(
                "lossy summary-grounded compaction without provenance would "
                f"invalidate inherited recall floor {inherited_floor} at hop {max_hop + 1}; "
                "either supply provenance pointers or mark output guarantee: none"
            )
        return SummaryArtifact(
            text="<rolled-up>",
            reference_corpus=corpus,
            hop_from_source=max_hop + 1,
            recall_floor=None,
            provenance=[],
        )

    if summary_grounded and lossy and has_provenance:
        # Provenance lets the eviction model re-read source spans, so the floor
        # can be rebased against the raw corpus rather than the prior summary.
        rebased = inherited_floor
        return SummaryArtifact(
            text="<rolled-up>",
            reference_corpus=corpus,
            hop_from_source=max_hop + 1,
            recall_floor=rebased,
            provenance=[p for a in inputs for p in a.provenance],
        )

    # Source-grounded or lossless: guarantee rebases cleanly.
    return SummaryArtifact(
        text="<rolled-up>",
        reference_corpus=corpus,
        hop_from_source=max_hop + 1,
        recall_floor=inherited_floor,
        provenance=[p for a in inputs for p in a.provenance],
    )
