# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-scoped-erasure-tombstone-as-a-write-barrier-rather-than-a-retrieval-filter.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-scoped-erasure-tombstone-as-a-write-barrier-rather-than-a-retrieval-filter.warrant.json
# Markdown SHA-256:   7c23d6a566879eea1667271c6b6c16ed5c03e9101115d68b7db03d2891174f0f
# Code AST SHA-256:   3d4046953251ca32f7a6cea2926b8710072c8bbbeb4a0107d8b69ce93ad8e2e4
# Verified Classes:   ErasureBarrierViolation, IncompleteLineageError, Tombstone, DerivedWrite, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ErasureBarrierViolation(RuntimeError):
    """Raised when a memory write's lineage closure intersects an active tombstone."""
    pass


class IncompleteLineageError(RuntimeError):
    """Raised when a derived record is submitted without total source lineage."""
    pass


@dataclass(frozen=True)
class Tombstone:
    subject_id: str
    scope: str
    erased_record_ids: FrozenSet[str]


@dataclass
class DerivedWrite:
    record_id: str
    target_scope: str
    source_ids: FrozenSet[str]
    lineage_complete: bool
    content: str = field(repr=False)


class MemoryStore:
    def __init__(self) -> None:
        self._tombstones: list[Tombstone] = []
        # scope graph: source_scope -> set of retained scopes it derives into
        self._derivation_edges: dict[str, set[str]] = {}

    def register_derivation(self, source_scope: str, target_scope: str) -> None:
        self._derivation_edges.setdefault(source_scope, set()).add(target_scope)

    def forget(self, subject_id: str, scope: str, record_ids: FrozenSet[str]) -> Tombstone:
        t = Tombstone(subject_id=subject_id, scope=scope, erased_record_ids=record_ids)
        self._tombstones.append(t)
        return t

    def requires_write_barrier(self, scope: str) -> bool:
        # Barrier is mandatory whenever the scope has any outbound derivation edge.
        return bool(self._derivation_edges.get(scope))

    def commit_derived(self, write: DerivedWrite) -> None:
        if not write.lineage_complete:
            raise IncompleteLineageError(
                f"derived record {write.record_id} has incomplete lineage; "
                f"erasure cannot be guaranteed"
            )
        # Write barrier: check lineage closure against every active tombstone.
        for t in self._tombstones:
            if write.source_ids & t.erased_record_ids:
                raise ErasureBarrierViolation(
                    f"write {write.record_id} into scope {write.target_scope} "
                    f"derives from erased record(s) "
                    f"{sorted(write.source_ids & t.erased_record_ids)} "
                    f"under tombstone for subject {t.subject_id} in scope {t.scope}; "
                    f"re-distill without tainted sources or discard"
                )
        # Commit would proceed here.
        return None


def consolidate_cluster(store: MemoryStore, cluster_sources: FrozenSet[str]) -> DerivedWrite:
    """Distill an episodic cluster into a semantic fact, enforcing the barrier."""
    write = DerivedWrite(
        record_id="sem-9001",
        target_scope="semantic",
        source_ids=cluster_sources,
        lineage_complete=True,
        content="distilled fact",
    )
    if store.requires_write_barrier("episodic"):
        store.commit_derived(write)  # raises ErasureBarrierViolation if tainted
    return write
