# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-hierarchical-summarization-has-silently-violated-lossless-recall-guarantees-under-auto-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-hierarchical-summarization-has-silently-violated-lossless-recall-guarantees-under-auto-compaction.warrant.json
# Markdown SHA-256:   2c238a6c78116285ce89ff366596b37e2a0a6c16153d451b336e2a22a2731c82
# Code AST SHA-256:   54bb5777a1ce311b46de00b0194858cc0c18ca6e6152569d8a88722645c47d68
# Verified Classes:   LosslessRecallViolation, SaturationTripwire, SummaryNode, CompactionController
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class LosslessRecallViolation(RuntimeError):
    """Raised when a parent summary would unlink children whose salient
    atoms are not reconstructable from the parent or the facts ledger."""
    pass


class SaturationTripwire(RuntimeError):
    """Raised when a parent summary is at eviction pressure with full
    leaf coverage, meaning coverage metadata cannot be trusted."""
    pass


ATOM_PATTERNS = [
    re.compile(r"\b\d+(?:\.\d+)?\b"),          # numbers / quantities
    re.compile(r"\bnot\b|\bnever\b|\bdo not\b", re.I),  # negations
    re.compile(r"`[^`]+`"),                     # code identifiers
    re.compile(r'"[^"]{2,}"'),                  # quoted strings
]


def extract_atoms(text: str) -> set[str]:
    atoms: set[str] = set()
    for pat in ATOM_PATTERNS:
        for m in pat.findall(text):
            atoms.add(m.strip().lower())
    return atoms


@dataclass
class SummaryNode:
    node_id: str
    text: str
    token_budget: int
    token_used: int
    covered_leaves: list[str] = field(default_factory=list)
    children: dict[str, "SummaryNode"] = field(default_factory=dict)


@dataclass
class CompactionController:
    facts_ledger: set[str] = field(default_factory=set)
    saturation_threshold: float = 0.97

    def _saturation(self, parent: SummaryNode) -> float:
        return parent.token_used / parent.token_budget

    def unlink_children(self, parent: SummaryNode) -> None:
        # Tripwire 1: eviction pressure + full coverage => metadata unreliable.
        if (
            self._saturation(parent) >= self.saturation_threshold
            and len(parent.covered_leaves) == len(parent.children)
        ):
            raise SaturationTripwire(
                f"parent {parent.node_id} at {self._saturation(parent):.3f} "
                f"saturation with {len(parent.children)}/{len(parent.children)} "
                f"leaves covered; coverage attestation cannot be trusted"
            )

        parent_atoms = extract_atoms(parent.text) | self.facts_ledger

        # Tripwire 2: pin-and-diff. Refuse to unlink any child whose
        # salient atoms are not reconstructable from parent or ledger.
        for child in parent.children.values():
            child_atoms = extract_atoms(child.text)
            missing = child_atoms - parent_atoms
            if missing:
                raise LosslessRecallViolation(
                    f"unlink of child {child.node_id} under parent "
                    f"{parent.node_id} would drop atoms {sorted(missing)}; "
                    f"retain child as pinned leaf or promote atoms to ledger"
                )

        # Only reached if every child atom is reconstructable.
        parent.children.clear()
        parent.covered_leaves = []

    def repair_subtree(self, parent: SummaryNode) -> None:
        # Corruption laundering guard: a laundered wrong value cannot be
        # patched at the leaf; the whole parent subtree must be invalidated
        # back to the last verified leaf.
        if any(a in self.facts_ledger for a in extract_atoms(parent.text)):
            # parent text overlaps ledger but children were unlinked:
            # provenance is clean, factual integrity is not.
            raise LosslessRecallViolation(
                f"parent {parent.node_id} overlaps facts ledger after child "
                f"unlink; patch would re-introduce laundered value — "
                f"invalidate subtree to last verified leaf"
            )
        parent.children.clear()
        parent.covered_leaves = []
        parent.text = ""
