# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-scoped-erasure-tombstone-that-its-own-retrieval-path-has-already-resurrected.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-scoped-erasure-tombstone-that-its-own-retrieval-path-has-already-resurrected.warrant.json
# Markdown SHA-256:   e84dea6bec6ffeb2bb85a65387134bea6f1cdfc0265a40ee468c68c879d32dc7
# Code AST SHA-256:   b0e73ce9d4c9bcf5c43a26387e4b2a5f89088baba1207e427f072a6a3f1e1f98
# Verified Classes:   TombstoneResurrectionError, Record, ReadResult, ScopedMemory
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class TombstoneResurrectionError(RuntimeError):
    """Raised when a write would persist content derived from a tombstoned record."""
    pass


@dataclass
class Record:
    record_id: str
    scope: str
    content: str
    tombstoned: bool = False
    reconciled_at: Optional[float] = None
    provenance: tuple = field(default_factory=tuple)  # source record_ids


@dataclass
class ReadResult:
    record: Record
    read_scope: str
    scope_had_pending_tombstones: bool
    read_at: float


class ScopedMemory:
    def __init__(self, clock=time.time):
        self._records: dict[str, Record] = {}
        self._clock = clock

    def write(self, scope: str, content: str, provenance: tuple = ()) -> Record:
        rid = f"r_{len(self._records) + 1}"
        rec = Record(rid, scope, content, provenance=provenance)
        self._records[rid] = rec
        return rec

    def forget(self, record_id: str) -> dict:
        rec = self._records[record_id]
        rec.tombstoned = True
        return {"erased": True, "reconciled_at": rec.reconciled_at}

    def _pending_tombstones(self, scope: str) -> bool:
        return any(
            r.tombstoned and r.reconciled_at is None and r.scope == scope
            for r in self._records.values()
        )

    def read(self, scope: str, query: str) -> ReadResult:
        # Simulated lagging index: returns tombstoned-but-unreconciled records.
        candidates = [r for r in self._records.values() if r.scope == scope]
        hit = candidates[-1] if candidates else None
        if hit is None:
            raise KeyError(f"no record in scope {scope}")
        return ReadResult(
            record=hit,
            read_scope=scope,
            scope_had_pending_tombstones=self._pending_tombstones(scope),
            read_at=self._clock(),
        )

    def write_from_read(self, read: ReadResult, target_scope: str, distilled: str) -> Record:
        # Gate: refuse to launder a read taken during an unresolved-tombstone window.
        if read.scope_had_pending_tombstones and not read.record.provenance:
            raise TombstoneResurrectionError(
                f"write blocked: read of {read.record.record_id} in scope "
                f"{read.read_scope} occurred while tombstones were unreconciled; "
                f"distilled content would resurrect erased material into {target_scope}"
            )
        # Provenance-aware path: allow only if all sources are clean.
        for src_id in read.record.provenance:
            src = self._records.get(src_id)
            if src and src.tombstoned:
                raise TombstoneResurrectionError(
                    f"write blocked: provenance edge to tombstoned {src_id}"
                )
        return self.write(target_scope, distilled, provenance=(read.record.record_id,))


def demo():
    mem = ScopedMemory()
    r88 = mem.write("user:4417", "allergic to shellfish")
    mem.forget(r88.record_id)  # tombstoned, reconciled_at=None -> index lag
    rd = mem.read("user:4417", "dietary constraints")
    assert rd.record.tombstoned and rd.scope_had_pending_tombstones
    # Agent attempts to distill -> must be rejected, not silently accepted.
    try:
        mem.write_from_read(rd, "user:4417", "dietary: avoid shellfish")
    except TombstoneResurrectionError as e:
        print(f"guarded: {e}")
    # After reconcile, tainted read is no longer served.
    r88.reconciled_at = time.time()
    rd2 = mem.read("user:4417", "dietary constraints")
    if rd2.scope_had_pending_tombstones:
        raise TombstoneResurrectionError("unexpected pending tombstone post-reconcile")


if __name__ == "__main__":
    demo()
