# 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-pruning-decision-because-the-pruned-span-is-a-load-bearing-referent-for-a-pending.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-model-driven-context-pruning-decision-because-the-pruned-span-is-a-load-bearing-referent-for-a-pending.warrant.json
# Markdown SHA-256:   1078307d979eabfda74b438b0e178bed34437015884c08e08d918ea2683bb21c
# Code AST SHA-256:   99a639b292eca8884d9270a247a5f3795b6500f1294fa0ff68fb518ccca5cdbf
# Verified Classes:   BindingInvariantViolation, Span, LiveCall, ContextPruner
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class BindingInvariantViolation(RuntimeError):
    """Raised when a model-driven prune would evict a load-bearing referent."""
    pass


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


@dataclass
class LiveCall:
    call_id: str
    arg_tokens: set[str]  # literal tokens the executor will dereference


@dataclass
class ContextPruner:
    protected_tokens: set[str] = field(default_factory=set)

    def register_bindings(self, live_calls: Iterable[LiveCall]) -> None:
        for call in live_calls:
            self.protected_tokens |= call.arg_tokens

    def _span_is_load_bearing(self, span: Span) -> bool:
        # A span is load-bearing if it is the unique textual source of any
        # token a live call will dereference -- regardless of relevance score.
        return any(tok in span.text for tok in self.protected_tokens)

    def apply_prune(self, spans: list[Span], evict_ids: set[str]) -> list[Span]:
        kept: list[Span] = []
        for span in spans:
            if span.span_id in evict_ids:
                if self._span_is_load_bearing(span):
                    raise BindingInvariantViolation(
                        f"refusing eviction of {span.span_id}: contains a token "
                        f"bound by a live call (relevance={span.relevance:.2f}); "
                        f"pin the binding or defer the prune until quiescent"
                    )
                continue
            kept.append(span)
        return kept


def run_pruning_pass(pruner: ContextPruner, spans: list[Span],
                     model_evict_ids: set[str]) -> list[Span]:
    try:
        return pruner.apply_prune(spans, model_evict_ids)
    except BindingInvariantViolation as exc:
        # Defer the offending eviction; keep the span, log, let model re-propose.
        offending = {s.span_id for s in spans
                     if s.span_id in model_evict_ids and pruner._span_is_load_bearing(s)}
        deferred = model_evict_ids - offending
        print(f"[deferred prune] {exc}")
        return pruner.apply_prune(spans, deferred)
