# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-model-driven-context-pruning-from-deleting-the-evidence-that-justifies-the-prune.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-model-driven-context-pruning-from-deleting-the-evidence-that-justifies-the-prune.warrant.json
# Markdown SHA-256:   fbeec213e295020ed2e6e618c505c97e6eb8041b05fd34a08c54100746f2724c
# Code AST SHA-256:   69bae334cee8af3eacc6b793842814bd2429235fb8df4e89cc5ea9e2eea7f67d
# Verified Classes:   JustificationClosureError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class JustificationClosureError(RuntimeError):
    """Raised when a proposed prune set would orphan a retained span's provenance."""


@dataclass
class Span:
    sid: str
    content: str
    prov: Set[str] = field(default_factory=set)  # ids this span cites
    tombstone: bool = False


def check_closure(spans: Dict[str, Span], prune: Set[str]) -> None:
    """Enforce: every retained span keeps >=1 live provenance edge, or is pruned.

    Raises JustificationClosureError listing each dangling dependent.
    """
    dangling = []
    for sid, span in spans.items():
        if sid in prune:
            continue
        if not span.prov:
            continue  # root span, no provenance to lose
        live = span.prov - prune
        if not live:
            dangling.append((sid, sorted(span.prov)))
    if dangling:
        raise JustificationClosureError(
            "prune set orphans retained spans; tombstone or cascade required: "
            + "; ".join(f"{s} <- {p}" for s, p in dangling)
        )


def apply_prune(spans: Dict[str, Span], prune: Set[str], tombstone: bool = True) -> Dict[str, Span]:
    """Commit a prune only if closure holds. Default: tombstone factual sources."""
    check_closure(spans, prune)
    out = dict(spans)
    for sid in prune:
        if tombstone and sid in out:
            src = out[sid]
            out[sid] = Span(sid=sid, content=src.content[:80], prov=src.prov, tombstone=True)
        else:
            out.pop(sid, None)
    return out


def run_compaction(spans: Dict[str, Span], model_proposed_prune: Set[str]) -> Dict[str, Span]:
    try:
        return apply_prune(spans, model_proposed_prune)
    except JustificationClosureError as e:
        # Reject the model's proposal; fall back to tombstoning the whole set,
        # which preserves closure without trusting the model's cascade judgment.
        return apply_prune(spans, model_proposed_prune, tombstone=True)
