# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-has-entered-a-rewrite-eviction-oscillation-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-has-entered-a-rewrite-eviction-oscillation-loop.warrant.json
# Markdown SHA-256:   5a5732b349e69464a383440932153e604a97f9ef53ceee9ca8467e0a48731dad
# Code AST SHA-256:   4a70dd33c407f9f4b83db785286c0cda8a1d009525b7b39291ae21f75b408343
# Verified Classes:   ContextOscillationError, Segment, SelfEditingContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ContextOscillationError(RuntimeError):
    """Raised when a self-editing context re-admits and re-evicts the same segment."""
    pass


@dataclass
class Segment:
    content: str
    salience: float
    inherited_floor: float = 0.0

    @property
    def content_hash(self) -> str:
        return hashlib.sha256(self.content.encode("utf-8")).hexdigest()


@dataclass
class SelfEditingContext:
    threshold: float = 0.25
    epsilon: float = 0.05
    segments: list = field(default_factory=list)
    tombstones: dict = field(default_factory=dict)   # hash -> cached summary
    eviction_counts: dict = field(default_factory=dict)

    def rewrite(self, idx: int, summary: str) -> Segment:
        src = self.segments[idx]
        # Inherit salience: a summary is never less salient than its source.
        new_sal = max(src.salience, src.inherited_floor) - self.epsilon
        return Segment(content=summary, salience=new_sal,
                       inherited_floor=src.inherited_floor)

    def rescore(self, seg: Segment, recomputed: float) -> float:
        # Monotonicity constraint across the rewrite edge.
        if recomputed < seg.inherited_floor - self.epsilon:
            raise ContextOscillationError(
                f"rescore of {seg.content_hash[:8]} dropped to {recomputed:.2f} "
                f"below inherited floor {seg.inherited_floor:.2f}; rewrite is lossy"
            )
        return max(recomputed, seg.inherited_floor)

    def admit(self, seg: Segment) -> None:
        h = seg.content_hash
        if h in self.tombstones:
            # Eviction is final: serve cached summary, do not re-admit raw tokens.
            cached = self.tombstones[h]
            self.segments.append(Segment(content=cached, salience=seg.salience,
                                         inherited_floor=seg.inherited_floor))
            return
        self.segments.append(seg)

    def evict(self, idx: int) -> None:
        seg = self.segments.pop(idx)
        h = seg.content_hash
        self.eviction_counts[h] = self.eviction_counts.get(h, 0) + 1
        if self.eviction_counts[h] >= 2:
            raise ContextOscillationError(
                f"segment {h[:8]} evicted {self.eviction_counts[h]} times; "
                f"rewrite-eviction oscillation detected"
            )
        self.tombstones[h] = seg.content
