# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-prune-a-context-segment-whose-salience-score-has-fallen-below-threshold-because-that-segment-is-the-s.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-prune-a-context-segment-whose-salience-score-has-fallen-below-threshold-because-that-segment-is-the-s.warrant.json
# Markdown SHA-256:   83d6719f42422e6288b34cd0b91ea173b66f6eb308e1472cf6b46781c592ccd4
# Code AST SHA-256:   b15f3a8d9c32e596392a337e13a32c6e554fa77a66a6237d9ae67f2f9f13f692
# Verified Classes:   CheckpointProvenanceError, Segment, Checkpoint, ContextManager
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CheckpointProvenanceError(RuntimeError):
    """Raised when a prune would orphan a live checkpoint's restore anchor."""


@dataclass
class Segment:
    seg_id: str
    tokens: int
    salience: float


@dataclass
class Checkpoint:
    cp_id: str
    deps: set[str]              # segment ids required to restore
    superseded: bool = False


@dataclass
class ContextManager:
    segments: dict[str, Segment]
    checkpoints: list[Checkpoint] = field(default_factory=list)
    salience_threshold: float = 0.10

    def _live_dependency_closure(self) -> set[str]:
        closure: set[str] = set()
        for cp in self.checkpoints:
            if not cp.superseded:
                closure |= cp.deps
        return closure

    def prune(self, candidates: list[str]) -> list[str]:
        closure = self._live_dependency_closure()
        pruned: list[str] = []
        for seg_id in candidates:
            seg = self.segments.get(seg_id)
            if seg is None:
                continue
            if seg.salience >= self.salience_threshold:
                continue
            if seg_id in closure:
                # Salience says drop; provenance says this is load-bearing.
                # Refuse and surface the conflict rather than silently corrupt.
                raise CheckpointProvenanceError(
                    f"refusing to prune segment {seg_id!r}: salience="
                    f"{seg.salience:.3f} below threshold but segment is a "
                    f"live checkpoint restore anchor"
                )
            del self.segments[seg_id]
            pruned.append(seg_id)
        return pruned

    def dry_run_restore(self, cp_id: str) -> bool:
        cp = next((c for c in self.checkpoints if c.cp_id == cp_id), None)
        if cp is None:
            raise CheckpointProvenanceError(f"unknown checkpoint {cp_id!r}")
        missing = cp.deps - set(self.segments)
        if missing:
            raise CheckpointProvenanceError(
                f"checkpoint {cp_id!r} restore would fail; missing anchors: "
                f"{sorted(missing)}"
            )
        return True
