# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-pruning-when-a-self-editing-context-window-can-delete-its-own-retention-evidence.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-pruning-when-a-self-editing-context-window-can-delete-its-own-retention-evidence.warrant.json
# Markdown SHA-256:   5d33cb0f214a9a11cf56750a17aa37bea73e7792d1624d34296a2bd8741dcf8b
# Code AST SHA-256:   cc450fafba9b4532bc24ac803c805b30feeb0b92490dd79038a32dcc4c49d7ed
# Verified Classes:   PruningOracleViolation, ObligationLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class PruningOracleViolation(RuntimeError):
    """Raised when a prune pass would evict evidence backing an open obligation."""
    pass


class ObligationLedger:
    """Pinned, non-evictable set of deferred task obligations."""

    def __init__(self):
        self._entries = {}  # obligation_id -> predicate description

    def add(self, obligation_id: str, predicate: str):
        self._entries[obligation_id] = predicate

    def resolve(self, obligation_id: str):
        self._entries.pop(obligation_id, None)

    def open_obligations(self):
        return dict(self._entries)


def admissible_prune(evict_span_ids, span_to_obligations, ledger):
    """
    A prune pass is admissible only if no evicted span is the sole
    remaining backing evidence for an open obligation.
    """
    open_ids = set(ledger.open_obligations())
    stranded = []
    for span_id in evict_span_ids:
        backed = span_to_obligations.get(span_id, set())
        for ob_id in backed & open_ids:
            # count remaining backing spans for this obligation
            remaining = [
                s for s, obs in span_to_obligations.items()
                if ob_id in obs and s not in evict_span_ids
            ]
            if not remaining:
                stranded.append((span_id, ob_id))

    if stranded:
        raise PruningOracleViolation(
            f"prune would strand open obligations: {stranded}; "
            f"retain these spans or re-acquire evidence before eviction"
        )
    return True


def run_prune_pass(model_proposed_evictions, span_to_obligations, ledger):
    try:
        admissible_prune(model_proposed_evictions, span_to_obligations, ledger)
    except PruningOracleViolation as e:
        # fall back to retaining stranded spans; surface loudly, never silently drop
        return {"applied": [], "rejected": model_proposed_evictions, "reason": str(e)}
    return {"applied": model_proposed_evictions, "rejected": [], "reason": None}
