# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-from-re-embedding-erased-agent-memories-after-gdpr-deletion.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-from-re-embedding-erased-agent-memories-after-gdpr-deletion.warrant.json
# Markdown SHA-256:   61282f1f09bbbac06c02f40c9309e44bdb2907fc405bcd3991c37f86a3c732d5
# Code AST SHA-256:   6c89977c04f89a9737dbad696c59dcc9e7a59684c1cf762311a45773f094f10c
# Verified Classes:   ResurrectionViolation, DerivedArtifact, MemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ResurrectionViolation(RuntimeError):
    """Raised when a derived memory artifact would regenerate an erased subject."""


@dataclass
class DerivedArtifact:
    artifact_id: str
    text: str
    provenance: frozenset  # transitive subject IDs; built at write time
    derived_from: str


class MemoryStore:
    def __init__(self):
        self.episodes = {}          # ep_id -> {"subject_id": str, "text": str}
        self.derived = {}           # artifact_id -> DerivedArtifact
        self.tombstones = set()     # durable erased subject IDs
        self.consolidation_fenced = set()

    def erase(self, subject_id: str) -> None:
        # Fence consolidation first so an in-flight batch cannot resurrect.
        self.consolidation_fenced.add(subject_id)
        self.tombstones.add(subject_id)  # durable before any purge
        # Closure: purge episodes AND every derived artifact whose
        # provenance intersects the erased subject.
        for ep_id in [e for e, r in self.episodes.items()
                      if r["subject_id"] == subject_id]:
            del self.episodes[ep_id]
        for aid in [a for a, art in self.derived.items()
                    if subject_id in art.provenance]:
            del self.derived[aid]

    def consolidate(self, ep_id: str, fact_text: str, artifact_id: str) -> DerivedArtifact:
        ep = self.episodes.get(ep_id)
        if ep is None:
            raise ResurrectionViolation(
                f"consolidation source {ep_id} missing; cannot establish provenance"
            )
        subject = ep["subject_id"]
        if subject in self.tombstones:
            # Guardrail: never re-derive from a tombstoned subject, even
            # if the episode somehow survived a partial purge.
            raise ResurrectionViolation(
                f"refusing to consolidate {ep_id}: subject {subject} is tombstoned"
            )
        if subject in self.consolidation_fenced:
            raise ResurrectionViolation(
                f"consolidation fenced for {subject}; erase in progress"
            )
        art = DerivedArtifact(
            artifact_id=artifact_id,
            text=fact_text,
            provenance=frozenset({subject}),
            derived_from=ep_id,
        )
        self.derived[artifact_id] = art
        return art

    def rebuild_index(self, reembed) -> None:
        for art in self.derived.values():
            if art.provenance & self.tombstones:
                raise ResurrectionViolation(
                    f"rebuild would re-embed {art.artifact_id} from tombstoned "
                    f"provenance {sorted(art.provenance & self.tombstones)}"
                )
            reembed(art)
