# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-deleted-memory-when-a-scoped-forget-tombstone-is-applied-only-to-the-hot-tier.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-deleted-memory-when-a-scoped-forget-tombstone-is-applied-only-to-the-hot-tier.warrant.json
# Markdown SHA-256:   047137e63ec0121b9ee05bba595747448f04bc361e714f93893f4985a199f9fb
# Code AST SHA-256:   9c708b0c907a09c82c65812440fc63ee5b47fb31333bb1b1a34ce86e115fce8c
# Verified Classes:   ProvenanceClosureError, Artifact, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class ProvenanceClosureError(RuntimeError):
    """Raised when a scoped forget cannot tombstone the full provenance closure."""
    pass

@dataclass
class Artifact:
    key: str
    provenance: set[str]
    tombstoned: bool = False

class MemoryStore:
    def __init__(self, artifacts: Iterable[Artifact]):
        self._artifacts = list(artifacts)
        self._peer_holders: dict[str, set[str]] = {}  # subject -> peer agent ids

    def register_peer_holder(self, subject_id: str, peer_id: str) -> None:
        self._peer_holders.setdefault(subject_id, set()).add(peer_id)

    def provenance_closure(self, subject_id: str) -> list[Artifact]:
        # Transitive: any artifact whose provenance intersects the subject,
        # iterated to fixpoint so summaries-of-summaries are included.
        closure: set[int] = set()
        frontier = {subject_id}
        changed = True
        while changed:
            changed = False
            for i, art in enumerate(self._artifacts):
                if i in closure:
                    continue
                if art.provenance & frontier:
                    closure.add(i)
                    frontier |= art.provenance
                    changed = True
        return [self._artifacts[i] for i in closure]

    def forget(self, subject_id: str) -> dict[str, int]:
        closure = self.provenance_closure(subject_id)
        pending_peers = set(self._peer_holders.get(subject_id, set()))
        if pending_peers:
            raise ProvenanceClosureError(
                f"forget({subject_id!r}) blocked: {len(pending_peers)} peer holder(s) "
                f"have not acknowledged invalidation: {sorted(pending_peers)}"
            )
        tombstoned = 0
        for art in closure:
            if not art.tombstoned:
                art.tombstoned = True
                tombstoned += 1
        # Re-derive check: any surviving artifact must not reference the subject.
        for art in self._artifacts:
            if not art.tombstoned and subject_id in art.provenance:
                raise ProvenanceClosureError(
                    f"post-forget leak: artifact {art.key!r} still references {subject_id!r}"
                )
        return {"tombstoned": tombstoned, "pending_peer_ack": 0}

    def recall(self, query_key: str) -> list[Artifact]:
        return [a for a in self._artifacts if a.key == query_key and not a.tombstoned]
