# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-rewrite-in-place-eviction-that-its-own-relevance-score-has-already-approved.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-rewrite-in-place-eviction-that-its-own-relevance-score-has-already-approved.warrant.json
# Markdown SHA-256:   a7bb9b9d903ced4369e6c1655233d23727b9be1509626022d7821805539daf4b
# Code AST SHA-256:   75fcb1f5bef14fbfe20a2c2f14981d15532885a943e3373b7f627f2e4fb5e5c7
# Verified Classes:   OrphanedReferenceError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field

class OrphanedReferenceError(RuntimeError):
    """Raised when a rewrite-in-place eviction would leave a retained span
    with a live reference edge into an evicted span."""
    pass

@dataclass
class Span:
    span_id: str
    text: str
    relevance: float
    # edges: this span refers to the antecedent span_id
    outbound_refs: set[str] = field(default_factory=set)

def evict_with_closure(spans: dict[str, Span], evict_ids: set[str]) -> set[str]:
    """Return the set of span_ids safe to overwrite in place.

    A span may be evicted only if no retained span has a live outbound
    reference into it. If it does, refuse — the relevance score is not
    a safety predicate.
    """
    retained = {sid for sid in spans if sid not in evict_ids}
    for sid in evict_ids:
        for rid in retained:
            if sid in spans[rid].outbound_refs:
                raise OrphanedReferenceError(
                    f"cannot evict {sid!r} in place: retained span {rid!r} "
                    f"holds a live reference into it (relevance {spans[sid].relevance:.2f}); "
                    f"inline the antecedent or mark {rid!r} unresolved first"
                )
    return evict_ids

def self_edit(spans: dict[str, Span], saturation: float, threshold: float = 0.85) -> set[str]:
    if saturation < threshold:
        return set()
    ranked = sorted(spans.values(), key=lambda s: s.relevance)
    bottom_decile = {s.span_id for s in ranked[: max(1, len(ranked) // 10)]}
    return evict_with_closure(spans, bottom_decile)
