# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-tracked-memory-deletion-from-silently-corrupting-downstream-retrieval-in-read-write-forget-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-tracked-memory-deletion-from-silently-corrupting-downstream-retrieval-in-read-write-forget-tool-apis.warrant.json
# Markdown SHA-256:   5ff433d8071d44a99164080d05ce33630284232493ad9bda61a6a8baef7a58f7
# Code AST SHA-256:   3f6c80159e9f869355fe773aed0684348d9d626dafea09a3f817ea467a3765fb
# Verified Classes:   ProvenanceDeletionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceDeletionError(RuntimeError):
    """Raised when a forget() cannot achieve provenance-consistent deletion."""
    pass


def forget_record(store, record_id, retention_class, timeout_s=5.0):
    """
    Attempt provenance-consistent deletion. Refuses (raises) rather than
    returning a misleading success receipt when lineage propagation cannot
    complete.
    """
    record = store.get(record_id)
    if record is None:
        return {"status": "not_found", "record_id": record_id}

    # Legal-hold / erasure classes demand full lineage propagation.
    strict = retention_class in ("legal_hold", "gdpr_erasure")

    children = store.derivation_children(record_id)
    receipt = {"record_id": record_id, "children_visited": [], "aggregates_adjusted": []}

    # Durably record intent BEFORE mutating primary store.
    manifest = store.write_invalidation_manifest(record_id, children)

    for child in children:
        if not store.invalidate_or_rederive(child, forgotten=record_id, timeout_s=timeout_s):
            if strict:
                raise ProvenanceDeletionError(
                    f"forget({record_id}) could not invalidate child {child.id}; "
                    f"retention_class={retention_class} forbids partial deletion. "
                    f"Manifest {manifest.id} left for recovery."
                )
            # best_effort: mark orphaned and continue
            store.mark_orphaned(child, forgotten=record_id)
        receipt["children_visited"].append(child.id)

    for agg in store.aggregates_citing(record_id):
        if not store.subtract_contribution(agg, record_id):
            if strict:
                raise ProvenanceDeletionError(
                    f"aggregate {agg.id} still encodes forgotten {record_id}; "
                    f"cannot satisfy {retention_class}."
                )
            store.mark_aggregate_stale(agg)
        receipt["aggregates_adjusted"].append(agg.id)

    store.remove_primary(record_id)
    store.finalize_manifest(manifest.id)
    receipt["status"] = "provenance_consistent_deleted"
    return receipt
