# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-hierarchical-summarization-has-silently-severed-retrieval-anchored-recall-guarantees-under-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-hierarchical-summarization-has-silently-severed-retrieval-anchored-recall-guarantees-under-budget.warrant.json
# Markdown SHA-256:   214cf96727170c2d00c47dd5ce555182d8566b16d08aba2890435ccdb7444239
# Code AST SHA-256:   e4f06f5d228836d91028f694a2030a07cc4d931775d939b3039608c152cfd07b
# Verified Classes:   RecallContractViolation, Span, SummaryNode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class RecallContractViolation(RuntimeError):
    """Raised when hierarchical compaction severs retrieval-anchored recall."""
    pass


@dataclass
class Span:
    span_id: str
    content: str
    content_hash: str = ""

    def __post_init__(self):
        if not self.content_hash:
            self.content_hash = hashlib.sha256(self.content.encode()).hexdigest()


@dataclass
class SummaryNode:
    node_id: str
    prose: str
    anchors: dict = field(default_factory=dict)  # span_id -> content_hash at write time
    children: list = field(default_factory=list)


def merge_children_into_parent(
    parent: SummaryNode,
    children: list,
    anchor_budget: int,
    span_store: dict,
) -> SummaryNode:
    """Fold children into parent, preserving the recall contract.

    Invariants enforced:
      1. anchors(parent) superset of union(children.anchors)  -- monotonic union
      2. anchor payload fits anchor_budget (reserved OUTSIDE prose budget)
      3. every anchor dereferences to a hash-matching span      -- no poisoned anchors
    """
    union = {}
    for child in children:
        for span_id, h in child.anchors.items():
            union[span_id] = h

    if len(union) > anchor_budget:
        # Truncating anchors here is the silent-severance bug. Refuse and split.
        raise RecallContractViolation(
            f"anchor union size {len(union)} exceeds reserved anchor budget "
            f"{anchor_budget}; split the cluster instead of truncating anchors"
        )

    parent.anchors = union
    parent.children = [c.node_id for c in children]

    # Verify every anchor dereferences to a hash-matching span.
    for span_id, expected_hash in parent.anchors.items():
        span = span_store.get(span_id)
        if span is None:
            raise RecallContractViolation(
                f"anchor {span_id} does not resolve to any span (dead anchor)"
            )
        if span.content_hash != expected_hash:
            raise RecallContractViolation(
                f"poisoned anchor {span_id}: hash {span.content_hash[:8]} != "
                f"recorded {expected_hash[:8]}; merge step reassigned anchor"
            )
    return parent


def assert_reachability(root: SummaryNode, summarized_span_count: int) -> float:
    """Return reachable/summarized ratio; must be >= 1.0 for intact recall."""
    reachable = len(root.anchors)
    ratio = reachable / summarized_span_count if summarized_span_count else 1.0
    if ratio < 1.0:
        raise RecallContractViolation(
            f"reachability ratio {ratio:.2f} < 1.0 at root {root.node_id}: "
            f"{summarized_span_count - reachable} spans summarized but unreachable"
        )
    return ratio
