# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-salience-inversion-at-the-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-salience-inversion-at-the-compaction-boundary.warrant.json
# Markdown SHA-256:   2859d90af60f8a5421f3da2590251c9a84b4ff61cb56e75faac95d4cbda36811
# Code AST SHA-256:   43e0e6581e54ba355e121ddd00a0fdfca9fb40b78947f8a327076e733faac293
# Verified Classes:   CompactionSalienceError, LedgerEntry, CompactionRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionSalienceError(RuntimeError):
    """Raised when a compaction pass cannot certify that no live
    decision-justification edge is being dropped."""


@dataclass(frozen=True)
class LedgerEntry:
    decision_id: str
    chosen: str
    rejected: tuple[str, ...]
    evidence_ref: str          # pointer into append-only cold store
    closed_at_turn: int


@dataclass
class CompactionRequest:
    range_start: int
    range_end: int
    depth: int = 0             # recursive compaction depth


MAX_COMPACTION_DEPTH = 2


def certify_compaction(
    request: CompactionRequest,
    ledger: list[LedgerEntry],
    cold_store: dict[str, str],
) -> None:
    """Verify that every live decision edge in the range is resolvable
    from the post-compaction store. Raise on any unresolved edge."""
    if request.depth > MAX_COMPACTION_DEPTH:
        raise CompactionSalienceError(
            f"compaction depth {request.depth} exceeds cap "
            f"{MAX_COMPACTION_DEPTH}; fidelity decay is multiplicative"
        )

    in_range = [
        e for e in ledger
        if request.range_start <= e.closed_at_turn <= request.range_end
    ]
    if not in_range:
        return  # nothing decision-bearing in range; compaction is safe

    unresolved = [e for e in in_range if e.evidence_ref not in cold_store]
    if unresolved:
        ids = ", ".join(e.decision_id for e in unresolved)
        raise CompactionSalienceError(
            f"cannot compact turns [{request.range_start},{request.range_end}]: "
            f"unresolved evidence for decision(s) {ids}. "
            f"Refuse and spill to cold store; do not summarize away."
        )


def auto_compact(
    request: CompactionRequest,
    ledger: list[LedgerEntry],
    cold_store: dict[str, str],
    summarize_fn,
) -> str:
    """Entry point. Certifies first; only then summarizes."""
    certify_compaction(request, ledger, cold_store)
    return summarize_fn(request.range_start, request.range_end)
