# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-provenance-tracked-forget-against-derived-semantic-memory-before-acknowledging-a-gdpr-erasure.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-provenance-tracked-forget-against-derived-semantic-memory-before-acknowledging-a-gdpr-erasure.warrant.json
# Markdown SHA-256:   4a3769265880c89229e18dafaabd4e005874c12df3f2b92aabfe398de7d2d083
# Code AST SHA-256:   998c2b13b9a42fe479d920694106c02beffdb12123763fd7ad3ee7d2b4fe08f3
# Verified Classes:   ErasureClosureError, Node
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional
import hashlib

class ErasureClosureError(RuntimeError):
    """Raised when an erasure ack would be emitted without proven lineage closure."""

@dataclass
class Node:
    id: str
    content: str
    tombstoned: bool = False
    parents: list[str] = field(default_factory=list)   # lineage: this <- parents
    indexed: bool = False                               # materialized in an ANN/keyword index

def fingerprint(content: str) -> str:
    return hashlib.sha256(content.strip().lower().encode()).hexdigest()[:16]

def reverse_lineage_closure(graph: dict[str, Node], source_id: str) -> set[str]:
    """BFS over ALL nodes, live and tombstoned. Tombstones are pass-through, not leaves."""
    if source_id not in graph:
        raise ErasureClosureError(f"source {source_id} absent from graph; cannot prove closure")
    children: dict[str, list[str]] = {}
    for n in graph.values():
        for p in n.parents:
            children.setdefault(p, []).append(n.id)
    seen, stack = set(), [source_id]
    while stack:
        cur = stack.pop()
        for c in children.get(cur, []):
            if c not in seen:
                seen.add(c)
                stack.append(c)          # traverse through tombstoned intermediates
    return seen

def verify_erasure(graph: dict[str, Node], source_id: str,
                    open_erasures: set[str]) -> dict:
    if source_id in open_erasures:
        raise ErasureClosureError(f"erasure of {source_id} already in flight; re-entrant ack forbidden")
    open_erasures.add(source_id)
    try:
        fp = fingerprint(graph[source_id].content)
        closure = reverse_lineage_closure(graph, source_id)
        survivors, tainted, stale_index = [], [], []
        for nid in closure:
            node = graph[nid]
            if node.tombstoned:
                continue
            if fingerprint(node.content) == fp:
                survivors.append(nid)            # content survived despite lineage
            elif not node.parents:
                tainted.append(nid)              # orphan: lineage broken, cannot attribute
            if node.indexed:
                stale_index.append(nid)          # index entry is a surviving copy
        if survivors or stale_index or tainted:
            raise ErasureClosureError(
                f"erasure of {source_id} not closed: "
                f"survivors={survivors} stale_index={stale_index} tainted={tainted}"
            )
        return {"deleted_derived": len(closure), "ack": "complete"}
    finally:
        open_erasures.discard(source_id)

def forget(graph: dict[str, Node], source_id: str, open_erasures: set[str]) -> dict:
    # 1. tombstone the source record
    graph[source_id].tombstoned = True
    # 2. closure proof BEFORE any ack; raises if survivors/index/taint remain
    return verify_erasure(graph, source_id, open_erasures)
