# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-erases-a-memory-that-other-agents-still-hold-as-a-retrieval-anchor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-erases-a-memory-that-other-agents-still-hold-as-a-retrieval-anchor.warrant.json
# Markdown SHA-256:   1d4294736bc0493ae7d64e3c58230f538d8c56ab6f59b4b32e8a9573e9a5eeb2
# Code AST SHA-256:   1723ded2f9f2c123a04ed5cd8f14f6eb825e5ce079b7808f4c112b25a9e4b592
# Verified Classes:   ErasureClosureError, MemoryNode, ErasureCoordinator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class ErasureClosureError(RuntimeError):
    """Raised when an erasure cannot be certified because derived memories
    or live context references remain reachable after point deletion."""


@dataclass
class MemoryNode:
    node_id: str
    derived_from: set[str] = field(default_factory=set)
    quarantined: bool = False


class ErasureCoordinator:
    def __init__(self, nodes: Iterable[MemoryNode], similarity_radius: float = 0.85):
        self.nodes: dict[str, MemoryNode] = {n.node_id: n for n in nodes}
        self.similarity_radius = similarity_radius
        self.live_context_refs: set[str] = set()

    def register_context_ref(self, node_id: str) -> None:
        self.live_context_refs.add(node_id)

    def _derived_closure(self, root: str) -> set[str]:
        closure: set[str] = set()
        frontier = [root]
        while frontier:
            current = frontier.pop()
            for node in self.nodes.values():
                if current in node.derived_from and node.node_id not in closure:
                    closure.add(node.node_id)
                    frontier.append(node.node_id)
        return closure

    def _unlineaged_risk(self, root: str) -> bool:
        # A node with no derived_from edge but high similarity to root is a
        # paraphrase leak candidate; we cannot prove it is unlinked.
        return any(
            not n.derived_from and n.node_id != root and not n.quarantined
            for n in self.nodes.values()
        )

    def erase(self, root: str, require_closure: bool = True) -> set[str]:
        if root not in self.nodes:
            raise ErasureClosureError(f"unknown root {root!r}; cannot certify erasure")

        closure = self._derived_closure(root)
        pending_context = (closure | {root}) & self.live_context_refs

        if require_closure and self._unlineaged_risk(root):
            raise ErasureClosureError(
                f"cannot certify erasure of {root!r}: un-lineaged derivatives "
                f"may survive; quarantine neighborhood before retrying"
            )

        if pending_context:
            raise ErasureClosureError(
                f"cannot certify erasure of {root!r}: live context references "
                f"remain for {sorted(pending_context)}; flush before completion"
            )

        erased = {root} | closure
        for node_id in erased:
            self.nodes.pop(node_id, None)
        return erased

    def quarantine_neighborhood(self, root: str, candidates: Iterable[str]) -> set[str]:
        flagged: set[str] = set()
        for node_id in candidates:
            node = self.nodes.get(node_id)
            if node is not None:
                node.quarantined = True
                flagged.add(node_id)
        return flagged


def certify_erasure(coordinator: ErasureCoordinator, record_id: str) -> set[str]:
    """Attempt closure erasure; raises if the invariant cannot be discharged."""
    try:
        return coordinator.erase(record_id, require_closure=True)
    except ErasureClosureError as exc:
        raise ErasureClosureError(
            f"erasure of {record_id!r} failed closure invariant: {exc}"
        ) from exc
