# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-its-own-context-lossy-self-editing-and-the-irreversibility-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-prune-its-own-context-lossy-self-editing-and-the-irreversibility-boundary.warrant.json
# Markdown SHA-256:   e0188e6be893408a51761dfcf381961715e361eaba9dc930814b1a2010946af5
# Code AST SHA-256:   74778bf93bd947c8330fec16d04a9958f70173eaad6a0fd925ddb2334410bf7d
# Verified Classes:   IrreversiblePruneError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class IrreversiblePruneError(RuntimeError):
    """Raised when a self-edit would destroy the only copy of a span."""
    pass


class Span:
    def __init__(self, span_id, content, external_handle=None, handle_pinned=False):
        self.span_id = span_id
        self.content = content
        self.external_handle = external_handle      # addressable in durable store?
        self.handle_pinned = handle_pinned          # handle immune to scoring?


def prune_span(span, scorer_rank, budget_pressure):
    """
    Gate a model-driven prune. Returns a disposition string.
    Raises IrreversiblePruneError when the edit would be lossy.
    """
    backed = span.external_handle is not None
    addressable_after = backed and span.handle_pinned

    if addressable_after:
        # Safe: reversible cache eviction.
        return "pruned_reversible"

    if backed and not span.handle_pinned:
        # Handle exists but could itself be scored away: pin first, then prune.
        span.handle_pinned = True
        return "handle_pinned_then_pruned"

    # No external copy: any rewrite is a destructive write.
    if budget_pressure and scorer_rank < 0.2:
        raise IrreversiblePruneError(
            f"span {span.span_id!r} has no durable handle; "
            f"refusing in-place rewrite under budget pressure "
            f"(rank={scorer_rank:.2f}). Promote to external store or "
            f"compact a different span."
        )

    # Low pressure and unbacked: tolerate, but never rewrite in place.
    return "retained_unbacked"
