# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-lossy-compaction-checkpoint-when-the-summarizer-s-own-confidence-metadata-is-the-only-recovery-witness.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-lossy-compaction-checkpoint-when-the-summarizer-s-own-confidence-metadata-is-the-only-recovery-witness.warrant.json
# Markdown SHA-256:   9f3ec0fcd8f74a4aafaa5aa7db9b39a5f257a02870493466bc11e185a9d97e66
# Code AST SHA-256:   edc5348079e08bb0aa1d375254fdb24b4f730410ae5578902e6e671c8e0269bc
# Verified Classes:   CompactionCheckpointError, Citation, CompactionCheckpoint
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class CompactionCheckpointError(RuntimeError):
    """Raised when a compaction checkpoint would destroy citable provenance."""
    pass


@dataclass
class Citation:
    field_name: str
    value: str
    source_id: str
    turn_index: int
    citable: bool = True


@dataclass
class CompactionCheckpoint:
    summary: str
    summarizer_confidence: float
    citations: list[Citation] = field(default_factory=list)


def gate_checkpoint(
    checkpoint: CompactionCheckpoint,
    span_exists: Callable[[int], bool],
    source_exists: Callable[[str], bool],
) -> str:
    """
    Decide whether a compaction checkpoint may commit.

    The summarizer's confidence is deliberately NOT consulted here. It is
    telemetry, not a durability witness. Only independent probes of the raw
    span and cited sources may authorize eviction.
    """
    unresolved: list[Citation] = []
    for c in checkpoint.citations:
        if not c.citable:
            continue
        span_ok = span_exists(c.turn_index)
        source_ok = source_exists(c.source_id)
        if not (span_ok or source_ok):
            unresolved.append(c)

    if unresolved:
        # A citable field's only witness is about to be destroyed.
        # Refuse to commit; the caller must re-materialize, downgrade, or abort.
        names = ", ".join(f"{c.field_name}@turn{c.turn_index}" for c in unresolved)
        raise CompactionCheckpointError(
            f"compaction blocked: {len(unresolved)} citable field(s) have no "
            f"surviving witness ({names}); summarizer confidence "
            f"{checkpoint.summarizer_confidence:.2f} is not a durability signal"
        )

    return "committed"


# --- demonstration of the turn-88 failure ---
span_exists = lambda turn: turn > 82          # cold tier TTL already expired for 1..82
source_exists = lambda sid: sid != "doc#7731" # source doc itself was evicted

checkpoint = CompactionCheckpoint(
    summary="Segment margin was approximately 18%, source doc #7731.",
    summarizer_confidence=0.91,
    citations=[Citation("segment_margin", "18.4%", "doc#7731", turn_index=14)],
)

try:
    gate_checkpoint(checkpoint, span_exists, source_exists)
except CompactionCheckpointError as e:
    # Correct outcome: block, force re-materialization or explicit downgrade,
    # so turn 112 cannot silently substitute a fresh (mutated) observation.
    print(f"BLOCKED: {e}")
