# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distinguish-between-eviction-and-invalidation-in-self-editing-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distinguish-between-eviction-and-invalidation-in-self-editing-context-windows.warrant.json
# Markdown SHA-256:   d9378b67f6a1f6d501fa8718e7b8c1f64eb7c4146b8c8d4c79f15e39d3e6e689
# Code AST SHA-256:   1eadec6e16dd6199b5550ac0c118edb06e6d17b697423090f4d052d7c1e0db38
# Verified Classes:   SegmentClass, EvictionBoundaryError, Segment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SegmentClass(Enum):
    EPISODIC = "episodic"
    PINNED = "pinned"          # constraints, schemas, preferences, safety rules


class EvictionBoundaryError(RuntimeError):
    """Raised when a prune would cross the eviction/invalidation boundary."""
    pass


@dataclass
class Segment:
    sid: str
    text: str
    cls: SegmentClass
    verbatim_recoverable: bool
    referenced_by: list = field(default_factory=list)
    superseded_by: Optional[str] = None


def decide_prune(segment: Segment, relevance: float, pinned_floor: int,
                 pinned_remaining_after: int, task_requires_pinned: bool) -> str:
    """
    Returns one of: 'evict', 'demote', 'invalidate', 'keep'.
    Raises EvictionBoundaryError when the request is boundary-crossing.
    """
    if segment.superseded_by is not None:
        # Stale content must be invalidated with a tombstone, never merely evicted,
        # or a later re-summary can resurrect it as truth.
        return "invalidate"

    if segment.cls is SegmentClass.PINNED:
        # Relevance is the wrong predicate for invariants. A low score here means
        # the scorer is misconfigured, not that the constraint is droppable.
        if task_requires_pinned and pinned_remaining_after < pinned_floor:
            raise EvictionBoundaryError(
                f"prune of pinned segment {segment.sid!r} would drop pinned "
                f"population below floor {pinned_floor}; refusing to evict an "
                f"invariant under budget pressure (relevance={relevance:.3f})"
            )
        return "demote"

    if segment.referenced_by:
        raise EvictionBoundaryError(
            f"segment {segment.sid!r} is referenced by {segment.referenced_by!r}; "
            f"eviction would silently retract a live precondition"
        )

    if not segment.verbatim_recoverable:
        raise EvictionBoundaryError(
            f"segment {segment.sid!r} is not verbatim-recoverable; eviction would "
            f"force a lossy re-summary that can invert meaning"
        )

    return "evict" if relevance < 0.10 else "keep"


def prune_window(window: list, relevance: dict, pinned_floor: int = 1) -> list:
    pinned_now = sum(1 for s in window if s.cls is SegmentClass.PINNED)
    kept = []
    for s in window:
        pinned_after = pinned_now - (1 if s.cls is SegmentClass.PINNED else 0)
        action = decide_prune(
            s,
            relevance.get(s.sid, 0.0),
            pinned_floor=pinned_floor,
            pinned_remaining_after=pinned_after,
            task_requires_pinned=True,
        )
        if action in ("keep", "demote", "invalidate"):
            kept.append(s)
        if s.cls is SegmentClass.PINNED and action == "demote":
            pinned_now -= 1
    return kept
