# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-hierarchical-context-compaction-when-a-fidelity-loss-budget-is-exhausted-mid-summarization.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-hierarchical-context-compaction-when-a-fidelity-loss-budget-is-exhausted-mid-summarization.warrant.json
# Markdown SHA-256:   261effe146e7f8e029c9350daabd04231ee13be12d10a48d83a464210c2a6db2
# Code AST SHA-256:   f4772e133351d4771f5c1efad1674def0331fbb967e1f84583e7fed8e6f69ba1
# Verified Classes:   FidelityBudgetExhausted, SummaryNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

ANCHOR_CLASSES = ("identifier", "numeric", "negation", "tool_arg")


class FidelityBudgetExhausted(RuntimeError):
    """Raised when a proposed summary node would breach the fidelity-loss budget
    against origin sources, or would drop a protected anchor."""
    pass


@dataclass
class SummaryNode:
    node_id: str
    rendered: str
    origin_sources: list[str]          # original turns this node transitively replaces
    claimed_anchors: dict[str, set]    # anchor class -> set of anchor literals preserved


def _anchors_in(sources: Iterable[str]) -> dict[str, set]:
    """Extract discrete anchors from origin text. Real impl uses NER + numeric parse;
    here we keep it explicit and conservative."""
    import re
    found = {k: set() for k in ANCHOR_CLASSES}
    for s in sources:
        found["numeric"].update(re.findall(r"\b\d+\b", s))
        found["identifier"].update(re.findall(r"\b[a-z_]+_[a-z_]+\b", s))
        for neg in ("not", "never", "do not", "must not"):
            if neg in s.lower():
                found["negation"].add(neg)
    return found


def check_node(node: SummaryNode, budget: float, current_loss: float) -> float:
    """Validate a proposed node against ORIGIN sources (not its parent).
    Returns the new cumulative loss. Raises on any breach."""
    origin_anchors = _anchors_in(node.origin_sources)

    # Anchor-loss boundary: hard stop, independent of aggregate budget.
    for cls in ANCHOR_CLASSES:
        missing = origin_anchors[cls] - node.claimed_anchors.get(cls, set())
        if missing:
            raise FidelityBudgetExhausted(
                f"node {node.node_id} dropped {cls} anchors {sorted(missing)} "
                f"from origin; pin these facts and halt compaction"
            )

    # Budget-exhaustion boundary: origin-anchored delta, not parent diff.
    total_anchors = sum(len(v) for v in origin_anchors.values()) or 1
    kept = sum(len(node.claimed_anchors.get(c, set())) for c in ANCHOR_CLASSES)
    node_loss = 1.0 - (kept / total_anchors)
    new_loss = max(current_loss, node_loss)  # frontier max, geometric-aware
    if new_loss >= budget:
        raise FidelityBudgetExhausted(
            f"node {node.node_id} origin-anchored loss {new_loss:.3f} "
            f"breaches budget {budget:.3f}; halt and pin remainder"
        )
    return new_loss


def compact_layer(nodes: list[SummaryNode], budget: float, current_loss: float = 0.0) -> float:
    loss = current_loss
    for n in nodes:
        loss = check_node(n, budget, loss)
    return loss
