# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-complete-erasure-when-a-memory-tool-s-forget-api-silently-tombstones-derived-summaries-instead-of-recomputing-t.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-complete-erasure-when-a-memory-tool-s-forget-api-silently-tombstones-derived-summaries-instead-of-recomputing-t.warrant.json
# Markdown SHA-256:   d7037277952b1305206ed4891f600e113d283270dea73f5dfaefa6e7470c570f
# Code AST SHA-256:   dde98e242777fb91d1a9ee8e736ecc3fd1c3331c233487f5e0c8562285281f7e
# Verified Classes:   ErasureInvariantViolation, MemoryRecord, MemoryTool
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ErasureInvariantViolation(RuntimeError):
    """Raised when a forget() success signal does not correspond to actual erasure."""
    pass


@dataclass
class MemoryRecord:
    id: str
    kind: str                      # "episodic" | "semantic" | "tombstone"
    content: str
    provenance: dict               # may carry "subject", "subjects", "derived_from"
    tainted: bool = False


@dataclass
class MemoryTool:
    rows: dict[str, MemoryRecord] = field(default_factory=dict)

    def write(self, rec: MemoryRecord) -> None:
        self.rows[rec.id] = rec

    def forget(self, subject: str) -> dict:
        # BUG (the boundary under study): matches only the singular key.
        deleted = [rid for rid, r in self.rows.items()
                   if r.provenance.get("subject") == subject]
        for rid in deleted:
            del self.rows[rid]
        return {"status": "ok", "deleted": len(deleted), "errors": []}

    def read(self, predicate) -> Iterable[MemoryRecord]:
        return [r for r in self.rows.values() if predicate(r)]


def audited_forget(tool: MemoryTool, subject: str) -> dict:
    """Two-phase erasure: forget, then verify the invariant the tool cannot see."""
    result = tool.forget(subject)

    # Phase 2: audit against the FULL provenance vocabulary, not the tool's filter.
    survivors = tool.read(
        lambda r: subject in r.provenance.get("subjects", [])
        or subject in r.provenance.get("derived_from", [])
        or r.provenance.get("subject") == subject
    )
    live_ids = set(tool.rows.keys())
    orphans = [
        r for r in tool.read(lambda r: True)
        if any(src not in live_ids for src in r.provenance.get("derived_from", []))
        and subject in r.provenance.get("subjects", [])
    ]

    if result.get("status") == "ok" and (survivors or orphans):
        # Do NOT report success. Invalidate survivors, escalate, halt normal recall.
        for r in survivors + orphans:
            r.tainted = True
        raise ErasureInvariantViolation(
            f"forget('{subject}') reported ok but left "
            f"{len(survivors)} survivor(s) and {len(orphans)} orphaned "
            f"derivation(s) carrying subject provenance; marked tainted, "
            f"erasure_pending — tool success signal is not sufficient."
        )
    return result
