# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-driven-context-prune-that-preserves-relevance-but-severs-referential-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-driven-context-prune-that-preserves-relevance-but-severs-referential-binding.warrant.json
# Markdown SHA-256:   54ca5642e094f6a7d70526566ae470f7ed1b77ea87c86bb95dca34815e366691
# Code AST SHA-256:   ffcd48bcabb0da644686669f517c48d40e8528bb0af14f87e25fb4dfaf49d181
# Verified Classes:   ReferentialClosureViolation, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class ReferentialClosureViolation(RuntimeError):
    """Raised when a prune plan severs a binding a retained span depends on."""


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str
    relevance: float
    aliases: frozenset[str]      # short forms this span defines
    dereferences: frozenset[str] # short forms this span uses
    is_negative_constraint: bool = False


def validate_prune_plan(
    spans: Iterable[Span],
    keep_ids: set[str],
    threshold: float = 0.35,
) -> set[str]:
    """
    Return the set of span_ids the plan must additionally retain to stay
    referentially closed. Raise if a severed negative constraint is detected.
    """
    spans = list(spans)
    by_id = {s.span_id: s for s in spans}
    retained = [by_id[i] for i in keep_ids if i in by_id]
    pruned = [s for s in spans if s.span_id not in keep_ids]

    # Symbol table: alias -> defining span, built from the FULL pre-prune context.
    definer: dict[str, Span] = {}
    for s in spans:
        for alias in s.aliases:
            definer.setdefault(alias, s)

    pinned: set[str] = set()
    for s in retained:
        for ref in s.dereferences:
            d = definer.get(ref)
            if d is None:
                continue  # unresolved even pre-prune; not this check's job
            if d.span_id not in keep_ids:
                pinned.add(d.span_id)

    # Negative constraints that survive nowhere but govern a retained span.
    for p in pruned:
        if not p.is_negative_constraint:
            continue
        restated = any(
            r.is_negative_constraint and r.text == p.text for r in retained
        )
        if restated:
            continue
        governed = any(
            ref in p.aliases for r in retained for ref in r.dereferences
        )
        if governed:
            raise ReferentialClosureViolation(
                f"prune plan severs negative constraint {p.span_id!r} "
                f"(relevance {p.relevance:.2f}) still governing retained spans; "
                f"refusing to apply. Re-emit plan with {p.span_id!r} pinned."
            )

    # Sanity: a pinned span must itself clear the closure bar or be explicitly
    # retained; otherwise the plan is internally inconsistent.
    for pid in pinned:
        if by_id[pid].relevance < threshold and pid not in keep_ids:
            raise ReferentialClosureViolation(
                f"span {pid!r} is a required antecedent but was scored "
                f"below threshold ({by_id[pid].relevance:.2f}); "
                f"relevance and binding disagree — pin explicitly."
            )

    return pinned
