# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-self-editing-context-windows-and-the-irreversible-eviction-of-a-load-bearing-premise.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-self-editing-context-windows-and-the-irreversible-eviction-of-a-load-bearing-premise.warrant.json
# Markdown SHA-256:   77ff99a94eed932eca071562f4978a4eb551189e5016f8f4800840f52d91bd57
# Code AST SHA-256:   f5a2dd15f1cb40696dc361200d6a7611450c1fe7d7fe80029ad073fa557baa3f
# Verified Classes:   PruneRefused, SpanKind, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class PruneRefused(RuntimeError):
    """Raised when a candidate span is load-bearing and cannot be safely evicted."""
    pass


class SpanKind(Enum):
    DISPENSABLE = "dispensable"
    CONSTRAINT = "constraint"
    NEGATIVE_RESULT = "negative_result"
    ANCHOR = "anchor"


@dataclass
class Span:
    span_id: str
    kind: SpanKind
    relevance_score: float
    reconstructible: bool
    literals: list[str]  # exact identifiers / constraint text / error codes


def safe_to_evict(span: Span) -> bool:
    # Reconstructible spans are always safe: eviction is a cache miss.
    if span.reconstructible:
        return True
    # Non-reconstructible spans are safe only if dependency-free.
    return span.kind is SpanKind.DISPENSABLE


def prune(candidates: list[Span], budget_utilization: float) -> list[Span]:
    if budget_utilization <= 0.80:
        return candidates  # no pruning needed

    retained: list[Span] = []
    for span in candidates:
        if not safe_to_evict(span):
            # Load-bearing and irrecoverable: refuse, do not summarize away.
            raise PruneRefused(
                f"cannot evict {span.span_id} (kind={span.kind.value}, "
                f"score={span.relevance_score:.2f}); "
                f"irrecoverable literals={span.literals}. "
                f"Escalate budget: expand window, offload with tombstone, or fail."
            )
        retained.append(span)
    return retained


def make_tombstone(span: Span) -> dict:
    # Minimal non-summarized record: exact literals + retrieval handle.
    return {"handle": f"store://{span.span_id}", "literals": list(span.literals)}
