# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-right-to-be-forgotten-erasure-has-silently-failed-in-a-scoped-retention-memory-tool-api.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-right-to-be-forgotten-erasure-has-silently-failed-in-a-scoped-retention-memory-tool-api.warrant.json
# Markdown SHA-256:   edde3453e4f2325b14f16c30ab01ffd0ad8cb56ad2cd8d2c92b4a7d2d46220c0
# Code AST SHA-256:   9f25f2bfb7c8d79bc9d7e390f13eadc98e065fc274ccf3ae6e8f3d036dae0d1b
# Verified Classes:   ErasureIncompleteError, MemoryRecord, ErasureReceipt
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ErasureIncompleteError(RuntimeError):
    """Raised when a forget() acknowledgment cannot be verified as effective."""


@dataclass
class MemoryRecord:
    record_id: str
    scope: str
    subject_id: str | None          # None => derivative that lost its erasure key
    content: str
    derived_from: list[str] = field(default_factory=list)


@dataclass
class ErasureReceipt:
    subject_id: str
    deleted_count: int
    scopes_touched: list[str]
    status: str


def _provenance_scopes(subject_id: str, records: Iterable[MemoryRecord]) -> set[str]:
    """Walk the provenance graph to find every scope holding subject content."""
    by_id = {r.record_id: r for r in records}
    scopes: set[str] = set()
    frontier = [r for r in records if r.subject_id == subject_id]
    seen: set[str] = set()
    while frontier:
        rec = frontier.pop()
        if rec.record_id in seen:
            continue
        seen.add(rec.record_id)
        scopes.add(rec.scope)
        for parent in rec.derived_from:
            if parent in by_id:
                frontier.append(by_id[parent])
        for child in records:
            if rec.record_id in child.derived_from:
                frontier.append(child)
    return scopes


def verify_erasure(
    subject_id: str,
    receipt: ErasureReceipt,
    records: Iterable[MemoryRecord],
    read_path_hits: Iterable[str],
) -> None:
    """
    Treat the forget() receipt as a hypothesis. Raise if any read path still
    returns subject content, if the provenance graph spans scopes the receipt
    never touched, or if a derivative carries the subject's content without
    the erasure key.
    """
    records = list(records)
    surviving_hits = list(read_path_hits)
    if surviving_hits:
        raise ErasureIncompleteError(
            f"subject {subject_id} still retrievable via read paths: {surviving_hits}"
        )

    provenance_scopes = _provenance_scopes(subject_id, records)
    untouched = provenance_scopes - set(receipt.scopes_touched)
    if untouched:
        raise ErasureIncompleteError(
            f"erasure for {subject_id} did not cover provenance scopes {sorted(untouched)}; "
            f"receipt touched only {receipt.scopes_touched}"
        )

    # Derivatives that lost the subject key are un-erasable by predicate.
    orphaned = [
        r.record_id
        for r in records
        if r.subject_id is None
        and any(parent in {x.record_id for x in records if x.subject_id == subject_id}
                for parent in r.derived_from)
    ]
    if orphaned:
        raise ErasureIncompleteError(
            f"derived records {orphaned} lost the erasure key for {subject_id}; "
            f"forget predicate cannot select them"
        )

    if receipt.deleted_count == 0 and provenance_scopes:
        raise ErasureIncompleteError(
            f"receipt reports zero deletions but provenance graph for {subject_id} "
            f"spans {sorted(provenance_scopes)}"
        )
