# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-lossless-summarization-checkpoint-has-silently-become-lossy-the-compaction-provenance-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-lossless-summarization-checkpoint-has-silently-become-lossy-the-compaction-provenance-gap.warrant.json
# Markdown SHA-256:   873ab77aedeccd78448f0c5bec9ab6f4b662ad75072418c667d142c72f5417c9
# Code AST SHA-256:   ae95dbc5262c6c5cd7541712037bc003ceb0c4bda840db5401ef39156d140dda
# Verified Classes:   LossyCompactionError, CompactionCheckpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class LossyCompactionError(RuntimeError):
    """Raised when a compaction checkpoint drops a load-bearing entity."""


@dataclass
class CompactionCheckpoint:
    summary: str
    entity_manifest: list[str] = field(default_factory=list)
    degraded: bool = False


_NEGATION = re.compile(r"\b(do not|never|must not|avoid|without)\b[^.]*", re.IGNORECASE)
_NUMERIC_BOUND = re.compile(r"\b\d+(?:\.\d+)?\s*(?:ms|s|kb|mb|gb|%|px|tokens?|retries?)\b", re.IGNORECASE)
_QUOTED = re.compile(r"\"([^\"]{2,80})\"")
_IDENTIFIER = re.compile(r"\b[a-z_][a-z0-9_]{2,}\(\)|\b[A-Z]{2,}_[A-Z0-9_]+\b")


def extract_salient_entities(span: str) -> list[str]:
    """Enumerate carriers downstream reasoning may dereference verbatim."""
    entities: list[str] = []
    entities += [m.group(0).strip() for m in _NEGATION.finditer(span)]
    entities += [m.group(0).strip() for m in _NUMERIC_BOUND.finditer(span)]
    entities += [m.group(1).strip() for m in _QUOTED.finditer(span)]
    entities += [m.group(0).strip() for m in _IDENTIFIER.finditer(span)]
    # dedupe, preserve order
    seen: set[str] = set()
    return [e for e in entities if not (e in seen or seen.add(e))]


def gate_checkpoint(span: str, summary: str) -> CompactionCheckpoint:
    """Admit a checkpoint only if every salient entity survives verbatim."""
    manifest = extract_salient_entities(span)
    dropped = [e for e in manifest if e.lower() not in summary.lower()]
    if dropped:
        # One missing carrier is sufficient to reject; do not average.
        raise LossyCompactionError(
            f"checkpoint rejected: {len(dropped)} salient entities dropped "
            f"(e.g. {dropped[:3]!r}); retain raw span instead of discarding"
        )
    return CompactionCheckpoint(summary=summary, entity_manifest=manifest, degraded=False)


def compact_or_degrade(span: str, summarizer) -> CompactionCheckpoint:
    """Attempt lossless compaction; on dropout, degrade and keep the span."""
    summary = summarizer(span)
    try:
        return gate_checkpoint(span, summary)
    except LossyCompactionError:
        # Degraded checkpoint: summary retained for readability, raw span retained
        # for rehydration, and the manifest records what was NOT guaranteed.
        return CompactionCheckpoint(
            summary=summary,
            entity_manifest=extract_salient_entities(span),
            degraded=True,
        )


def assert_rehydratable(cp: CompactionCheckpoint, raw_span: str | None) -> None:
    """A degraded checkpoint is admissible only if the raw span is still reachable."""
    if cp.degraded and raw_span is None:
        raise LossyCompactionError(
            "degraded checkpoint with no retained raw span: memory is silently lossy"
        )
