# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-forget-this-memory-as-a-provenance-erasure-transaction-rather-than-a-row-delete-and-what-invariant-breaks-whe.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-forget-this-memory-as-a-provenance-erasure-transaction-rather-than-a-row-delete-and-what-invariant-breaks-whe.warrant.json
# Markdown SHA-256:   d67efe65c30375c14d120e760c03a2a941b1e2ab3062b5387294e125d8a1215a
# Code AST SHA-256:   1e8fa7284a67d3be107e3c4ebd5a1e618ec2200ff4288a644e28867a2d659d3e
# Verified Classes:   ProvenanceErasureError, Artifact, ErasureReceipt
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ProvenanceErasureError(RuntimeError):
    """Raised when a forget request cannot be closed over the derivation graph."""


@dataclass
class Artifact:
    artifact_id: str
    derived_from: list[str]          # one-hop provenance IDs (sources or other artifacts)
    revoked: bool = False
    store: str = "local"             # local | peer:<id> | index | checkpoint


@dataclass
class ErasureReceipt:
    source_id: str
    closed: bool
    erased: list[str] = field(default_factory=list)
    unresolved_scopes: list[str] = field(default_factory=list)


def erase_provenance(source_id: str, graph: dict[str, Artifact]) -> ErasureReceipt:
    """Close a forget request over the transitive derivation graph.

    Invariant: on closed=True, no artifact reachable from source_id remains
    un-revoked, and every reachable artifact lives in a store we can write.
    """
    if source_id not in graph:
        raise ProvenanceErasureError(
            f"forget target {source_id!r} not present in graph; cannot distinguish "
            f"'already erased' from 'never known' — refusing to report success"
        )

    # Fixpoint walk: descendants may themselves be derived_from sources.
    reachable: set[str] = set()
    frontier: list[str] = [source_id]
    while frontier:
        node = frontier.pop()
        if node in reachable:
            continue
        reachable.add(node)
        for aid, art in graph.items():
            if node in art.derived_from and aid not in reachable:
                frontier.append(aid)

    receipt = ErasureReceipt(source_id=source_id, closed=True)
    for aid in reachable:
        art = graph[aid]
        if art.store.startswith("peer:") or art.store == "checkpoint":
            # Cannot write across this boundary in-transaction.
            receipt.closed = False
            receipt.unresolved_scopes.append(f"{art.store}:{aid}")
            continue
        art.revoked = True
        receipt.erased.append(aid)

    # Index revocation is keyed by provenance, not row id; a hit whose
    # provenance is revoked must be filtered at read time even if the
    # vector survives eventual-consistency deletion.
    if not receipt.closed:
        raise ProvenanceErasureError(
            f"partial erasure for {source_id!r}: unresolved scopes "
            f"{receipt.unresolved_scopes}; returning success would be a false forget"
        )
    return receipt
