# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-the-token-it-just-decided-to-keep-pruning-marker-reclamation-and-the-salience-commitment-race-in-self-editing-context-wind.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-the-token-it-just-decided-to-keep-pruning-marker-reclamation-and-the-salience-commitment-race-in-self-editing-context-wind.warrant.json
# Markdown SHA-256:   8ac1a69c9b979dd7225f4a6252dd4fa954967e9cd165efce5f9f77a58485be38
# Code AST SHA-256:   0f1bd9d7b78fc61d12885fc3123b727a32f87b212d525f3b4fb490df1c0f25df
# Verified Classes:   OrphanedProtectionError, ProtectionLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OrphanedProtectionError(RuntimeError):
    """Raised when a pruner is about to evict a span whose protection record
    was removed in an earlier pass without a corresponding release."""
    pass


class ProtectionLedger:
    """External, append-only store of protection claims. The pruner reads it
    but never mutates it; only the model's explicit release can retire a claim."""

    def __init__(self):
        self._claims = {}          # span_id -> {"reason": str, "alive": bool}
        self._pruned_markers = set()

    def claim(self, span_id: str, reason: str) -> None:
        self._claims[span_id] = {"reason": reason, "alive": True}

    def release(self, span_id: str) -> None:
        if span_id in self._claims:
            self._claims[span_id]["alive"] = False

    def record_marker_eviction(self, span_id: str) -> None:
        # A KEEP marker for this span was itself pruned this pass.
        self._pruned_markers.add(span_id)

    def is_protected(self, span_id: str) -> bool:
        c = self._claims.get(span_id)
        return bool(c and c["alive"])


def prune_pass(spans, ledger: ProtectionLedger, threshold: float = 0.30):
    survivors, evicted = [], []
    for span in spans:
        if ledger.is_protected(span.id):
            survivors.append(span)
            continue
        # Guardrail: never silently evict a span whose marker was already
        # reclaimed. This is the two-pass orphan condition.
        if span.id in ledger._pruned_markers and span.id in ledger._claims:
            raise OrphanedProtectionError(
                f"span {span.id!r} lost its KEEP marker in a prior pass and is "
                f"now unprotected; refusing silent eviction. "
                f"Original reason: {ledger._claims[span.id]['reason']!r}"
            )
        if span.salience < threshold:
            evicted.append(span)
        else:
            survivors.append(span)
    return survivors, evicted
