# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-evict-a-segment-it-has-just-scored-as-low-salience-the-self-editing-context-window-and-the-score-eviction-race.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-evict-a-segment-it-has-just-scored-as-low-salience-the-self-editing-context-window-and-the-score-eviction-race.warrant.json
# Markdown SHA-256:   239504fa1305bed78363de0dbbe1c0a17ae918d21bb75900f3c02aac12562382
# Code AST SHA-256:   1452e0c4531aae87b315f4f3f7addd18791c52c8b427921a22113db10edc06d7
# Verified Classes:   EvictionRefused, ScoreProvenance, Segment, Tombstone, SelfEditingWindow
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class EvictionRefused(RuntimeError):
    """Raised when a self-editing context window attempts an eviction that
    violates the score-provenance / tombstone invariant."""
    pass


class ScoreProvenance(Enum):
    IN_CONTEXT_SELF = "in_context_self"      # segment body was in the scoring pass
    OUT_OF_CONTEXT_ABSTRACT = "out_of_context_abstract"  # only ingest-time abstract scored


@dataclass
class Segment:
    seg_id: str
    abstract: str
    body_tokens: int
    pinned: bool = False
    score: float | None = None
    provenance: ScoreProvenance | None = None
    residency_passes: int = 0


@dataclass
class Tombstone:
    seg_id: str
    abstract: str
    score: float
    scorer_version: str
    turn: int


@dataclass
class SelfEditingWindow:
    segments: dict[str, Segment] = field(default_factory=dict)
    tombstones: list[Tombstone] = field(default_factory=list)
    tombstone_store_available: bool = True
    contested_threshold: float = 0.3
    max_residency_passes: int = 40

    def evict(self, seg_id: str, turn: int, scorer_version: str) -> Tombstone:
        seg = self.segments.get(seg_id)
        if seg is None:
            raise EvictionRefused(f"unknown segment {seg_id}")

        # Invariant 1: score provenance must be out-of-context.
        if seg.provenance is not ScoreProvenance.OUT_OF_CONTEXT_ABSTRACT:
            raise EvictionRefused(
                f"segment {seg_id} scored via {seg.provenance}; "
                f"in-context self-scores cannot authorize eviction"
            )

        # Invariant 2: score must exist and be low.
        if seg.score is None or seg.score >= 0.4:
            raise EvictionRefused(
                f"segment {seg_id} score {seg.score} does not meet eviction threshold"
            )

        # Invariant 3: pinned segments are never evicted on score.
        if seg.pinned:
            raise EvictionRefused(
                f"segment {seg_id} is pinned (open subgoal / pending verification)"
            )

        # Invariant 4: tombstone must be committable in the same atomic step.
        if not self.tombstone_store_available:
            raise EvictionRefused(
                f"cannot tombstone {seg_id}; eviction would create a memory hole"
            )

        tomb = Tombstone(
            seg_id=seg_id,
            abstract=seg.abstract,
            score=seg.score,
            scorer_version=scorer_version,
            turn=turn,
        )
        # Atomic: tombstone first, then mutate buffer.
        self.tombstones.append(tomb)
        del self.segments[seg_id]
        return tomb

    def score(self, seg_id: str, value: float, provenance: ScoreProvenance) -> None:
        seg = self.segments[seg_id]
        if seg.score is not None and abs(seg.score - value) > self.contested_threshold:
            seg.pinned = True  # freeze contested segment
            return
        seg.score = value
        seg.provenance = provenance
        seg.residency_passes += 1
        if seg.residency_passes > self.max_residency_passes and not seg.pinned:
            # Staleness eviction is a separate axis; still requires tombstone.
            seg.score = 0.0
            seg.provenance = ScoreProvenance.OUT_OF_CONTEXT_ABSTRACT
