# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-relevance-scored-eviction-policy-has-crossed-from-compression-into-information-destruction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-relevance-scored-eviction-policy-has-crossed-from-compression-into-information-destruction.warrant.json
# Markdown SHA-256:   b551a4224f21f797f6cf60eb09b258a7cdb025563d8ed547586023719b025dce
# Code AST SHA-256:   e68e65d8010c34759346e04c8c9f261e38684086bcd517029c4797abd67c7c18
# Verified Classes:   EvictionBoundaryError, SegmentClass, Segment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class EvictionBoundaryError(RuntimeError):
    """Raised when a relevance-scored eviction would destroy a load-bearing constraint."""
    pass


class SegmentClass(Enum):
    NARRATIVE = "narrative"
    DECLARATIVE = "declarative"


@dataclass
class Segment:
    seg_id: str
    text: str
    relevance_score: float
    recoverable: bool
    seg_class: SegmentClass
    counterfactual_score: float | None = None


THRESHOLD = 0.15
PINNED_RESERVE_FRACTION = 0.08


def authorize_eviction(seg: Segment, budget_tokens: int, pinned_tokens: int) -> bool:
    """
    Decide whether a segment may be evicted under a model-driven relevance score.
    Returns True if eviction is authorized, False if the segment must be pinned.
    Raises EvictionBoundaryError if the caller attempts to force eviction of a
    non-recoverable declarative segment without a counterfactual probe.
    """
    if seg.recoverable:
        return seg.relevance_score < THRESHOLD

    if seg.seg_class is SegmentClass.DECLARATIVE:
        if seg.counterfactual_score is None:
            raise EvictionBoundaryError(
                f"segment {seg.seg_id!r} is non-recoverable and declarative; "
                f"refusing score-only eviction without counterfactual probe"
            )
        if pinned_tokens >= int(budget_tokens * PINNED_RESERVE_FRACTION):
            raise EvictionBoundaryError(
                f"segment {seg.seg_id!r} would exceed pinned reserve "
                f"({pinned_tokens} >= {int(budget_tokens * PINNED_RESERVE_FRACTION)}); "
                f"pinning budget exhausted, escalate for supersession review"
            )
        return (seg.relevance_score < THRESHOLD
                and seg.counterfactual_score < THRESHOLD)

    # non-recoverable narrative: evict on score, but caller must log the hash
    return seg.relevance_score < THRESHOLD


def evict(window: list[Segment], budget_tokens: int) -> tuple[list[Segment], list[Segment]]:
    """Partition window into (resident, evicted) under the two-signal gate."""
    resident, evicted = [], []
    pinned_tokens = 0
    for seg in window:
        try:
            if authorize_eviction(seg, budget_tokens, pinned_tokens):
                evicted.append(seg)
            else:
                resident.append(seg)
                if not seg.recoverable:
                    pinned_tokens += len(seg.text.split())
        except EvictionBoundaryError:
            resident.append(seg)
            pinned_tokens += len(seg.text.split())
    return resident, evicted
