# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-the-wrong-thing-when-erasure-is-scoped-to-a-memory-record-instead-of-the-derived-representations-that-cite-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-the-wrong-thing-when-erasure-is-scoped-to-a-memory-record-instead-of-the-derived-representations-that-cite-it.warrant.json
# Markdown SHA-256:   8dbb11c559ad22c20d1add9abde426911039f077fac0011703851d04486b2011
# Code AST SHA-256:   788bc10cf4d94e8021c1b14ee55edb40879366ab823985e1420af06ff19a68b6
# Verified Classes:   ErasureClosureError, Artifact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ErasureClosureError(RuntimeError):
    """Raised when erasure cannot be proven transitively closed over derivations."""


@dataclass
class Artifact:
    artifact_id: str
    source_ids: frozenset[str] | None  # None => provenance missing/unstructured
    kind: str  # "canonical" | "summary" | "embedding" | "handoff_bundle"


def resolve_erasure_closure(
    erased_ids: Iterable[str],
    artifacts: dict[str, Artifact],
    max_depth: int = 8,
) -> set[str]:
    """
    Compute the transitive set of artifact IDs that must be erased because they
    derive (directly or indirectly) from any erased canonical ID.

    Fails closed: if any artifact that intersects the closure has missing
    provenance, we cannot prove closure and must refuse to report success.
    """
    erased = set(erased_ids)
    closure: set[str] = set()
    frontier = set(erased)
    depth = 0

    while frontier and depth < max_depth:
        next_frontier: set[str] = set()
        for aid, art in artifacts.items():
            if aid in closure or aid in erased:
                continue
            if art.source_ids is None:
                # Provenance gap: this artifact *might* derive from erased content.
                # We cannot exclude it, so closure is unprovable.
                raise ErasureClosureError(
                    f"artifact {aid!r} ({art.kind}) has no structured provenance; "
                    f"cannot prove it is disjoint from erased set {sorted(erased)}"
                )
            if art.source_ids & frontier:
                closure.add(aid)
                next_frontier.add(aid)
        frontier = next_frontier
        depth += 1

    if frontier:
        raise ErasureClosureError(
            f"provenance depth exceeded {max_depth}; possible cycle or runaway "
            f"derivation chain at {sorted(frontier)}"
        )
    return closure


def audit_erasure(
    erased_ids: Iterable[str],
    artifacts: dict[str, Artifact],
) -> dict[str, object]:
    """
    A sound retention audit: asserts no surviving artifact cites an erased ID.
    Unlike a point lookup, this catches laundered content in summaries,
    embeddings, and handoff bundles.
    """
    erased = set(erased_ids)
    try:
        closure = resolve_erasure_closure(erased, artifacts)
    except ErasureClosureError as exc:
        return {"status": "unverifiable", "reason": str(exc)}

    survivors = set(artifacts) - erased - closure
    leaks = [
        aid for aid in survivors
        if artifacts[aid].source_ids and (artifacts[aid].source_ids & erased)
    ]
    if leaks:
        raise ErasureClosureError(
            f"derived artifacts still cite erased records: {sorted(leaks)}"
        )
    return {
        "status": "pass",
        "erased_canonical": sorted(erased),
        "erased_derived": sorted(closure),
        "survivors": sorted(survivors),
    }


# --- Trace of the observed failure, now caught ------------------------------
store = {
    "m_4471": Artifact("m_4471", frozenset(), "canonical"),
    # Distillation cites a turn index, not the memory ID -> provenance gap.
    "s_0912": Artifact("s_0912", None, "summary"),
    "e_0912": Artifact("e_0912", frozenset({"s_0912"}), "embedding"),
    "peer_ctx_77": Artifact("peer_ctx_77", frozenset({"s_0912"}), "handoff_bundle"),
}

try:
    audit_erasure({"m_4471"}, store)
except ErasureClosureError as e:
    # The point-lookup audit reported "pass" here. The closure audit refuses.
    print(f"erasure unverifiable: {e}")
