# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-hierarchical-summarization-triggers-that-destroy-the-evidence-a-downstream-verifier-will-need.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-hierarchical-summarization-triggers-that-destroy-the-evidence-a-downstream-verifier-will-need.warrant.json
# Markdown SHA-256:   e9c8e48c3860f469673a5a9a38feda8b9fe8a0cbfde9110da03ee1c59dacff7f
# Code AST SHA-256:   cdd157cc049264d856a6a41e7ccdd58b75a84cad170ca14ad4a0ce4af9e443e4
# Verified Classes:   CompactionInvariantViolation, Span, ObligationLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionInvariantViolation(RuntimeError):
    """Raised when a hierarchical compaction fold would destroy evidence
    still required to discharge an open verification obligation."""
    pass


@dataclass
class Span:
    span_id: str
    tokens: list[str]
    open_obligations: set[str] = field(default_factory=set)  # claims a verifier may re-check
    provenance_handle: Optional[str] = None  # external addressable copy, if pinned


@dataclass
class ObligationLedger:
    # never summarized; survives every compaction level by construction
    open: dict[str, str] = field(default_factory=dict)  # obligation -> provenance handle

    def pin(self, span: Span) -> str:
        handle = f"store://span/{span.span_id}"
        for ob in span.open_obligations:
            self.open[ob] = handle
        span.provenance_handle = handle
        return handle

    def discharge(self, obligation: str) -> None:
        self.open.pop(obligation, None)


def maybe_compact(span: Span, utilization: float, threshold: float,
                  ledger: ObligationLedger) -> Optional[str]:
    """Return a folded summary id, or None if the fold is refused.

    The invariant: a span may be folded only if it carries no open
    obligations, OR every open obligation is pinned to an external
    addressable handle recorded in the ledger.
    """
    if utilization < threshold:
        return None  # no trigger; nothing to do

    if span.open_obligations:
        pinned = all(ledger.open.get(ob) is not None for ob in span.open_obligations)
        if not pinned:
            # Refuse: folding here would launder open uncertainty into a
            # coherent-but-false summary at the next level.
            raise CompactionInvariantViolation(
                f"refusing to fold span {span.span_id}: "
                f"open obligations {sorted(span.open_obligations)} are unpinned; "
                f"checkpoint-and-pin before compaction"
            )
        # Obligations pinned: the summary may carry handles, not claims.
        return f"summary/{span.span_id}?handles={len(span.open_obligations)}"

    # No open obligations: safe capacity operation.
    return f"summary/{span.span_id}"


def compact_or_pin(span: Span, utilization: float, threshold: float,
                   ledger: ObligationLedger) -> str:
    try:
        result = maybe_compact(span, utilization, threshold, ledger)
    except CompactionInvariantViolation:
        # Third transition: pin, then fold. Never exhaust, never launder.
        ledger.pin(span)
        result = maybe_compact(span, utilization, threshold, ledger)
    if result is None:
        return "no-op"
    return result
