# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-eviction-when-relevance-scores-are-computed-against-a-mutating-query.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-eviction-when-relevance-scores-are-computed-against-a-mutating-query.warrant.json
# Markdown SHA-256:   c5cacb3c49abd2b03dcde0a5841df4622d404c096ccc26ce91e2ec07fd3149ff
# Code AST SHA-256:   f95e1948045087dd0958c42adf3e026b8ebffc93136779512f50b5e2c52d0aa5
# Verified Classes:   ConstraintEvictionError, Segment, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class ConstraintEvictionError(RuntimeError):
    """Raised when an eviction proposal would remove a constraint-bearing segment
    that has no redundant carrier in the window."""
    pass


@dataclass
class Segment:
    id: str
    text: str
    is_constraint: bool = False
    subject: str = ""          # e.g. "migration_files"
    superseded_by: str | None = None


@dataclass
class ContextWindow:
    segments: dict[str, Segment] = field(default_factory=dict)
    constraint_index: dict[str, set[str]] = field(default_factory=dict)  # subject -> segment ids

    def add(self, seg: Segment) -> None:
        self.segments[seg.id] = seg
        if seg.is_constraint and seg.subject:
            self.constraint_index.setdefault(seg.subject, set()).add(seg.id)

    def has_redundant_constraint(self, subject: str, excluding: str) -> bool:
        return any(sid != excluding for sid in self.constraint_index.get(subject, set()))


def evict(
    window: ContextWindow,
    candidate_id: str,
    score: float,
    threshold: float,
    scorer: Callable[[Segment], float],
    stable_frame: str,
) -> None:
    seg = window.segments.get(candidate_id)
    if seg is None:
        return

    # Hard stop: constraint-bearing segments are never scored-evictable.
    if seg.is_constraint and seg.subject:
        if not window.has_redundant_constraint(seg.subject, excluding=seg.id):
            raise ConstraintEvictionError(
                f"refusing to evict constraint segment {seg.id!r} on subject "
                f"{seg.subject!r}: no redundant carrier; score {score:.2f} is advisory only"
            )

    # Query-drift guard: re-score against the stable task frame, not the latest turn.
    rescored = scorer(seg)  # scorer must be bound to stable_frame, not q_t
    if abs(rescored - score) > 0.15:
        raise ConstraintEvictionError(
            f"score instability for {seg.id!r}: {score:.2f} vs {rescored:.2f} "
            f"under stable frame {stable_frame!r}; eviction unsound across query drift"
        )

    if rescored >= threshold:
        return  # not evictable anyway

    # Two-phase commit: only mutate after both guards pass.
    del window.segments[candidate_id]
    if seg.is_constraint and seg.subject:
        window.constraint_index[seg.subject].discard(candidate_id)
