# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-window-has-evicted-a-load-bearing-segment-rather-than-a-stale-one.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-window-has-evicted-a-load-bearing-segment-rather-than-a-stale-one.warrant.json
# Markdown SHA-256:   158d3f36928b38481b62ba86faf947ee19af7ee64c1090c4f4fb5e5e16f44988
# Code AST SHA-256:   474ff8a160763c51a0986203feca998caab5b9c5e1c3c19c47ef29dc271ddde0
# Verified Classes:   LoadBearingEvictionError, Segment
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class LoadBearingEvictionError(RuntimeError):
    """Raised when a pruning policy attempts to evict a segment that
    constrains unexecuted work, or whose summary drops polarity/operand."""
    pass


SegmentClass = Literal["content", "constraint"]


@dataclass
class Segment:
    seg_id: str
    cls: SegmentClass
    text: str
    relevance: float
    # seg_ids of unexecuted segments this one constrains (outgoing edges)
    dependency_edges: set[str] = field(default_factory=set)
    # keys (fields/units/identifiers) this segment defines
    defines_keys: set[str] = field(default_factory=set)
    # True if any proposed summary preserves polarity and operand
    summary_preserves_constraint: bool = True


def assert_eviction_safe(
    candidate: Segment,
    retained: list[Segment],
    eviction_floor: float,
) -> None:
    """Enforce the structural invariant before relevance-based eviction.

    Raises LoadBearingEvictionError if the candidate is load-bearing
    regardless of its relevance score.
    """
    # Rule 1: constraints are never eligible for relevance eviction.
    if candidate.cls == "constraint":
        raise LoadBearingEvictionError(
            f"segment {candidate.seg_id} is a constraint; "
            f"relevance {candidate.relevance:.2f} is the wrong axis"
        )

    # Rule 2: outgoing edges into unexecuted work forbid eviction.
    if candidate.dependency_edges:
        raise LoadBearingEvictionError(
            f"segment {candidate.seg_id} has dependency edges into "
            f"unexecuted segments {sorted(candidate.dependency_edges)}"
        )

    # Rule 3: a summary that drops polarity/operand is a failed eviction.
    if candidate.cls == "constraint" or not candidate.summary_preserves_constraint:
        raise LoadBearingEvictionError(
            f"summary of {candidate.seg_id} drops polarity/operand; "
            f"retain verbatim or fail closed"
        )

    # Rule 4: do not orphan a referent still used by retained segments.
    for other in retained:
        if other.seg_id == candidate.seg_id:
            continue
        if candidate.defines_keys & _referenced_keys(other):
            raise LoadBearingEvictionError(
                f"evicting {candidate.seg_id} would orphan keys "
                f"{sorted(candidate.defines_keys)} referenced by {other.seg_id}"
            )

    # Only now is relevance consulted.
    if candidate.relevance >= eviction_floor:
        raise LoadBearingEvictionError(
            f"segment {candidate.seg_id} relevance {candidate.relevance:.2f} "
            f"above floor {eviction_floor:.2f}; not evictable"
        )


def _referenced_keys(seg: Segment) -> set[str]:
    # Placeholder: real impl scans seg.text for defined keys/identifiers.
    return set()
