# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-fact-through-a-memory-tool-but-the-underlying-vector-index-retains-it-retention-policy-divergence-and-the-resu.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-fact-through-a-memory-tool-but-the-underlying-vector-index-retains-it-retention-policy-divergence-and-the-resu.warrant.json
# Markdown SHA-256:   92d78613572fb8c05b601026151fc41cafb76855b4e8d84bc3c0346cad485fa4
# Code AST SHA-256:   d1047719217f17524f3033d5211efca82c8dd7140611ae0451197b20a9d027b0
# Verified Classes:   UnlearnCascadeError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnlearnCascadeError(RuntimeError):
    """Raised when a forget operation is not closed under the derivation relation."""
    pass


def forget_with_closure(store, memory_id: str, ledger) -> dict:
    # Enumerate the derivation closure; a forget that does not do this is unsound.
    children = store.derived_children(memory_id)
    if children is None:
        raise UnlearnCascadeError(
            f"cannot compute derivation closure for {memory_id}: "
            "store does not expose parent_id index; refuse to tombstone parent alone"
        )

    ledger.tombstone(memory_id)
    for child in children:
        ledger.tombstone(child)

    # Verify no reader can still surface a child before claiming success.
    for child in children:
        probe = store.read(query=child.text, top_k=5)
        if any(hit.memory_id == child.memory_id for hit in probe):
            raise UnlearnCascadeError(
                f"derived fragment {child.memory_id} still retrievable after tombstone; "
                "read path is post-filtering or index purge has not propagated"
            )

    return {"status": "cascade_complete", "derived_count": len(children)}
