# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-a-tombstoned-memory-after-a-crdt-merge-and-silently-re-inject-it-into-the-retrieval-index.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-a-tombstoned-memory-after-a-crdt-merge-and-silently-re-inject-it-into-the-retrieval-index.warrant.json
# Markdown SHA-256:   ec5cd7ab720c66cd0d6f11a16d6394576c6acb1d3b087841957f802d4a5aa9aa
# Code AST SHA-256:   c787987690c87384c7b9a1e3a76a9d4047291281bd38373ed2e5ae41260c7b81
# Verified Classes:   ForgottenMemoryResurrection, FederatedMemoryReplica
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Set


class ForgottenMemoryResurrection(RuntimeError):
    """Raised when a memory identity marked forgotten re-enters the retrieval index."""
    pass


@dataclass
class FederatedMemoryReplica:
    # OR-Set state: identity -> set of live tags, plus per-identity tombstoned tags.
    live_tags: dict = field(default_factory=dict)
    tombstoned_tags: dict = field(default_factory=dict)
    # Grow-only, identity-scoped forget set. Never shrinks except under causal stability.
    forgotten_ids: Set[str] = field(default_factory=set)
    # Physical retrieval index (what queries actually hit).
    index: Set[str] = field(default_factory=set)

    def merge(self, other: "FederatedMemoryReplica") -> None:
        for ident, tags in other.live_tags.items():
            self.live_tags.setdefault(ident, set()).update(tags)
        for ident, tags in other.tombstoned_tags.items():
            self.tombstoned_tags.setdefault(ident, set()).update(tags)
        # Forget is monotone: union of forgotten identities.
        self.forgotten_ids |= other.forgotten_ids

    def visible(self) -> Set[str]:
        """Set membership minus tombstoned tags, THEN minus forgotten identities."""
        out = set()
        for ident, tags in self.live_tags.items():
            live = tags - self.tombstoned_tags.get(ident, set())
            if live and ident not in self.forgotten_ids:
                out.add(ident)
        return out

    def forget(self, ident: str) -> None:
        """Identity-scoped forget: tombstone all observed tags AND record identity permanently."""
        self.tombstoned_tags.setdefault(ident, set()).update(
            self.live_tags.get(ident, set())
        )
        self.forgotten_ids.add(ident)
        self.index.discard(ident)

    def reconcile_index(self) -> None:
        """Rebuild index from visible set; assert no forgotten identity leaks in."""
        target = self.visible()
        # Guard: a forgotten identity must never be a reconcile target.
        leaked = target & self.forgotten_ids
        if leaked:
            raise ForgottenMemoryResurrection(
                f"reconcile tried to index forgotten identities: {sorted(leaked)}"
            )
        self.index = target

    def query(self, ident: str) -> bool:
        """Retrieval path: hard negative filter applied at return time."""
        if ident in self.forgotten_ids and ident in self.index:
            raise ForgottenMemoryResurrection(
                f"query would return forgotten identity {ident!r} from index"
            )
        return ident in self.index


def demonstrate_resurrection() -> None:
    a = FederatedMemoryReplica()
    d = FederatedMemoryReplica()
    # Both hold f_7731 with tags t1,t2; D additionally minted t3 during partition heal.
    a.live_tags["f_7731"] = {"t1", "t2"}
    d.live_tags["f_7731"] = {"t1", "t2", "t3"}
    a.reconcile_index()

    a.forget("f_7731")            # identity-scoped forget on A
    assert "f_7731" not in a.index

    a.merge(d)                    # D's add carries unseen tag t3 -> set resurrects
    assert "f_7731" in a.visible() or "f_7731" in a.live_tags  # set-level presence

    # The guard: reconcile must not re-index the forgotten identity despite set presence.
    try:
        # Simulate a buggy reconciler that trusts set membership alone.
        buggy_target = set(a.live_tags)  # ignores forgotten_ids
        if buggy_target & a.forgotten_ids:
            raise ForgottenMemoryResurrection(
                "reconciler trusted set membership over forgotten_ids; "
                "forgotten identity f_7731 would re-enter index"
            )
        a.reconcile_index()
    except ForgottenMemoryResurrection:
        # Correct path: identity filter holds; index stays clean.
        a.reconcile_index()
        assert "f_7731" not in a.index
        assert not a.query("f_7731")
        return
    raise ForgottenMemoryResurrection("forget invariant not enforced")


if __name__ == "__main__":
    demonstrate_resurrection()
