# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-hierarchical-summarization-drift-when-rehydrated-retrieval-citations-resolve-against-a-stale-leaf-index.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-hierarchical-summarization-drift-when-rehydrated-retrieval-citations-resolve-against-a-stale-leaf-index.warrant.json
# Markdown SHA-256:   9ab3c782c799dc28ab9636449356f3648627262b80e5f22d0b61e5a680b4f6c5
# Code AST SHA-256:   70013818415f72247d841b1cdc1e6864176fcb47be782c1a308fa179db371a3a
# Verified Classes:   RehydrationDriftError, Citation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

class RehydrationDriftError(RuntimeError):
    """Raised when a summary citation resolves to a span whose content hash
    does not match the hash recorded at summary-authoring time."""
    pass

@dataclass(frozen=True)
class Citation:
    span_id: str
    content_hash: str  # recorded at authoring time

def _hash(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()

def rehydrate(citation: Citation, leaf_index: dict[str, str], *,
              index_reid_watermark: int, summary_watermark: int) -> str:
    # If the index has not been re-IDed since authoring, opaque IDs are safe.
    if index_reid_watermark <= summary_watermark:
        span = leaf_index.get(citation.span_id)
        if span is None:
            raise RehydrationDriftError(
                f"citation {citation.span_id} unresolved on stable index")
        return span

    # Index was remapped after authoring: ID may be recycled. Verify identity.
    span = leaf_index.get(citation.span_id)
    if span is None:
        raise RehydrationDriftError(
            f"citation {citation.span_id} evicted after re-ID pass")
    if _hash(span) != citation.content_hash:
        raise RehydrationDriftError(
            f"citation {citation.span_id} resolved to foreign span "
            f"(recycled ID); expected hash {citation.content_hash[:12]}, "
            f"got {_hash(span)[:12]}")
    return span
