# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-compaction-irreversible-fidelity-loss-in-hierarchical-summarization-when-the-rehydration-key-set-is-not-closed-under-the.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-compaction-irreversible-fidelity-loss-in-hierarchical-summarization-when-the-rehydration-key-set-is-not-closed-under-the.warrant.json
# Markdown SHA-256:   3df59e6d7cecf42af13f05b6d17d6f6d57ea1efca794b053212326250720a0f1
# Code AST SHA-256:   38c256a5202167f5d26d52d77721c22c26f0310d05980d6792dfc3eef189bb66
# Verified Classes:   UnrecoverableCompactionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnrecoverableCompactionError(RuntimeError):
    """Raised when a compaction drop set is not closed under the key-dependency relation:
    a dropped fact has no surviving key that can retrieve it from the rehydration backend."""
    pass


def verify_key_closure(dropped_facts, retained_keys, key_dependency_fn):
    # key_dependency_fn(fact) -> set of keys that retrieve this fact
    for fact in dropped_facts:
        retrievers = key_dependency_fn(fact)
        if not (retrievers & set(retained_keys)):
            raise UnrecoverableCompactionError(
                f"Fact {fact!r} dropped with no surviving key; "
                f"candidate keys {retrievers} all elided. "
                f"Compaction would be lossy AND unrecoverable. Refuse or retain key verbatim."
            )
    return True


def rehydrate(query_keys, backend_index, summary_window):
    hits = [k for k in query_keys if k in backend_index and k in summary_window]
    if not hits:
        raise UnrecoverableCompactionError(
            f"Rehydration for keys {query_keys} resolved to zero keyed hits in the "
            f"post-compaction window. The fact may exist only in the immutable transcript. "
            f"Halt and re-read source; do NOT re-derive from narrative summary."
        )
    return backend_index[hits[0]]
