# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-evict-the-self-pruning-context-window-and-the-unsnapshotted-evidence-trap.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-evict-the-self-pruning-context-window-and-the-unsnapshotted-evidence-trap.warrant.json
# Markdown SHA-256:   6b02a9fa8393c7e780353943d8922d876fc41137fcba7ce6cf7cc0fdc74f3315
# Code AST SHA-256:   795767f3cea93e9d1b7d2d9573e9d37bfa4eff2673e8eb25f5eaabd702028bc7
# Verified Classes:   UnsafeEvictionError, Proposition, Span, ObligationLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnsafeEvictionError(RuntimeError):
    """Raised when a self-pruning pass attempts to evict a witness-only span."""


@dataclass
class Proposition:
    subject: str
    field_name: str
    value: object
    has_typed_surrogate: bool
    raw_handle: Optional[str] = None


@dataclass
class Span:
    span_id: str
    tokens: int
    relevance: float
    witnesses: list[Proposition] = field(default_factory=list)


@dataclass
class ObligationLedger:
    live: set[tuple[str, str]] = field(default_factory=set)  # (subject, field_name)

    def is_live(self, subject: str, field_name: str) -> bool:
        return (subject, field_name) in self.live


def may_evict(span: Span, ledger: ObligationLedger) -> tuple[bool, str]:
    """Return (allowed, reason). Refuses when a span is the sole witness for a
    live proposition that has no typed surrogate and no retrieval handle."""
    for prop in span.witnesses:
        live = ledger.is_live(prop.subject, prop.field_name)
        if not live:
            continue
        if prop.has_typed_surrogate:
            continue
        if prop.raw_handle is not None:
            # reconstructible via handle; compaction, not eviction, is still preferred
            continue
        return False, (
            f"span {span.span_id} is sole witness for live proposition "
            f"{prop.subject}.{prop.field_name}={prop.value!r} "
            f"with no typed surrogate and no retrieval handle"
        )
    return True, "safe: all live-witnessed propositions are surrogated or handle-backed"


def prune(spans: list[Span], ledger: ObligationLedger, token_budget: int) -> list[Span]:
    """Evict lowest-relevance spans until under budget, but never violate the
    evidentiary-survival invariant. Raises if budget cannot be met safely."""
    ordered = sorted(spans, key=lambda s: s.relevance)
    kept: list[Span] = []
    total = sum(s.tokens for s in spans)
    evicted = 0
    for span in ordered:
        if total <= token_budget:
            kept.append(span)
            continue
        allowed, reason = may_evict(span, ledger)
        if allowed:
            total -= span.tokens
            evicted += 1
        else:
            kept.append(span)
    if total > token_budget:
        raise UnsafeEvictionError(
            f"cannot meet budget {token_budget} without unsafe eviction; "
            f"remaining {total} tokens held by witness-only spans. "
            f"Compaction required before further pruning. "
            f"last refusal: {reason if not kept else 'see per-span refusals'}"
        )
    return kept
