# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-eviction-reentry-oscillation-in-self-editing-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-eviction-reentry-oscillation-in-self-editing-context-windows.warrant.json
# Markdown SHA-256:   d2da4c4866fc687ffe3fa1102d4fb442847c31491fe97b0a5f778a1f3f6f1a0c
# Code AST SHA-256:   33dca2c374a8d98bc4c62fc3628242a73b9983ffe678d141819791f295e7f6d9
# Verified Classes:   EvictionOscillationError, SegmentLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class EvictionOscillationError(RuntimeError):
    """Raised when a segment re-enters the window after repeated evictions
    without hysteresis, indicating a non-convergent pruning control loop."""
    pass


class SegmentLedger:
    """Tracks eviction history to detect and prevent re-entry oscillation."""

    HARD_LIMIT = 2          # evictions before a segment must be pinned or canonicalized
    HYSTERESIS_MARGIN = 0.10

    def __init__(self):
        self._evictions = {}   # segment_id -> count
        self._pinned = set()

    def record_eviction(self, segment_id: str, score: float, threshold: float) -> None:
        self._evictions[segment_id] = self._evictions.get(segment_id, 0) + 1
        if self._evictions[segment_id] >= self.HARD_LIMIT:
            # The segment has oscillated. Do not silently allow another re-admission.
            raise EvictionOscillationError(
                f"segment {segment_id!r} evicted {self._evictions[segment_id]} times "
                f"(score={score:.3f} threshold={threshold:.3f}); "
                f"pin it or replace with canonical form before re-admission"
            )

    def admit(self, segment_id: str, score: float, threshold: float) -> bool:
        prior = self._evictions.get(segment_id, 0)
        if prior == 0:
            return score >= threshold
        if segment_id in self._pinned:
            return True
        # Probationary re-admission requires clearing the hysteresis margin.
        return score >= threshold + self.HYSTERESIS_MARGIN

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


def evict(ledger: SegmentLedger, segment_id: str, score: float, threshold: float) -> None:
    if segment_id in ledger._pinned:
        return
    if score < threshold:
        ledger.record_eviction(segment_id, score, threshold)
