# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-model-driven-context-prune-when-salience-scores-are-computed-against-a-stale-checkpoint-baseline.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-model-driven-context-prune-when-salience-scores-are-computed-against-a-stale-checkpoint-baseline.warrant.json
# Markdown SHA-256:   b295682d43d809cd5972b89bf130631e8d1429247033a758c4d7450c02dcf39c
# Code AST SHA-256:   0b6ee97c1a1d16dc290b3eea440c1196164c44efa750761d817e7e69ca8147fd
# Verified Classes:   StaleSalienceBaseline, SalienceScore, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Tuple


class StaleSalienceBaseline(RuntimeError):
    """Raised when a model-driven prune would discard a span that has
    acquired a live dependency after its salience score was minted."""
    pass


@dataclass
class SalienceScore:
    span_id: str
    score: float
    baseline_window_hash: str
    turn_minted: int


@dataclass
class ContextWindow:
    window_hash: str
    ancestor_hashes: Set[str] = field(default_factory=set)
    spans: Set[str] = field(default_factory=set)
    # dependency edges: (referrer_span, target_span) -> turn_created
    edges: Dict[Tuple[str, str], int] = field(default_factory=dict)


def admissible_prune(
    window: ContextWindow,
    scores: Dict[str, SalienceScore],
    tau: float,
    current_turn: int,
) -> Set[str]:
    """Return the set of spans safe to prune, or raise on stale baseline."""
    candidates = {sid for sid, s in scores.items() if s.score < tau}

    for sid in candidates:
        s = scores[sid]
        # Condition 3: score must be minted against an ancestor of this window.
        if s.baseline_window_hash not in window.ancestor_hashes \
                and s.baseline_window_hash != window.window_hash:
            raise StaleSalienceBaseline(
                f"span {sid!r} scored against non-ancestor baseline "
                f"{s.baseline_window_hash!r}"
            )
        # Condition 1: no post-baseline edge may target a pruned span.
        for (referrer, target), created in window.edges.items():
            if target == sid and created > s.turn_minted and referrer in window.spans:
                raise StaleSalienceBaseline(
                    f"span {sid!r} (score {s.score:.2f}, minted turn "
                    f"{s.turn_minted}) is target of live edge from "
                    f"{referrer!r} created turn {created}; deferring prune"
                )
    return candidates


def commit_prune(
    window: ContextWindow,
    to_prune: Set[str],
    checkpoint_writer,
    current_turn: int,
) -> ContextWindow:
    """Condition 2: checkpoint BEFORE mutation, then rewrite window."""
    if not to_prune:
        return window
    checkpoint_writer(window, current_turn)  # pre-mutation snapshot
    new_spans = window.spans - to_prune
    new_edges = {
        e: t for e, t in window.edges.items() if e[0] in new_spans and e[1] in new_spans
    }
    return ContextWindow(
        window_hash=f"w{current_turn}",
        ancestor_hashes=window.ancestor_hashes | {window.window_hash},
        spans=new_spans,
        edges=new_edges,
    )
