# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-lossy-summarization-as-an-irreversible-projection-rather-than-a-reversible-compression.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-lossy-summarization-as-an-irreversible-projection-rather-than-a-reversible-compression.warrant.json
# Markdown SHA-256:   966cd20c4727e609df99560cf7bd49f620c2ec611c027cfe2005d10a31fb280b
# Code AST SHA-256:   99065445f6cc3f15d69d38c8031ef9bfeaa8fe9e2dfe82dad4b25c0cdbb6ecae
# Verified Classes:   CompactionProjectionError, Span, PinnedLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionProjectionError(RuntimeError):
    """Raised when a lossy compaction would silently drop a state transition."""


@dataclass
class Span:
    span_id: str
    turns: list[str]
    contains_correction: bool = False
    contains_negation: bool = False
    contains_commitment_change: bool = False

    @property
    def is_state_transition(self) -> bool:
        return (
            self.contains_correction
            or self.contains_negation
            or self.contains_commitment_change
        )


@dataclass
class PinnedLedger:
    entries: list[str] = field(default_factory=list)

    def pin(self, span: Span) -> None:
        # Pinned verbatim; never routed through the summarizer.
        for turn in span.turns:
            self.entries.append(f"[{span.span_id}] {turn}")


def compact(
    spans: Iterable[Span],
    ledger: PinnedLedger,
    retention_ratio: float,
    summarizer,
) -> tuple[str, PinnedLedger]:
    if retention_ratio < 0.03:
        raise CompactionProjectionError(
            f"retention_ratio={retention_ratio:.3f} is below the triage "
            "threshold; summarizer will select rather than compress and "
            "supersession content will be lost."
        )

    narrative: list[str] = []
    for span in spans:
        if span.is_state_transition:
            # Ordering-sensitive: must survive verbatim, not as prose.
            ledger.pin(span)
        else:
            narrative.append(" ".join(span.turns))

    summary = summarizer(" ".join(narrative))
    return summary, ledger


def probe_consistency(
    asserted_fact: str,
    ledger: PinnedLedger,
    store_lookup,
) -> None:
    """Post-compaction check: any asserted fact touching a pinned span
    must match the store, not the summary."""
    for entry in ledger.entries:
        key = entry.split("] ", 1)[-1]
        if key and key in asserted_fact:
            ground_truth = store_lookup(key)
            if ground_truth is not None and ground_truth not in asserted_fact:
                raise CompactionProjectionError(
                    f"asserted fact diverges from pinned ledger: "
                    f"summary says {asserted_fact!r}, store says "
                    f"{ground_truth!r}. Compaction was a projection, not "
                    f"a compression; rehydrate from span before proceeding."
                )
