# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-pruned-context-re-derivation-from-silently-resurrecting-superseded-state.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-pruned-context-re-derivation-from-silently-resurrecting-superseded-state.warrant.json
# Markdown SHA-256:   96a97e6945164adb2f6d67915e527c385b64982c439241dffe6f9497bb325bd0
# Code AST SHA-256:   89e9af3df590b05409f188761979d6ba1043d54503266191691cf08d5492bc48
# Verified Classes:   UnsoundPruneError, Turn, SlotState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnsoundPruneError(RuntimeError):
    """Raised when an eviction would strip the only surviving binding for a
    mutable slot, or would drop a supersession while retaining its target."""
    pass


@dataclass
class Turn:
    turn_id: int
    sets_slot: Optional[str] = None       # mutable slot this turn binds
    supersedes: Optional[int] = None      # turn_id this turn invalidates
    salience: float = 0.0


@dataclass
class SlotState:
    pinned_turns: set = field(default_factory=set)
    last_binding_turn: Optional[int] = None


def plan_prune(turns: list[Turn], slots: dict[str, SlotState],
               candidates: list[int]) -> list[int]:
    """Return the subset of candidates safe to evict. Refuses unsound evictions."""
    evict = set(candidates)
    surviving = [t for t in turns if t.turn_id not in evict]

    for slot_name, state in slots.items():
        binders = [t for t in surviving if t.sets_slot == slot_name]
        if not binders:
            # Slot would lose all binding evidence -> re-derivation would guess.
            raise UnsoundPruneError(
                f"prune would leave mutable slot {slot_name!r} with zero "
                f"surviving bindings; re-derivation would be ungrounded"
            )
        # Most recent surviving binding must not be older than a superseded one.
        latest = max(binders, key=lambda t: t.turn_id)
        superseded_ids = {t.supersedes for t in surviving if t.supersedes}
        if latest.supersedes is None and latest.turn_id in superseded_ids:
            raise UnsoundPruneError(
                f"slot {slot_name!r} most-recent surviving binding is turn "
                f"{latest.turn_id}, which a dropped turn superseded; "
                f"re-derivation would resurrect a stale value"
            )
        # A supersession turn is immortal while its target survives.
        for t in turns:
            if t.turn_id in evict and t.supersedes is not None:
                if any(s.turn_id == t.supersedes for s in surviving):
                    raise UnsoundPruneError(
                        f"cannot evict supersession turn {t.turn_id} while "
                        f"its target turn {t.supersedes} survives"
                    )
    return sorted(evict)
