# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-hierarchical-summarization-checkpoint-has-crossed-the-reversible-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-hierarchical-summarization-checkpoint-has-crossed-the-reversible-compaction-boundary.warrant.json
# Markdown SHA-256:   29f7242b18b73d1d2c5f983785d2e38a9e842175c9f988e12b0f0d56a6b7bb50
# Code AST SHA-256:   4349fbacbdb64d847e32b2ce621e9daa1739204acd491800d7748eab3f6b19bf
# Verified Classes:   IrreversibleCompactionError, SummaryNode, SpanStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class IrreversibleCompactionError(RuntimeError):
    """Raised when a summary would become the sole durable copy of a span
    while still containing an unbound reference to that span's content."""
    pass


@dataclass
class SummaryNode:
    text: str
    source_span_hash: Optional[str]
    dangling_refs: list[str] = field(default_factory=list)


@dataclass
class SpanStore:
    live: dict[str, str] = field(default_factory=dict)

    def evict(self, span_hash: str) -> None:
        self.live.pop(span_hash, None)

    def resolvable(self, span_hash: str) -> bool:
        return span_hash in self.live


def commit_checkpoint(
    node: SummaryNode,
    store: SpanStore,
    plan_entities: set[str],
    task_complete: bool,
) -> None:
    """Persist a summary node and release its source span, enforcing the
    reversible-compaction invariant.

    The boundary is crossed if, at eviction time, the node still refers to
    content that lives only in the span being evicted AND that content is
    load-bearing for an unresolved subgoal.
    """
    load_bearing = [r for r in node.dangling_refs if r in plan_entities]

    if load_bearing and not task_complete:
        # The summary delegates a load-bearing fact to a span we are about to
        # delete. Eviction here is irreversible: the fact is gone.
        if node.source_span_hash and not store.resolvable(node.source_span_hash):
            raise IrreversibleCompactionError(
                f"summary for span {node.source_span_hash!r} contains unbound "
                f"references {load_bearing!r} that are load-bearing for "
                f"unresolved subgoals; source span is already evicted"
            )
        # Span still live: refuse to evict, force re-summarization with the
        # value inlined rather than delegating to a soon-to-die span.
        raise IrreversibleCompactionError(
            f"refusing to evict span {node.source_span_hash!r}: summary "
            f"delegates load-bearing facts {load_bearing!r} without carrying "
            f"them; re-summarize with values inlined before release"
        )

    # Safe to persist and release: either self-contained or task is done.
    if node.source_span_hash:
        store.evict(node.source_span_hash)


def resume_from_checkpoint(
    node: SummaryNode,
    store: SpanStore,
    plan_entities: set[str],
) -> None:
    """On cold-start resume, verify the checkpoint has not silently crossed
    the boundary: a dangling reference whose antecedent is unrecoverable
    means the reconstructed state is a plausible fiction."""
    for ref in node.dangling_refs:
        if ref in plan_entities and (
            node.source_span_hash is None
            or not store.resolvable(node.source_span_hash)
        ):
            raise IrreversibleCompactionError(
                f"checkpoint references {ref!r} but antecedent is unrecoverable; "
                f"resumed state would be a confident reconstruction, not a restore"
            )
