# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-irreversible-evidence-boundary-in-model-driven-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-irreversible-evidence-boundary-in-model-driven-context-compaction.warrant.json
# Markdown SHA-256:   45935dd9c1f7a58c87bb39d0e3e664dcdc93519c8fd6c0a4e690f1374c84cd74
# Code AST SHA-256:   2e4e81d90572d915ecd3e19e2de3eddace5b2d5b0cf00754fb5b2d7386cb8f84
# Verified Classes:   IrreversibleEvictionError, Turn
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class IrreversibleEvictionError(RuntimeError):
    """Raised when a pruning policy attempts to summarize away the only copy of a fact."""
    pass


REGENERABLE = "REGENERABLE"
IRREVERSIBLE = "IRREVERSIBLE"


class Turn:
    def __init__(self, turn_id, evidence_class, payload, resolver=None):
        self.turn_id = turn_id
        self.evidence_class = evidence_class
        self.payload = payload
        self.resolver = resolver  # callable() -> payload, or None if unrecoverable

    def is_reconstructible(self):
        return self.evidence_class == REGENERABLE or self.resolver is not None


def apply_pruning_policy(window, eviction_set, durable_store):
    """
    window: list[Turn]
    eviction_set: set[turn_id] proposed by the model-driven relevance policy
    durable_store: object with .write_pointer(turn_id, payload) -> pointer_id
    Returns the surviving window after a *sound* compaction.
    """
    survivors = []
    for turn in window:
        if turn.turn_id not in eviction_set:
            survivors.append(turn)
            continue

        # Reconstructible: safe to drop outright.
        if turn.is_reconstructible():
            continue

        # Irreversible with no resolver: refuse to summarize; externalize atomically.
        if turn.resolver is None:
            if durable_store is None:
                raise IrreversibleEvictionError(
                    f"turn {turn.turn_id} is the sole copy of an irreversible fact "
                    f"and no durable store is configured; refusing SUMMARIZE-mode "
                    f"compaction (would cause silent hallucination downstream)"
                )
            # Atomic: pointer written before tokens dropped, in one step.
            pointer_id = durable_store.write_pointer(turn.turn_id, turn.payload)
            survivors.append(
                Turn(turn.turn_id, IRREVERSIBLE, payload=f"<ptr:{pointer_id}>",
                     resolver=lambda pid=pointer_id: durable_store.read_pointer(pid))
            )
            continue

        # Has a resolver: allowed, but pointer must exist before drop (same step).
        survivors.append(turn)

    return survivors
