# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-provenance-laundering-write-during-retention-compaction-forgetting.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-provenance-laundering-write-during-retention-compaction-forgetting.warrant.json
# Markdown SHA-256:   699e197857b6b862f29bcfc0440860b70def8a25f66f0efb54c8c771d7963fb9
# Code AST SHA-256:   243c2988b89d726d47809d0846d41580675b07461e4ca3b87ee56bbff556c7f2
# Verified Classes:   ProvenanceLaunderingError, ProvenanceRewrite, ForgetManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a forget/compaction rewrote a survivor's provenance to a
    node that does not faithfully absorb the original target."""
    pass


@dataclass
class ProvenanceRewrite:
    survivor_id: str
    old_parent: str
    new_parent: str
    absorbed_ids: list[str]
    lossy: bool


@dataclass
class ForgetManifest:
    rewrites: list[ProvenanceRewrite] = field(default_factory=list)
    tombstones: list[str] = field(default_factory=list)


def validate_forget_manifest(manifest: ForgetManifest) -> None:
    """Refuse to trust any survivor whose reparenting laundered provenance.

    Invariant: for every rewrite, the original parent must appear in the
    new parent's absorbed_ids. Otherwise the survivor now claims support
    from a node that never witnessed the original derivation.
    """
    for rw in manifest.rewrites:
        if rw.old_parent not in rw.absorbed_ids:
            raise ProvenanceLaunderingError(
                f"survivor {rw.survivor_id!r} reparented from {rw.old_parent!r} "
                f"to {rw.new_parent!r}, but new parent absorbed "
                f"{rw.absorbed_ids!r} and never witnessed the original. "
                f"Survivor must be marked orphaned_of={rw.old_parent!r} or tombstoned."
            )
        if rw.lossy and rw.old_parent not in rw.absorbed_ids:
            # defensive: lossy summaries must still declare what they absorbed
            raise ProvenanceLaunderingError(
                f"lossy summary {rw.new_parent!r} omits absorbed source "
                f"{rw.old_parent!r}; provenance chain is unauditable."
            )


def apply_forget(manifest: ForgetManifest, store) -> None:
    validate_forget_manifest(manifest)
    for rw in manifest.rewrites:
        store.set_provenance(rw.survivor_id, [rw.new_parent])
        if rw.lossy:
            store.set_flag(rw.survivor_id, "provenance_degraded", True)
    for tid in manifest.tombstones:
        store.tombstone(tid)
