# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-provenance-tagged-memory-deletion-against-tombstone-resurrection-during-targeted-forgetting.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-provenance-tagged-memory-deletion-against-tombstone-resurrection-during-targeted-forgetting.warrant.json
# Markdown SHA-256:   75f2ec13d012b3d757ce0da0d866674ddb1b8d1fce1a74f430af9da7f542799b
# Code AST SHA-256:   fb1723b6758e8ea8d085faaf8970a2922afaa147ceb8fa3b4483ebe00b6e3e43
# Verified Classes:   ProvenanceClosureViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceClosureViolation(RuntimeError):
    """Raised when a forget would leave live entries reachable from the tombstoned id."""
    pass


def targeted_forget(store, target_id, max_reachable=256):
    # Enumerate every live entry whose provenance transitively reaches target_id.
    reachable = store.reverse_provenance_closure(target_id)
    if len(reachable) > max_reachable:
        # Cannot close the closure within the transaction budget: open forgetting.
        store.write_tombstone(target_id)
        store.mark_tainted(reachable)
        store.set_flag("forget_pending", True)
        return {"status": "open", "tainted": sorted(reachable)}

    unrewritten = []
    for entry_id in reachable:
        entry = store.get(entry_id)
        if entry is None:
            continue
        # Rewrite drops the dangling reference and re-distills content.
        rewritten = store.redistill(entry, drop_provenance={target_id})
        if rewritten.still_depends_on(target_id):
            unrewritten.append(entry_id)

    if unrewritten:
        # Tombstone is written but closure is not closed: refuse to claim success.
        store.write_tombstone(target_id)
        store.mark_tainted(unrewritten)
        raise ProvenanceClosureViolation(
            f"forget({target_id}) left {len(unrewritten)} entries still depending on it: "
            f"{sorted(unrewritten)}; retrieval must gate on forget_pending"
        )

    store.write_tombstone(target_id)
    store.delete(target_id)
    store.delete_from_index(target_id)
    store.set_flag("forget_pending", False)
    return {"status": "closed", "rewritten": sorted(reachable)}
