# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-model-driven-context-pruning-has-violated-a-dependency-closure-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-model-driven-context-pruning-has-violated-a-dependency-closure-invariant.warrant.json
# Markdown SHA-256:   07adc4b048d6e93de10bbae72659f9f830dd782317da00e9bef6608c0c17e3f3
# Code AST SHA-256:   419c1d4b90b644f00fd38a1d994ac09d491c19a4dc46ceee7df366123cd4c6dc
# Verified Classes:   ClosureViolationError, Span, Window
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ClosureViolationError(RuntimeError):
    """Raised when a model-driven prune would evict a binder while retaining its bound reference."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    score: float


@dataclass
class Window:
    spans: Dict[str, Span] = field(default_factory=dict)
    # (binder_id, bound_id) pairs: binder fixes the interpretation of bound
    bindings: Set[Tuple[str, str]] = field(default_factory=set)


def compute_eviction_set(window: Window, keep_k: int) -> Set[str]:
    ordered = sorted(window.spans.values(), key=lambda s: s.score, reverse=True)
    keep = {s.span_id for s in ordered[:keep_k]}
    return set(window.spans) - keep


def assert_closure_safe(window: Window, evicted: Set[str]) -> None:
    """
    A prune is closure-safe iff no binding edge has its binder evicted while
    its bound reference survives. Violations are collected and raised.
    """
    violations = []
    for binder, bound in window.bindings:
        if binder in evicted and bound not in evicted:
            violations.append((binder, bound))
    if violations:
        raise ClosureViolationError(
            "closure-unsafe prune: evicted binders still referenced by surviving spans: "
            + ", ".join(f"{b}->{d}" for b, d in violations)
        )


def safe_prune(window: Window, keep_k: int) -> Window:
    evicted = compute_eviction_set(window, keep_k)
    # Hard precondition: closure must hold before the prune commits.
    assert_closure_safe(window, evicted)

    new_spans = {sid: s for sid, s in window.spans.items() if sid not in evicted}
    new_bindings = {(a, b) for (a, b) in window.bindings if a in new_spans and b in new_spans}
    return Window(spans=new_spans, bindings=new_bindings)


def demo() -> None:
    w = Window(
        spans={
            "s_def": Span("s_def", "api_base = https://staging.internal", score=0.11),
            "s_use": Span("s_use", "verify against the internal endpoint", score=0.88),
        },
        bindings={("s_def", "s_use")},
    )
    # keep_k=1 evicts the terse definition and keeps the high-scoring reference.
    safe_prune(w, keep_k=1)  # raises ClosureViolationError


if __name__ == "__main__":
    demo()
