# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-hierarchical-summarization-pass-as-lossy-by-construction-rather-than-lossless-by-default.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-hierarchical-summarization-pass-as-lossy-by-construction-rather-than-lossless-by-default.warrant.json
# Markdown SHA-256:   652d034c783228c3b209b87861dafdfd36319753c636ee9830a67f83a3b12ebc
# Code AST SHA-256:   2d9159f2c393f5d099e490250ff1b4fcc3e747050d572e2344da2ce20680be8f
# Verified Classes:   CompactionLossBudgetViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CompactionLossBudgetViolation(RuntimeError):
    """Raised when a summary node's pinned spans are not fully reconstructable."""
    pass


LOAD_BEARING_ATOM_PATTERNS = [
    # comparison operators (strict vs non-strict is the canonical silent mutation)
    r"(<=|>=|<|>|==|!=)",
    # identifiers
    r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b",
    # numeric bounds with units
    r"\b\d+(\.\d+)?\s*(ms|s|m|h|kb|mb|gb|%)\b",
    # negation scope markers
    r"\b(not|never|no|without|unless)\b",
]


def pin_load_bearing_spans(raw_leaf_text: str, leaf_id: str) -> dict[str, str]:
    """Extract verbatim load-bearing spans from a raw leaf. These are never summarized."""
    import re
    pinned: dict[str, str] = {}
    for pat in LOAD_BEARING_ATOM_PATTERNS:
        for i, m in enumerate(re.finditer(pat, raw_leaf_text)):
            span_id = f"{leaf_id}:{pat}:{i}"
            pinned[span_id] = m.group(0)
    return pinned


def promote_summary_node(
    summary_text: str,
    child_leaf_ids: list[str],
    anchor_store: dict[str, str],
    loss_budget: float,
    measured_loss: float,
) -> None:
    """
    Gate promotion of a summary node to a parent level.

    A node may only be promoted if:
      1. Every child leaf has at least one pinned span in the anchor store
         (provenance is non-empty).
      2. Every pinned span is verbatim-reconstructable from the anchor store
         (no paraphrase drift at the atom level).
      3. The per-node measured loss is within budget.

    The embedding-distance loss budget is a lower bound on loss, not a
    certificate of fidelity. Atom-class reconstruction is the hard gate.
    """
    if not child_leaf_ids:
        raise CompactionLossBudgetViolation(
            "summary node has no child leaves; provenance is empty and node "
            "cannot be promoted (lossless-by-default assumption is invalid)"
        )

    missing_provenance = [lid for lid in child_leaf_ids
                          if not any(sid.startswith(f"{lid}:") for sid in anchor_store)]
    if missing_provenance:
        raise CompactionLossBudgetViolation(
            f"child leaves {missing_provenance} have no pinned spans in anchor "
            f"store; anchor is contaminated or spans were never frozen at leaf time"
        )

    # Atom-class reconstruction check: every pinned span must appear verbatim
    # in the anchor store AND must be representable in the summary's provenance.
    # We do not require the span to appear in summary_text (summaries paraphrase),
    # but we require the anchor to be retrievable so future steps can re-expand it.
    unreconstructable = []
    for span_id, span_value in anchor_store.items():
        leaf_prefix = span_id.split(":")[0]
        if leaf_prefix in child_leaf_ids and anchor_store.get(span_id) != span_value:
            unreconstructable.append(span_id)

    if unreconstructable:
        raise CompactionLossBudgetViolation(
            f"pinned spans {unreconstructable} are not verbatim-reconstructable "
            f"from anchor store; atom-level drift detected (likely paraphrase "
            f"mutation of comparison operator, identifier, or negation scope)"
        )

    if measured_loss > loss_budget:
        raise CompactionLossBudgetViolation(
            f"per-node measured loss {measured_loss:.4f} exceeds budget "
            f"{loss_budget:.4f}; node must be re-summarized or split before promotion"
        )


def compact_hierarchical(context_leaves: dict[str, str]) -> dict[str, str]:
    """Run a hierarchical compaction pass with atom-pinning enforced at leaf time."""
    anchor_store: dict[str, str] = {}
    for leaf_id, raw_text in context_leaves.items():
        pinned = pin_load_bearing_spans(raw_text, leaf_id)
        anchor_store.update(pinned)

    # ... leaf/section/root summarization happens here, producing summary_text ...

    # Gate every summary node on provenance + atom reconstruction + per-node loss.
    # If any gate fires, the pass is rejected and the instance must retry at a
    # finer granularity rather than promoting a lossy node.
    summary_text = "<placeholder for actual summary>"
    measured_loss = 0.0  # placeholder for actual per-node loss
    promote_summary_node(
        summary_text=summary_text,
        child_leaf_ids=list(context_leaves.keys()),
        anchor_store=anchor_store,
        loss_budget=0.18,
        measured_loss=measured_loss,
    )
    return anchor_store
