# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-the-tombstone-barrier-when-a-scoped-forget-memory-api-returns-before-physical-erasure.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-the-tombstone-barrier-when-a-scoped-forget-memory-api-returns-before-physical-erasure.warrant.json
# Markdown SHA-256:   f2a647d51c47a9124f14f56d80a236c52b9cd128c79859a853a8ce7ba370ffa1
# Code AST SHA-256:   a3199b49f918c5c15ae58b2f6cc38054a604a944933ecc265f833bbe7a948347
# Verified Classes:   TombstoneBarrierViolation, PendingTombstone, MemoryGateway
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TombstoneBarrierViolation(RuntimeError):
    """Raised when a read/distill would materialize content intersecting a pending tombstone."""
    pass


@dataclass
class PendingTombstone:
    tombstone_id: str
    scope: str
    physical_eta_ms: int
    physically_erased: bool = False


@dataclass
class MemoryGateway:
    pending: dict[str, PendingTombstone] = field(default_factory=dict)

    def forget(self, scope: str, tombstone_id: str, physical_eta_ms: int) -> None:
        # 'accepted' != 'erased': register the barrier before returning to the agent.
        self.pending[tombstone_id] = PendingTombstone(tombstone_id, scope, physical_eta_ms)

    def verify_erased(self, tombstone_id: str) -> bool:
        tb = self.pending.get(tombstone_id)
        if tb is None:
            return True
        # In production this polls the store's physical-completion endpoint.
        return tb.physically_erased

    def read(self, query: str, scope: str, provenance_scopes: set[str]) -> str:
        # provenance_scopes: every scope that contributed to candidate artifacts,
        # including summary/derivative sources, NOT just the artifact's own tag.
        for tb in self.pending.values():
            if tb.physically_erased:
                continue
            if tb.scope in provenance_scopes:
                raise TombstoneBarrierViolation(
                    f"read(query={query!r}, scope={scope!r}) would surface a derivative "
                    f"of pending tombstone {tb.tombstone_id} (scope={tb.scope!r}); "
                    f"physical erasure not confirmed. Quarantine until verify_erased."
                )
        return "<retrieved content>"

    def distill_episodic_to_semantic(self, buffer_scopes: set[str]) -> None:
        for tb in self.pending.values():
            if tb.physically_erased:
                continue
            if tb.scope in buffer_scopes:
                raise TombstoneBarrierViolation(
                    f"distillation would re-persist content from tombstoned scope "
                    f"{tb.scope!r} via context buffer; flush buffer for entity first."
                )
        # ... persist summary ...
