# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-evict-the-summary-of-summary-solubility-trap-in-self-editing-context.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-evict-the-summary-of-summary-solubility-trap-in-self-editing-context.warrant.json
# Markdown SHA-256:   e3802f388a8d047d31b23a8357060966fe0dc17c8bd1a8bd079896e450e215c7
# Code AST SHA-256:   7bada3c11828cace156347f46ccc55304af3d4383cd87480b87e314257264870
# Verified Classes:   EvictionRefused, Span, SummaryNode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class EvictionRefused(RuntimeError):
    """Raised when a span cannot be evicted without violating carrier-lineage invariant."""
    pass


@dataclass
class Span:
    span_id: str
    score: float
    parent_summary: str | None          # None => never folded
    binding_constraints: list[str] = field(default_factory=list)


@dataclass
class SummaryNode:
    node_id: str
    pinned: bool
    sole_carrier_for: set[str] = field(default_factory=set)


THRESHOLD = 0.15


def evict(span: Span, summaries: dict[str, SummaryNode]) -> str:
    """
    Decide whether to drop `span`. Relevance authorizes dropping dead spans;
    only carrier-pinning authorizes dropping live-but-compressed spans.
    """
    if span.score >= THRESHOLD:
        return "retain"

    if span.parent_summary is None:
        return "drop_irrelevant"          # true dead span, safe

    parent = summaries.get(span.parent_summary)
    if parent is None:
        raise EvictionRefused(
            f"span {span.span_id} references missing summary {span.parent_summary}"
        )

    if parent.pinned:
        return "drop_lossless"            # gloss guaranteed to survive

    # Parent is compression-eligible: score lacks authority to drop.
    if span.binding_constraints:
        return "promote_then_drop"        # lift constraints to typed record first

    raise EvictionRefused(
        f"span {span.span_id} is sole-carried by compressible summary "
        f"{parent.node_id}; eviction would permit silent constraint loss. "
        f"Promote constraints or evict a lower-lineage span."
    )


def compress_summary(node: SummaryNode, summaries: dict[str, SummaryNode]) -> None:
    """Summary-of-summary is illegal while the node is sole carrier for evicted spans."""
    if node.sole_carrier_for:
        raise EvictionRefused(
            f"summary {node.node_id} is sole carrier for {sorted(node.sole_carrier_for)}; "
            f"re-compression would attenuate non-redundant signal. Pin or restore children first."
        )
    node.pinned = True
