# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-hierarchical-summary-checkpoint-has-silently-dropped-a-recoverable-fact.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-hierarchical-summary-checkpoint-has-silently-dropped-a-recoverable-fact.warrant.json
# Markdown SHA-256:   309954415e85d4f70ace464040b0f4cbf97111f44a66aaf60713357179344f10
# Code AST SHA-256:   9e8c8e7d346d2429adcd1d4ed0dfc4d9834421880008914909b574aedb20fdb0
# Verified Classes:   CheckpointIntegrityError, SummaryNode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CheckpointIntegrityError(RuntimeError):
    """Raised when a hierarchical checkpoint claims recoverability it cannot honor."""


@dataclass
class SummaryNode:
    node_id: str
    level: int
    text: str
    asserted_facts: FrozenSet[str]
    child_digests: dict[str, str] = field(default_factory=dict)
    pinned: bool = False


def verify_containment(parent: SummaryNode, children: list[SummaryNode]) -> None:
    """Enforce fact-set containment: a parent may omit, never introduce."""
    child_facts: set[str] = set()
    for child in children:
        child_facts |= child.asserted_facts

    orphaned = parent.asserted_facts - child_facts
    if orphaned:
        # These facts have no leaf witness. Do NOT reconcile by deleting them.
        parent.pinned = True
        raise CheckpointIntegrityError(
            f"node {parent.node_id} asserts facts with no descendant witness: "
            f"{sorted(orphaned)}; node pinned, excluded from further lossy compression"
        )


def verify_digests(parent: SummaryNode, finalized: dict[str, str]) -> None:
    """Enforce digest monotonicity: parent must reference finalized children only."""
    for child_id, recorded in parent.child_digests.items():
        actual = finalized.get(child_id)
        if actual is None:
            raise CheckpointIntegrityError(
                f"node {parent.node_id} references unfinalized child {child_id}"
            )
        if actual != recorded:
            raise CheckpointIntegrityError(
                f"node {parent.node_id} stale: child {child_id} digest "
                f"{recorded} != finalized {actual}; ancestor must be rewritten"
            )


def rehydrate(node: SummaryNode, leaves: dict[str, SummaryNode]) -> list[str]:
    """Return facts the checkpoint can actually recover from leaf witnesses."""
    if node.pinned:
        raise CheckpointIntegrityError(
            f"node {node.node_id} is pinned (unbacked facts); "
            f"re-observe before treating its facts as recoverable"
        )
    recovered: set[str] = set()
    for leaf in leaves.values():
        recovered |= leaf.asserted_facts
    return sorted(node.asserted_facts & recovered)
