# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-provenance-tracked-forget-as-a-tombstone-rather-than-a-deletion-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-provenance-tracked-forget-as-a-tombstone-rather-than-a-deletion-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   370a8bcd8ec714a40265c19ea1a60e7e2b4a21f096dac6c42196ec4dfbf546c1
# Code AST SHA-256:   d78e7f64ba690c126a497319e30a216b38e56886f78aa990426b420c2ff76ae4
# Verified Classes:   ProvenanceErasureError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceErasureError(RuntimeError):
    """Raised when a forget would leave a live descendant citing an erased source."""
    pass


def forget_with_provenance(store, index, provenance, record_id, legal_hold=False):
    if legal_hold:
        raise ProvenanceErasureError(
            f"refusing forget on {record_id}: legal hold active, retention required"
        )

    descendants = provenance.transitive_descendants(record_id)
    if not descendants:
        store.delete(record_id)
        index.remove(record_id)
        return "hard_deleted"

    # Every descendant must be classified before any payload is destroyed.
    plan = []
    for d in descendants:
        remaining = provenance.sources_excluding(d, record_id)
        if remaining:
            plan.append((d, "re_derive", remaining))
        else:
            plan.append((d, "taint", None))

    # Fail closed if any descendant cannot be resolved.
    unresolved = [d for d, action, _ in plan if action == "taint" and d.payload is None]
    if unresolved:
        raise ProvenanceErasureError(
            f"cannot taint descendants {unresolved}: payload already missing, "
            f"erasure of {record_id} would launder provenance"
        )

    # Atomic cascade: re-derive where possible, taint the rest, then tombstone.
    for d, action, sources in plan:
        if action == "re_derive":
            store.rewrite(d, derive_from=sources)
            provenance.replace_edges(d, sources)
        else:
            store.set_state(d, state="tainted", confidence="unverified")
            index.demote(d, priority="suppressed")
            provenance.convert_to_dangling_citation(d, cited=record_id)

    store.erase_payload(record_id)          # payload gone
    index.remove(record_id)                 # embedding gone
    provenance.tombstone(record_id)         # node survives, opaque
    return "tombstoned_with_taint_cascade"
