# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-when-relevance-scored-eviction-silently-drops-the-causal-premise-of-an-in-flight-plan.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-when-relevance-scored-eviction-silently-drops-the-causal-premise-of-an-in-flight-plan.warrant.json
# Markdown SHA-256:   64fa44c3a89009d24bd61b5c3bc140dd5d33c42d917566c842792d9586355446
# Code AST SHA-256:   2345c4eadd6f412834e4a6a9d110faeab6d3d85a2f653ed415d5ea5ff0d00c12
# Verified Classes:   PremiseEvictionError, Segment, PlanNode, SelfEditingContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PremiseEvictionError(RuntimeError):
    """Raised when a scored eviction would drop a segment referenced by a live plan node."""
    pass


@dataclass
class Segment:
    id: str
    text: str
    relevance: float = 0.0


@dataclass
class PlanNode:
    id: str
    status: str  # "live" | "completed" | "abandoned"
    premise_ids: set[str] = field(default_factory=set)


class SelfEditingContext:
    def __init__(self, segments: list[Segment], plan: list[PlanNode]):
        self.segments = {s.id: s for s in segments}
        self.plan = {n.id: n for n in plan}

    def _pinned_ids(self) -> set[str]:
        pinned: set[str] = set()
        for node in self.plan.values():
            if node.status == "live":
                pinned |= node.premise_ids
        return pinned

    def evict_by_score(self, threshold: float) -> list[str]:
        """Evict lowest-relevance segments below threshold, but never a pinned premise."""
        pinned = self._pinned_ids()
        candidates = [
            s for s in self.segments.values()
            if s.relevance < threshold and s.id not in pinned
        ]
        evicted = [s.id for s in candidates]
        for sid in evicted:
            del self.segments[sid]
        return evicted

    def evict_or_refuse(self, segment_id: str) -> None:
        """Explicit eviction request; refuse if the segment justifies a live plan node."""
        pinned = self._pinned_ids()
        if segment_id in pinned:
            owners = [
                n.id for n in self.plan.values()
                if n.status == "live" and segment_id in n.premise_ids
            ]
            raise PremiseEvictionError(
                f"refusing to evict segment {segment_id!r}: it is a premise of "
                f"live plan node(s) {owners}; complete or abandon those nodes first"
            )
        self.segments.pop(segment_id, None)


# --- trace of the observed failure, now bounded ---
ctx = SelfEditingContext(
    segments=[
        Segment("s3", "Only status='open' rows are in scope; closed rows belong to another pipeline.", relevance=0.11),
        Segment("s41", "tool log: fetched 1,204 rows", relevance=0.88),
    ],
    plan=[PlanNode("reconcile", status="live", premise_ids={"s3"})],
)

# Score-based prune: s3 is low-relevance but pinned, so it is NOT a candidate.
evicted = ctx.evict_by_score(threshold=0.5)
assert "s3" not in evicted, "pinned premise must survive scored eviction"

# An explicit request to drop the constraint is refused, not silently honored.
try:
    ctx.evict_or_refuse("s3")
except PremiseEvictionError as e:
    print("blocked:", e)

# Freeing the pin requires an explicit plan-lifecycle decision.
ctx.plan["reconcile"].status = "completed"
ctx.evict_or_refuse("s3")  # now permitted
