# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-lossy-summarization-invariant-and-the-mid-horizon-amnesia-cliff.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-lossy-summarization-invariant-and-the-mid-horizon-amnesia-cliff.warrant.json
# Markdown SHA-256:   36a7b1e46e290b389d015fedfe4c58f956b0661dfe2c88e79e732f31a9c8f2d2
# Code AST SHA-256:   ff71a3f9881b1429073685a879c1e04e66385d3867032d509fa4dadd733acb9a
# Verified Classes:   UnrecoverableBindingError, Binding, FoldSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnrecoverableBindingError(RuntimeError):
    """Raised when compaction would fold a live binding that has no re-acquisition path."""
    pass


@dataclass
class Binding:
    name: str
    value: str
    reacquire_proc: Optional[str]  # None => unrecoverable if folded without pinning
    truth_status_load_bearing: bool = False  # e.g. negation / completion polarity


@dataclass
class FoldSpan:
    span_id: str
    bindings: list[Binding] = field(default_factory=list)


def decide_compaction(span: FoldSpan, pinned_ledger: set[str]) -> str:
    """
    Returns one of: 'fold', 'pin_then_fold', 'refuse'.
    Enforces the re-acquisition invariant before any lossy summarization.
    """
    unrecoverable = [
        b for b in span.bindings
        if b.reacquire_proc is None and b.name not in pinned_ledger
    ]

    # Truth-status of a live obligation cannot survive a digest -> hard refuse.
    for b in unrecoverable:
        if b.truth_status_load_bearing:
            raise UnrecoverableBindingError(
                f"span {span.span_id}: binding '{b.name}' carries load-bearing "
                f"truth-status with no re-acquisition path; summarization would "
                f"flip or drop its polarity. Refusing to compact."
            )

    if unrecoverable:
        # Must pin verbatim into the obligations ledger before folding.
        return "pin_then_fold"

    return "fold"


def compact(span: FoldSpan, pinned_ledger: set[str]) -> str:
    decision = decide_compaction(span, pinned_ledger)
    if decision == "refuse":
        # decide_compaction already raised; defensive re-raise for clarity.
        raise UnrecoverableBindingError(f"span {span.span_id}: compaction refused")
    if decision == "pin_then_fold":
        for b in span.bindings:
            if b.reacquire_proc is None and b.name not in pinned_ledger:
                pinned_ledger.add(b.name)  # verbatim value must be stored by caller
    return f"compacted:{span.span_id}:{decision}"


# --- trace of the observed failure ---
span_22 = FoldSpan(
    span_id="turns_1_28",
    bindings=[
        Binding(name="rsv_7f3a", value="rsv_7f3a", reacquire_proc=None),
    ],
)
ledger: set[str] = set()

# Correct behavior: pin the identifier rather than paraphrase it.
print(compact(span_22, ledger))  # compacted:turns_1_28:pin_then_fold
assert "rsv_7f3a" in ledger

# Hard-refusal case: a load-bearing open obligation.
span_open = FoldSpan(
    span_id="turns_29_40",
    bindings=[
        Binding(name="peer_confirmed", value="NOT confirmed",
                reacquire_proc=None, truth_status_load_bearing=True),
    ],
)
try:
    compact(span_open, ledger)
except UnrecoverableBindingError as e:
    print("halted:", e)
