# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-fact-but-keep-its-embedding-tombstone-divergence-in-right-to-be-forgotten-enforcement-across-agent-memory-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-fact-but-keep-its-embedding-tombstone-divergence-in-right-to-be-forgotten-enforcement-across-agent-memory-stores.warrant.json
# Markdown SHA-256:   4e6da31dbd6b099742cc3d986a69dea341bcbd0b582d124da7015c9d85c627f1
# Code AST SHA-256:   e840f870ce7d4c07476a68100b6fdb20e2def1656c333a86edd961c9d6d46110
# Verified Classes:   ErasureClosureIncomplete, Artifact
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ErasureClosureIncomplete(RuntimeError):
    """Raised when an erasure cannot be proven to cover the information closure."""
    pass


@dataclass
class Artifact:
    artifact_id: str
    kind: str                      # "turn" | "fact" | "summary" | "embedding"
    provenance: list[str] = field(default_factory=list)  # upstream artifact_ids
    index_key: str | None = None   # key in any shared index, if indexed


def compute_closure(root_ids: Iterable[str], artifacts: dict[str, Artifact]) -> set[str]:
    """Transitive downstream closure of the given roots. Requires complete provenance."""
    closure: set[str] = set(root_ids)
    changed = True
    while changed:
        changed = False
        for aid, art in artifacts.items():
            if aid in closure:
                continue
            if any(src in closure for src in art.provenance):
                closure.add(aid)
                changed = True
    return closure


def enforce_erasure(user_id: str, artifacts: dict[str, Artifact],
                    user_roots: dict[str, list[str]],
                    shared_index_keys: set[str]) -> set[str]:
    roots = user_roots.get(user_id, [])
    if not roots:
        return set()

    # Guard 1: every derived artifact must carry provenance, or closure is uncomputable.
    for aid, art in artifacts.items():
        if art.kind in ("summary", "embedding") and not art.provenance:
            raise ErasureClosureIncomplete(
                f"artifact {aid} ({art.kind}) has no provenance; "
                f"erasure closure for user {user_id} cannot be proven"
            )

    closure = compute_closure(roots, artifacts)

    # Guard 2: every artifact in the closure that is indexed must be reachable
    # in the shared index namespace, or the erasure leaks through the index.
    for aid in closure:
        art = artifacts[aid]
        if art.index_key is not None and art.index_key not in shared_index_keys:
            raise ErasureClosureIncomplete(
                f"artifact {aid} indexed under {art.index_key!r} but that key "
                f"is not addressable by the erasure predicate; shared-index leak"
            )

    return closure


def verify_recovery_probe(fact_id: str, probe_hits: int, k: int,
                          threshold: float = 0.95) -> None:
    """Assert that no probe recovered the erased fact above retrieval threshold."""
    if probe_hits > 0:
        raise ErasureClosureIncomplete(
            f"erased fact {fact_id} recovered on {probe_hits}/{k} probes; "
            f"closure incomplete or retrieval non-determinism exceeds bound"
        )
    miss_bound = (1.0 - 0.05) ** k
    if miss_bound > (1.0 - threshold):
        raise ErasureClosureIncomplete(
            f"probe count k={k} insufficient: miss bound {miss_bound:.3f} "
            f"exceeds {1.0 - threshold:.3f}; increase k before certifying erasure"
        )
