# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-loses-the-rehydration-path-after-hierarchical-summarization-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-loses-the-rehydration-path-after-hierarchical-summarization-compaction.warrant.json
# Markdown SHA-256:   bf2535dd7eb803b4abe174a992c00522d7c0466ea21a38e955c18ef86264746b
# Code AST SHA-256:   b11a8505e0ec090fbace01949e5ce45f17c99a2c4f691fa7c267edf2d9d31bb8
# Verified Classes:   CompactionIntegrityError, SpanHandle, SummaryNode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field


class CompactionIntegrityError(RuntimeError):
    """Raised when a summary node's handle set or hash fails verification."""


@dataclass(frozen=True)
class SpanHandle:
    span_id: str
    content_sha: str  # hex digest of the raw span bytes


@dataclass
class SummaryNode:
    text: str
    children: list["SummaryNode"] = field(default_factory=list)
    # Handles are DERIVED by code, never generated by the summarizer LLM.
    handles: list[SpanHandle] = field(default_factory=list)


def derive_handles(node: SummaryNode) -> list[SpanHandle]:
    """Parent handle set = deduplicated union of children. Deterministic."""
    seen: dict[str, SpanHandle] = {}
    for child in node.children:
        for h in child.handles:
            seen.setdefault(h.span_id, h)
    return list(seen.values())


def verify_node(node: SummaryNode, store: dict[str, bytes]) -> None:
    derived = {h.span_id for h in derive_handles(node)}
    declared = {h.span_id for h in node.handles}

    missing = derived - declared
    if missing:
        raise CompactionIntegrityError(
            f"handle-set monotonicity violated: parent dropped {sorted(missing)}"
        )

    for h in node.handles:
        raw = store.get(h.span_id)
        if raw is None:
            raise CompactionIntegrityError(f"dangling handle: {h.span_id}")
        actual = hashlib.sha256(raw).hexdigest()
        if actual != h.content_sha:
            # Fail closed. Never fall back to summary text.
            raise CompactionIntegrityError(
                f"handle-referent integrity violated at {h.span_id}: "
                f"declared {h.content_sha[:12]} actual {actual[:12]}"
            )


def rehydrate(node: SummaryNode, store: dict[str, bytes], span_id: str) -> bytes:
    verify_node(node, store)
    handle = next((h for h in node.handles if h.span_id == span_id), None)
    if handle is None:
        raise CompactionIntegrityError(
            f"span {span_id} not reachable from summary; reasoning would be lossy"
        )
    return store[handle.span_id]
