# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-compaction-from-silently-destroying-recall-critical-facts.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-compaction-from-silently-destroying-recall-critical-facts.warrant.json
# Markdown SHA-256:   ca77897db358be3a3bbcd76aa4d3cae4261a679b4fe386e0c3a6ffad8d5d4fb4
# Code AST SHA-256:   40cb44b8b66f499fe66d3ecb7a3103d025904f493182652d2cdcb3e31a01f8c0
# Verified Classes:   AncestorCoverageError, Node
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AncestorCoverageError(RuntimeError):
    """Raised when an eviction would orphan content not covered by all ancestors."""
    pass


@dataclass
class Node:
    node_id: str
    level: int
    salient_entities: set[str]
    parent: Optional["Node"] = None
    children: list["Node"] = field(default_factory=list)


def ancestors(node: Node) -> list[Node]:
    chain, cur = [], node.parent
    while cur is not None:
        chain.append(cur)
        cur = cur.parent
    return chain


def verify_transitive_coverage(node: Node) -> bool:
    """Every salient entity of `node` must appear in EVERY ancestor to root."""
    anc = ancestors(node)
    if not anc:
        return False
    for entity in node.salient_entities:
        if not all(entity in a.salient_entities for a in anc):
            return False
    return True


def evict(node: Node) -> None:
    if node.parent is None:
        raise AncestorCoverageError(
            f"cannot evict root node {node.node_id}: no ancestors to carry content"
        )
    if not verify_transitive_coverage(node):
        missing = [
            a.node_id for a in ancestors(node)
            if not node.salient_entities.issubset(a.salient_entities)
        ]
        raise AncestorCoverageError(
            f"eviction of {node.node_id} would orphan entities "
            f"{sorted(node.salient_entities)}; uncovered ancestors: {missing}. "
            f"Promote to protected-fact registry or retain node."
        )
    node.parent.children.remove(node)
    node.parent = None
