# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-context-when-the-summarizer-s-information-loss-budget-exceeds-the-retrieval-fallback-s-recove.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-context-when-the-summarizer-s-information-loss-budget-exceeds-the-retrieval-fallback-s-recove.warrant.json
# Markdown SHA-256:   58f6fe75e42f6af604f20d08d204c8679c7e647ad4e48a2881d8aef59eb3cb90
# Code AST SHA-256:   3f5030dd3758320368e4a11ba144e1c18da5d2a818744550baa5c6bd050fb33a
# Verified Classes:   UnrecoverableCompactionError, Turn, IndexCoverageManifest, CompactionDigest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class UnrecoverableCompactionError(RuntimeError):
    """Raised when a compaction would evict content the retrieval index cannot repay."""
    pass


@dataclass(frozen=True)
class Turn:
    turn_id: int
    role: str
    text: str
    identifier_tokens: frozenset[str]  # ARNs, IDs, hashes, numeric constants


@dataclass(frozen=True)
class IndexCoverageManifest:
    # set of turn_ids the indexer has fully indexed with query-addressable embeddings
    indexed_turn_ids: frozenset[int]


@dataclass(frozen=True)
class CompactionDigest:
    verbatim_identifiers: frozenset[str]  # identifier tokens retained literally in digest
    referenced_turn_ids: frozenset[int]


def assert_compaction_recoverable(
    evicted: Iterable[Turn],
    digest: CompactionDigest,
    manifest: IndexCoverageManifest,
) -> None:
    """
    Enforce the recoverability invariant before committing a compaction.

    Boundary condition: refuse to compact when information_loss > recovery_capacity.
    For each evicted turn, every identifier-class token must be either:
      (a) verbatim in the digest, or
      (b) in a turn the index has fully indexed (query-addressable).
    Otherwise the eviction creates an unrepayable information deficit.
    """
    unrepayable: list[str] = []

    for turn in evicted:
        turn_is_indexed = turn.turn_id in manifest.indexed_turn_ids

        for token in turn.identifier_tokens:
            in_digest = token in digest.verbatim_identifiers
            if in_digest:
                continue
            if turn_is_indexed:
                # index holds the turn; token is query-addressable via its chunk
                continue
            # Neither verbatim in digest nor present in the index coverage.
            unrepayable.append(
                f"turn {turn.turn_id} token {token!r}: "
                f"not in digest, turn not in index manifest"
            )

    if unrepayable:
        raise UnrecoverableCompactionError(
            "refusing to compact: information_loss exceeds recovery_capacity; "
            "retain verbatim or spill to external store. Deficits:\n  "
            + "\n  ".join(unrepayable)
        )


def compact_or_refuse(
    evicted: list[Turn],
    digest: CompactionDigest,
    manifest: IndexCoverageManifest,
    spill_store: dict[str, str],
) -> CompactionDigest:
    """
    Attempt compaction; on refusal, spill uncovered turns verbatim to an
    external store and extend the digest with retrieval keys.
    """
    try:
        assert_compaction_recoverable(evicted, digest, manifest)
        return digest
    except UnrecoverableCompactionError:
        # Spill the uncovered turns verbatim; digest now points at the spill store.
        spill_keys: set[str] = set()
        for turn in evicted:
            if turn.turn_id not in manifest.indexed_turn_ids:
                key = f"spill:turn:{turn.turn_id}"
                spill_store[key] = turn.text
                spill_keys.add(key)

        # Rebuild digest with spill keys so downstream retrieval has a literal pointer.
        merged_verbatim = digest.verbatim_identifiers | frozenset(spill_keys)
        new_digest = CompactionDigest(
            verbatim_identifiers=merged_verbatim,
            referenced_turn_ids=digest.referenced_turn_ids,
        )
        # Re-validate: spill keys are now verbatim identifiers, so coverage holds.
        assert_compaction_recoverable(evicted, new_digest, manifest)
        return new_digest
