# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-forget-tool-ack-as-insufficient-proof-of-erasure-across-a-memory-lineage-graph.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-forget-tool-ack-as-insufficient-proof-of-erasure-across-a-memory-lineage-graph.warrant.json
# Markdown SHA-256:   d9be59e58cc7238bb85763ca5c5f8fd251a8a120b7f99f6d26fcba4e2ffbc483
# Code AST SHA-256:   aa8a03540b84aa715b7df6f63fa1d015d9fc7f09715bd5bf920b6b20a110fdcd
# Verified Classes:   ErasureAttestationError, LineageNode, Replica
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

INFORMATION_BEARING_EDGE_TYPES = frozenset({"derived_from", "summarized_session", "distilled_to_semantic"})


class ErasureAttestationError(RuntimeError):
    pass


@dataclass
class LineageNode:
    node_id: str
    edges: list[tuple[str, str]] = field(default_factory=list)  # (edge_type, target_node_id)


@dataclass
class Replica:
    replica_id: str
    live_source_node: str | None  # non-None => can re-materialize from a live source


def compute_closure(root_id: str, graph: dict[str, LineageNode]) -> set[str]:
    seen: set[str] = set()
    stack = [root_id]
    while stack:
        cur = stack.pop()
        if cur in seen:
            continue
        seen.add(cur)
        node = graph.get(cur)
        if node is None:
            continue
        for edge_type, target in node.edges:
            if edge_type not in INFORMATION_BEARING_EDGE_TYPES:
                # Fail closed: an unknown edge type could hide a dependency.
                raise ErasureAttestationError(
                    f"unknown edge type {edge_type!r} on {cur}; closure not provably empty"
                )
            stack.append(target)
    return seen


def attest_erasure(
    subject_id: str,
    forget_ack: dict,
    graph: dict[str, LineageNode],
    replicas: Iterable[Replica],
) -> bool:
    if forget_ack.get("status") != "ok":
        raise ErasureAttestationError(f"forget tool did not ACK for {subject_id}")

    # Post-ACK re-evaluation: closure computed now, not before deletion.
    closure = compute_closure(subject_id, graph)
    live_dependents = {n for n in closure if n != subject_id and n in graph}
    if live_dependents:
        raise ErasureAttestationError(
            f"closure non-empty for {subject_id}: {sorted(live_dependents)}"
        )

    for replica in replicas:
        if replica.live_source_node in closure or replica.live_source_node == subject_id:
            raise ErasureAttestationError(
                f"replica {replica.replica_id} can re-materialize erased content from "
                f"live source {replica.live_source_node}"
            )
    return True
