# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hierarchical-auto-compaction-from-silently-promoting-a-lossy-leaf-summary-into-the-durable-semantic-tier.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hierarchical-auto-compaction-from-silently-promoting-a-lossy-leaf-summary-into-the-durable-semantic-tier.warrant.json
# Markdown SHA-256:   405e031e241da901a191569614cc52b6aa740b5e26e8782b15149cb8a8724048
# Code AST SHA-256:   71fdade453368481914fb0dab8a64b8e431c45a671b650afb774db6d6a0719bc
# Verified Classes:   CompactionPromotionError, SummaryNode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionPromotionError(RuntimeError):
    """Raised when a summary is about to be promoted past its fidelity bound."""


@dataclass
class SummaryNode:
    tier: str                      # "leaf" | "intermediate" | "root"
    local_fidelity: float          # scored against source (leaf) or children (parent)
    children: list["SummaryNode"] = field(default_factory=list)
    atomic_fact_recall: float = 0.0   # recall of numerics/IDs/negations vs source
    residual_index_present: bool = False

    def effective_fidelity(self) -> float:
        if not self.children:
            return self.local_fidelity
        child_bound = min(c.effective_fidelity() for c in self.children)
        return self.local_fidelity * child_bound


PROMOTION_FIDELITY_FLOOR = 0.90
ATOMIC_RECALL_FLOOR = 0.95


def promote_to_semantic_tier(node: SummaryNode) -> None:
    """Gate promotion on the propagated lower bound, not the local score."""
    if node.tier != "root":
        raise CompactionPromotionError(
            f"only root may be promoted, got tier={node.tier!r}"
        )

    bound = node.effective_fidelity()
    if bound < PROMOTION_FIDELITY_FLOOR:
        raise CompactionPromotionError(
            f"propagated fidelity {bound:.3f} < floor {PROMOTION_FIDELITY_FLOOR}; "
            f"local root score {node.local_fidelity:.3f} is laundering a lossy leaf"
        )

    if node.atomic_fact_recall < ATOMIC_RECALL_FLOOR:
        raise CompactionPromotionError(
            f"atomic-fact recall {node.atomic_fact_recall:.3f} < "
            f"{ATOMIC_RECALL_FLOOR}; gist preserved but numerics/IDs dropped"
        )

    if not node.residual_index_present:
        raise CompactionPromotionError(
            "no residual index: abstraction-tier promotion would discard "
            "recoverable atomic facts; refuse and keep source reachable"
        )

    # Promotion is safe: bound holds, atomic facts recoverable, residual reachable.
    return None
