# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-pruning-corruption-when-its-own-context-rewrite-policy-erases-the-evidence-needed-to-validate-the-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-pruning-corruption-when-its-own-context-rewrite-policy-erases-the-evidence-needed-to-validate-the-rewrite.warrant.json
# Markdown SHA-256:   f3a8a17693613465849d1c8bad33e1c6deb19d7d4c7a24fb4d21a982ca15aee5
# Code AST SHA-256:   a707a866356e494967f5834b5329cd2cc3ea951fd6e73356c0f33a3c7e0394a0
# Verified Classes:   SpanType, Span, UnsafeCompactionError, PinnedStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SpanType(Enum):
    TRANSCRIPT = "transcript"   # re-fetchable by tool-call id
    SCRATCH = "scratch"         # disposable
    OBLIGATION = "obligation"   # prohibition / identity / schema contract


@dataclass
class Span:
    span_id: str
    span_type: SpanType
    content: str
    relevance: float
    recoverable_by_id: Optional[str] = None


class UnsafeCompactionError(RuntimeError):
    """Raised when a model-driven prune would drop an obligation without a
    pruner-immune, content-bearing record, or would truncate such a record."""


@dataclass
class PinnedStore:
    """Pruner-immune region. Not scored, not evicted, not subject to window budget."""
    obligations: dict[str, str] = field(default_factory=dict)

    def pin(self, span: Span) -> None:
        if span.span_type is not SpanType.OBLIGATION:
            raise UnsafeCompactionError(
                f"pin() called on non-obligation span {span.span_id}"
            )
        self.obligations[span.span_id] = span.content


def prune(
    buffer: list[Span],
    pinned: PinnedStore,
    eviction_log: list[tuple[str, float]],
    log_budget: int,
    threshold: float = 0.2,
) -> list[Span]:
    """Model-driven prune. Evicts spans below `threshold` relevance.

    Invariant enforced: a span may only be evicted if its loss is recoverable,
    or if it has first been promoted into the pruner-immune pinned store.
    The eviction log must never be truncated while it holds obligation records.
    """
    survivors: list[Span] = []
    pending_log: list[tuple[str, float]] = []

    for span in buffer:
        if span.relevance >= threshold:
            survivors.append(span)
            continue

        # Below threshold: decide whether eviction is safe.
        if span.span_type is SpanType.OBLIGATION:
            # Cannot evict an unpinned obligation — its record would be thinner
            # than its content. Promote first, then it is safe to drop the payload.
            if span.span_id not in pinned.obligations:
                raise UnsafeCompactionError(
                    f"refusing to evict unpinned obligation {span.span_id!r}: "
                    f"eviction record would lose obligation content"
                )
            pending_log.append((span.span_id, span.relevance))
            continue

        if span.recoverable_by_id is not None:
            # Loss is recoverable from an external store; log the pointer.
            pending_log.append((span.span_id, span.relevance))
            continue

        if span.span_type is SpanType.SCRATCH:
            pending_log.append((span.span_id, span.relevance))
            continue

        # TRANSCRIPT with no recoverable id: eviction is unrecoverable loss.
        raise UnsafeCompactionError(
            f"cannot evict unrecoverable transcript {span.span_id!r} "
            f"(no backing store id); relevance {span.relevance}"
        )

    # Guard the log itself: truncation must never drop an obligation record.
    projected = eviction_log + pending_log
    if len(projected) > log_budget:
        overflow = projected[: len(projected) - log_budget]
        pinned_ids = set(pinned.obligations)
        for span_id, _ in overflow:
            if span_id in pinned_ids:
                raise UnsafeCompactionError(
                    f"log truncation would drop obligation record {span_id!r}; "
                    f"refusing compaction rather than losing the comparator"
                )

    return survivors
