# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-relevance-scored-pruning-from-silently-deleting-the-antecedent-of-a-live-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-relevance-scored-pruning-from-silently-deleting-the-antecedent-of-a-live-obligation.warrant.json
# Markdown SHA-256:   a2e8597a1bb681810d3d2123b4f757914988715b4cd130d1b9472ef183cf51dc
# Code AST SHA-256:   7bc047e18fb131cc5bcd53922adc7685e045ed2b4a096d61e9e35884222aa95b
# Verified Classes:   OrphanedObligationError, Span, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class OrphanedObligationError(RuntimeError):
    """Raised when a live consequent's antecedent is absent from the window."""


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str
    is_constraint: bool          # prohibition / frozen schema / budget
    references: tuple[str, ...]  # antecedent span_ids this span depends on


@dataclass
class ContextWindow:
    spans: dict[str, Span] = field(default_factory=dict)
    constraint_ledger: dict[str, str] = field(default_factory=dict)

    def live_references(self) -> set[str]:
        refs: set[str] = set()
        for s in self.spans.values():
            refs.update(s.references)
        return refs


def antecedent_closure(window: ContextWindow, candidates: Iterable[str]) -> set[str]:
    """Expand an eviction candidate set so no surviving span is orphaned."""
    evict = set(candidates)
    # Constraints are exempt from pruning entirely.
    evict = {sid for sid in evict if not window.spans[sid].is_constraint}

    changed = True
    while changed:
        changed = False
        survivors = [s for sid, s in window.spans.items() if sid not in evict]
        for s in survivors:
            for ref in s.references:
                if ref not in evict and ref not in window.spans:
                    raise OrphanedObligationError(
                        f"span {s.span_id} references unknown antecedent {ref}"
                    )
                if ref in evict:
                    evict.discard(ref)  # re-include antecedent
                    changed = True
    return evict


def commit_prune(window: ContextWindow, ranked_candidates: list[str]) -> ContextWindow:
    evict = antecedent_closure(window, ranked_candidates)
    survivors = {sid: s for sid, s in window.spans.items() if sid not in evict}
    # Re-inject constraint ledger verbatim; it is append-only for the task.
    for sid, text in window.constraint_ledger.items():
        survivors[sid] = Span(sid, text, is_constraint=True, references=())
    return ContextWindow(spans=survivors, constraint_ledger=dict(window.constraint_ledger))


def resolve_at_consumption(window: ContextWindow, span_id: str) -> Span:
    span = window.spans.get(span_id)
    if span is None:
        raise OrphanedObligationError(f"consumed span {span_id} not in window")
    for ref in span.references:
        if ref not in window.spans:
            raise OrphanedObligationError(
                f"obligation unbound: {span_id} depends on evicted antecedent {ref}"
            )
    return span
