# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-priority-weighted-context-eviction-from-silently-deleting-the-agent-s-own-eviction-policy.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-priority-weighted-context-eviction-from-silently-deleting-the-agent-s-own-eviction-policy.warrant.json
# Markdown SHA-256:   650215f721adb999f47d23d20d03b52402aad97c916c25ed2bacf481576134d3
# Code AST SHA-256:   4c1fa163cebcf336617b3ce271cff72a5894c56dc9ebc4e0f471ba82c063ca71
# Verified Classes:   PolicyClosureViolation, Segment, ContextStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class PolicyClosureViolation(RuntimeError):
    """Raised when the eviction policy's own definition is reachable by eviction."""
    pass


@dataclass
class Segment:
    key: str
    namespace: str          # "task", "retrieval", "policy"
    priority: float
    relevance: float
    content: str


@dataclass
class ContextStore:
    segments: dict[str, Segment] = field(default_factory=dict)
    policy_keys: set[str] = field(default_factory=set)

    def add(self, seg: Segment) -> None:
        self.segments[seg.key] = seg
        if seg.namespace == "policy":
            self.policy_keys.add(seg.key)


def eviction_pass(
    store: ContextStore,
    budget_tokens: int,
    token_len: Callable[[str], int],
    w_p: float,
    w_r: float,
    tau: float,
) -> list[str]:
    # INVARIANT: policy closure is never a candidate, regardless of score.
    candidates = [
        s for s in store.segments.values()
        if s.namespace != "policy" and s.key not in store.policy_keys
    ]

    def score(s: Segment) -> float:
        return w_p * s.priority + w_r * s.relevance

    candidates.sort(key=score)  # ascending: lowest value evicted first
    total = sum(token_len(s.content) for s in store.segments.values())
    evicted: list[str] = []

    for seg in candidates:
        if total <= budget_tokens:
            break
        if score(seg) >= tau:
            break  # everything above threshold is retained; over-budget is a hard error
        total -= token_len(seg.content)
        evicted.append(seg.key)
        del store.segments[seg.key]

    if total > budget_tokens:
        # Cannot evict enough without touching protected content: refuse silently
        # dropping policy or over-threshold segments.
        raise PolicyClosureViolation(
            f"window over budget ({total} > {budget_tokens}) after evicting "
            f"{len(evicted)} segments; remaining candidates are protected. "
            f"Refusing to evict policy closure or over-threshold content."
        )

    # Post-condition: no policy key was removed.
    leaked = store.policy_keys - set(store.segments)
    if leaked:
        raise PolicyClosureViolation(
            f"policy segments evicted by their own policy: {sorted(leaked)}"
        )
    return evicted
