# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-window-has-begun-evicting-its-own-eviction-criteria.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-window-has-begun-evicting-its-own-eviction-criteria.warrant.json
# Markdown SHA-256:   ae0e661ef6bf15fba6f41d76058599d56251037495a65ecbc43dcbfa3599aaea
# Code AST SHA-256:   991594e2353323fa0e63ef2cce61d0bc17b6062db655daa11282416cfe50cb18
# Verified Classes:   PolicyEvictionError, PruningGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PolicyEvictionError(RuntimeError):
    """Raised when a self-pruning pass would evict or has evicted its own policy."""
    pass


class PruningGuard:
    """Enforces P ∩ C = ∅ and a monotone pin set across pruning passes."""

    def __init__(self, arrival_rate: float, eviction_threshold: float):
        self.arrival_rate = arrival_rate
        self.eviction_threshold = eviction_threshold
        self._pins: set[str] = set()          # engine-owned source of truth
        self._prev_pinned_count: int | None = None
        self._prev_reclaimed: int | None = None

    def pin(self, segment_id: str) -> None:
        self._pins.add(segment_id)

    def check_preconditions(self, segments: list[dict]) -> None:
        # Signal 3: a policy-bearing segment currently scores as evictable.
        for seg in segments:
            if seg.get("is_policy") and seg["score"] < self.eviction_threshold:
                raise PolicyEvictionError(
                    f"policy segment {seg['id']!r} scores {seg['score']:.3f} "
                    f"< threshold {self.eviction_threshold}; pruning would consume the rubric"
                )

    def check_postconditions(self, reclaimed: int, pinned_after: int) -> None:
        # Signal 1: pinned-set shrinkage without an unpin event.
        if (self._prev_pinned_count is not None
                and pinned_after < self._prev_pinned_count):
            raise PolicyEvictionError(
                f"pinned set shrank {self._prev_pinned_count}->{pinned_after} "
                f"with no unpin call; pins were evicted as content"
            )
        # Signal 2: eviction rate accelerating past a flat arrival rate.
        if (self._prev_reclaimed is not None
                and reclaimed > self._prev_reclaimed
                and reclaimed > self.arrival_rate):
            raise PolicyEvictionError(
                f"reclaimed {reclaimed} > arrival {self.arrival_rate:.0f} while rising; "
                f"policy exclusions likely consumed"
            )
        self._prev_pinned_count = pinned_after
        self._prev_reclaimed = reclaimed

    def prune(self, segments: list[dict]) -> tuple[list[dict], int]:
        self.check_preconditions(segments)
        # Structural exclusion: policy segments never reach the scorer.
        candidates = [s for s in segments if not s.get("is_policy") and s["id"] not in self._pins]
        keep = [s for s in segments if s not in candidates]
        evict = [s for s in candidates if s["score"] < self.eviction_threshold]
        reclaimed = sum(s["tokens"] for s in evict)
        kept = [s for s in segments if s not in evict]
        self.check_postconditions(reclaimed, len(self._pins))
        return kept, reclaimed
