# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-evict-a-segment-whose-relevance-score-has-dropped-but-whose-referent-is-still-live-in-the-reasoning-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-evict-a-segment-whose-relevance-score-has-dropped-but-whose-referent-is-still-live-in-the-reasoning-trace.warrant.json
# Markdown SHA-256:   eba91dd003123c4c5b29da7fa8686b268160f541da5bbf75ed50ccba430de589
# Code AST SHA-256:   7f6fb4bcc0e05a104c1c7c7c205dbb748ebc2549549733ff2312eaf8e8dcb517
# Verified Classes:   SegmentKind, Segment, LiveTrace, UnsafeEvictionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SegmentKind(Enum):
    RAW = "raw"
    DERIVED = "derived"
    REDUNDANT = "redundant"
    SUMMARY = "summary"


@dataclass
class Segment:
    seg_id: str
    kind: SegmentKind
    relevance: float
    reconstructible_from: Optional[str] = None  # seg_id of retained input


@dataclass
class LiveTrace:
    # variables / plan-node ids / pending obligations -> segment they dereference
    references: dict[str, str] = field(default_factory=dict)
    pending_obligations: set[str] = field(default_factory=set)

    def is_referenced(self, seg_id: str) -> bool:
        return seg_id in self.references.values() or seg_id in self.pending_obligations


class UnsafeEvictionError(RuntimeError):
    """Raised when an eviction would sever a live referent with no lossless path."""


def evict(
    seg: Segment,
    trace: LiveTrace,
    floor: float,
    retained: dict[str, Segment],
) -> Optional[str]:
    """
    Returns the seg_id to evict, or None to retain.
    Raises UnsafeEvictionError if the segment is a live, non-reconstructible referent
    and the caller is attempting summary-substitution.
    """
    if seg.relevance >= floor:
        return None  # keep: still relevant

    live = trace.is_referenced(seg.seg_id)

    if not live:
        return seg.seg_id  # safe: no referent, low score

    # Live referent. Only lossless paths are permitted.
    if seg.kind == SegmentKind.REDUNDANT:
        return seg.seg_id

    if seg.reconstructible_from is not None:
        src = retained.get(seg.reconstructible_from)
        if src is not None:
            # deliberate recompute path exists; record it, then evict
            trace.references[seg.seg_id] = seg.reconstructible_from
            return seg.seg_id
        # claimed reconstructible but source is gone: not actually reconstructible
        raise UnsafeEvictionError(
            f"segment {seg.seg_id} claims reconstructible_from "
            f"{seg.reconstructible_from} but source is not retained"
        )

    # Live, not reconstructible, not redundant: MUST retain. Summary substitution is a bug.
    raise UnsafeEvictionError(
        f"refusing to evict live referent {seg.seg_id}: "
        f"relevance={seg.relevance:.2f} < floor={floor:.2f} but referenced by "
        f"live trace with no lossless reconstruction path. "
        f"Retain or replace with a content-hash handle, not a summary."
    )


def self_edit(segments: list[Segment], trace: LiveTrace, floor: float) -> list[str]:
    retained = {s.seg_id: s for s in segments}
    evicted: list[str] = []
    for seg in segments:
        try:
            result = evict(seg, trace, floor, retained)
        except UnsafeEvictionError:
            # retain and surface; do not swallow into a silent summary
            continue
        if result is not None:
            evicted.append(result)
            retained.pop(result, None)
    return evicted
