# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-forget-this-user-as-a-distributed-state-transition-problem-rather-than-a-single-vector-store-delete.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-forget-this-user-as-a-distributed-state-transition-problem-rather-than-a-single-vector-store-delete.warrant.json
# Markdown SHA-256:   d899d3438b8e390166cf7a6b983e1710a92192fb8cc78333a22acd9cd75fe0a8
# Code AST SHA-256:   039502336b085d7ee0ffb38b684fc55be95631cb4ba725d81ec8e8cce42fa76d
# Verified Classes:   ErasureClosureViolation, Artifact, MemoryGraph
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ErasureClosureViolation(RuntimeError):
    """Raised when an erasure claim cannot be closed over the derivation DAG."""
    pass


@dataclass
class Artifact:
    artifact_id: str
    kind: str                      # "episodic" | "summary" | "embedding" | "cache"
    source_subject_ids: list[str]
    content: str


@dataclass
class MemoryGraph:
    artifacts: dict[str, Artifact] = field(default_factory=dict)
    suppressed_subjects: set[str] = field(default_factory=set)

    def reachable_from(self, subject_id: str) -> list[Artifact]:
        return [
            a for a in self.artifacts.values()
            if subject_id in a.source_subject_ids
        ]


def _probe_hit(graph: MemoryGraph, subject_id: str, probe_ngrams: list[str],
               threshold: int = 1) -> list[str]:
    """Content-probe: independent of deletion path. Returns artifact ids still
    carrying the subject's unique phrases."""
    hits = []
    for a in graph.artifacts.values():
        if subject_id in a.source_subject_ids:
            continue  # already accounted for by provenance walk
        matches = sum(1 for g in probe_ngrams if g in a.content)
        if matches >= threshold:
            hits.append(a.artifact_id)
    return hits


def execute_erasure(graph: MemoryGraph, subject_id: str,
                    probe_ngrams: list[str]) -> dict:
    # (a) durable tombstone BEFORE deletion so re-distillation is suppressed
    graph.suppressed_subjects.add(subject_id)

    # (b) delete by provenance membership across the whole DAG
    reachable = graph.reachable_from(subject_id)
    deleted = []
    for a in reachable:
        graph.artifacts.pop(a.artifact_id, None)
        deleted.append(a.artifact_id)

    # (c) upstream caches that could re-derive: drop any cache whose content
    #     still matches the probe, regardless of provenance tag
    residual = _probe_hit(graph, subject_id, probe_ngrams)
    for aid in residual:
        graph.artifacts.pop(aid, None)

    # (d) independent verification: re-probe after deletion
    survivors = _probe_hit(graph, subject_id, probe_ngrams)

    # (e) refuse to assert completion if any survivor remains
    if survivors:
        raise ErasureClosureViolation(
            f"erasure for {subject_id} not closed: {len(survivors)} "
            f"unreachable-but-resident artifacts survive: {survivors}"
        )

    return {
        "subject_id": subject_id,
        "deleted_by_provenance": deleted,
        "deleted_by_probe": residual,
        "status": "ERASURE_COMPLETE",
        "tombstone": hashlib.sha256(subject_id.encode()).hexdigest()[:16],
    }
