# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-relevance-score-monotonicity-when-model-driven-pruning-deletes-the-evidence-that-justified-the-pruning.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-relevance-score-monotonicity-when-model-driven-pruning-deletes-the-evidence-that-justified-the-pruning.warrant.json
# Markdown SHA-256:   8c23459ce4d1aee61e2c5ea0b726ea6dc2ae2ff30b057a2b376ab09bb055c5b8
# Code AST SHA-256:   44df8da8595b80dee4d472d40af3a5ce4ff1e29fe5ebd02cb1b6a6e335c79418
# Verified Classes:   RelevancePruneInvariantError, SpanScore, PruneRecord, SelfEditingContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Optional


class RelevancePruneInvariantError(RuntimeError):
    """Raised when a self-editing pass would prune a span whose justification
    was computed against a context that the same pass mutates."""
    pass


@dataclass
class SpanScore:
    span_id: str
    score: float
    pass_id: int
    context_fingerprint: str


@dataclass
class PruneRecord:
    span_id: str
    score: float
    context_fingerprint: str
    pass_id: int


@dataclass
class SelfEditingContext:
    live_spans: Dict[str, str] = field(default_factory=dict)          # span_id -> text
    history: Dict[str, List[SpanScore]] = field(default_factory=dict)  # span_id -> scores
    prune_log: List[PruneRecord] = field(default_factory=list)         # immutable, not model-readable
    re_admission_budget: int = 8
    epsilon: float = 0.15
    k_stability: int = 2

    def fingerprint(self) -> str:
        return "|".join(sorted(self.live_spans.keys()))

    def score_stability(self, span_id: str) -> Optional[float]:
        hs = self.history.get(span_id, [])
        if len(hs) < self.k_stability + 1:
            return None
        recent = hs[-(self.k_stability + 1):]
        return max(s.score for s in recent) - min(s.score for s in recent)

    def apply_prune_pass(
        self,
        pass_id: int,
        scores: Dict[str, float],
        reversibility_cost: Dict[str, int],   # tool-calls to re-admit
        threshold: float = 0.3,
    ) -> List[str]:
        """Returns span_ids actually pruned. Defers unstable/high-cost spans."""
        fp = self.fingerprint()
        candidates = [sid for sid, s in scores.items() if s < threshold and sid in self.live_spans]

        # Freeze scores BEFORE mutating anything.
        for sid, s in scores.items():
            self.history.setdefault(sid, []).append(
                SpanScore(sid, s, pass_id, fp)
            )

        pruned, deferred = [], []
        for sid in candidates:
            stability = self.score_stability(sid)
            cost = reversibility_cost.get(sid, 0)

            # Invariant 1: unstable score => defer, do not prune this pass.
            if stability is None or stability > self.epsilon:
                deferred.append(sid)
                continue

            # Invariant 2: high reversibility cost + co-present pruned neighbors => defer.
            if cost > 0 and self._co_pruned_neighbor(sid, candidates):
                deferred.append(sid)
                continue

            pruned.append(sid)

        # Apply only after all decisions are frozen.
        for sid in pruned:
            text = self.live_spans.pop(sid)
            self.prune_log.append(
                PruneRecord(sid, scores[sid], fp, pass_id)
            )
        return pruned

    def _co_pruned_neighbor(self, sid: str, candidates: List[str]) -> bool:
        return any(other != sid for other in candidates)

    def re_admit(self, span_id: str, text: str) -> None:
        if self.re_admission_budget <= 0:
            raise RelevancePruneInvariantError(
                f"Re-admission budget exhausted while re-admitting {span_id!r}; "
                "escalate to exogenous compaction with pinned-evidence list."
            )
        self.re_admission_budget -= 1
        self.live_spans[span_id] = text

    def assert_prune_justification(self, record: PruneRecord) -> None:
        """A prune record is only valid against the fingerprint it was made under.
        If the live context no longer matches, the record is stale and must not
        be used as evidence of irrelevance."""
        if record.context_fingerprint != self.fingerprint():
            raise RelevancePruneInvariantError(
                f"Stale prune justification for {record.span_id!r}: recorded under "
                f"{record.context_fingerprint!r}, live context is {self.fingerprint()!r}. "
                "Treat span as UNKNOWN, not irrelevant; re-admit or re-derive."
            )
