# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-tombstone-collisions-when-right-to-erasure-deletes-overlap-shared-semantic-memory-in-a-persistent-agent-store.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-tombstone-collisions-when-right-to-erasure-deletes-overlap-shared-semantic-memory-in-a-persistent-agent-store.warrant.json
# Markdown SHA-256:   58b2c1278b82ac7cf1b96a6a33a4d43f540690b85541efb9541ce28e2e01e8dd
# Code AST SHA-256:   b8f1624834a14de393844cc48f1737ed869fb9959bb707dd4fdf5fbfb2d01974
# Verified Classes:   ErasureCollisionError, DerivedMemory, Store
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ErasureCollisionError(RuntimeError):
    """Raised when a derived memory's provenance cannot be resolved post-erasure."""


@dataclass
class DerivedMemory:
    row_id: str
    text: str
    source_event_ids: list[str]
    subject_id: str | None = None

    def content_fingerprint(self) -> str:
        return hashlib.sha256(self.text.encode("utf-8")).hexdigest()


@dataclass
class Store:
    live_events: dict[str, str] = field(default_factory=dict)       # event_id -> subject
    derived: dict[str, DerivedMemory] = field(default_factory=dict)
    tombstones: set[str] = field(default_factory=set)               # content fingerprints


def erase_subject(store: Store, subject_id: str) -> dict:
    erased_event_ids = {eid for eid, sid in store.live_events.items() if sid == subject_id}
    for eid in erased_event_ids:
        del store.live_events[eid]

    unclassified: list[str] = []
    for row in list(store.derived.values()):
        touches = erased_event_ids.intersection(row.source_event_ids)
        if not touches:
            continue
        resolves = any(eid in store.live_events for eid in row.source_event_ids)
        if resolves:
            continue  # rewrite path is safe; leave for re-distillation
        fp = row.content_fingerprint()
        if fp in store.tombstones:
            del store.derived[row.row_id]
        else:
            unclassified.append(row.row_id)

    if unclassified:
        raise ErasureCollisionError(
            f"erasure for subject {subject_id!r} left {len(unclassified)} derived rows "
            f"with dangling provenance and no matching tombstone: {unclassified}"
        )

    return {"subject_id": subject_id, "status": "complete", "scope": "live+derived tiers only"}


def distill_and_commit(store: Store, candidate: DerivedMemory) -> None:
    fp = candidate.content_fingerprint()
    if fp in store.tombstones:
        return  # distillation race guard: erased content must not re-materialize
    store.derived[candidate.row_id] = candidate
