# 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-retrieval-blocking-predicate-rather-than-a-deletion-event.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-scoped-erasure-tombstone-as-a-retrieval-blocking-predicate-rather-than-a-deletion-event.warrant.json
# Markdown SHA-256:   a97f15e227ad8e923d23a40ab1a4baf8e37009b3dba9a2aa7a3a5f0e1079dcef
# Code AST SHA-256:   db43aca05e98567c56f97e4b2bf851b1d716edc80d3877bf9842ca8ccf92d066
# Verified Classes:   ErasureContractViolation, Tombstone, MemoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class ErasureContractViolation(RuntimeError):
    """Raised when a memory operation would surface or re-introduce erased content."""


@dataclass(frozen=True)
class Tombstone:
    tombstone_id: str
    scope_atoms: frozenset[str]   # e.g. {"subject:S-4417"}
    durable: bool = True          # must outlive derivative horizons


@dataclass
class MemoryRecord:
    record_id: str
    scope_atoms: frozenset[str]   # the record's own scope
    derived_from: frozenset[str]  # provenance closure; empty == unprovenanced
    content: str


def _contaminated(record: MemoryRecord, tombstones: Iterable[Tombstone]) -> Tombstone | None:
    """A record is contaminated if any tombstone intersects its scope OR its provenance.

    Unprovenanced records are treated as contaminated by any tombstone whose scope
    is a strict subset of the record's scope atoms -- we cannot prove innocence.
    """
    for ts in tombstones:
        if ts.scope_atoms & record.scope_atoms:
            return ts
        if record.derived_from and (ts.scope_atoms & record.derived_from):
            return ts
        if not record.derived_from and ts.scope_atoms < record.scope_atoms:
            return ts
    return None


def read_with_tombstone_prefilter(
    query_scope: frozenset[str],
    candidates: list[MemoryRecord],
    tombstones: list[Tombstone],
) -> tuple[list[MemoryRecord], list[str]]:
    """Pre-filter candidates against tombstones BEFORE scoring/ranking.

    Returns (surviving_records, tombstoned_scope_atoms_observed).
    The second element lets the caller distinguish erasure from absence.
    """
    survivors: list[MemoryRecord] = []
    observed: set[str] = set()
    for rec in candidates:
        hit = _contaminated(rec, tombstones)
        if hit is not None:
            observed.update(hit.scope_atoms)
            continue
        survivors.append(rec)
    return survivors, sorted(observed)


def write_with_provenance_check(
    new_record: MemoryRecord,
    tombstones: list[Tombstone],
) -> None:
    """Reject writes whose provenance intersects an active tombstone (laundering guard)."""
    hit = _contaminated(new_record, tombstones)
    if hit is not None:
        raise ErasureContractViolation(
            f"write of {new_record.record_id!r} intersects active tombstone "
            f"{hit.tombstone_id!r} via scope {sorted(hit.scope_atoms)}; "
            f"content would re-introduce erased material"
        )


def forget(scope_atoms: frozenset[str], existing: list[Tombstone]) -> list[Tombstone]:
    """Erasure is tombstone creation, not deletion. TTL must be derived from derivative horizons."""
    ts = Tombstone(tombstone_id=f"ts:{'-'.join(sorted(scope_atoms))}", scope_atoms=scope_atoms)
    return existing + [ts]


# --- failure trace reproduced from the observed incident ---
tombstones = forget(frozenset({"subject:S-4417"}), [])

# Distillation output: subject erased, but summary is scoped to tenant and carries provenance.
leaky_summary = MemoryRecord(
    record_id="sem-88213",
    scope_atoms=frozenset({"tenant:T-09"}),
    derived_from=frozenset({"subject:S-4417", "subject:S-4418"}),
    content="paraphrase of erased content",
)

survivors, observed = read_with_tombstone_prefilter(
    frozenset({"tenant:T-09"}), [leaky_summary], tombstones
)
assert survivors == [], "post-filtering would have leaked here"
assert "subject:S-4417" in observed, "caller must be told this was erasure, not absence"

# Laundering attempt: an agent re-writes erased content under its own scope.
laundered = MemoryRecord(
    record_id="mem-99001",
    scope_atoms=frozenset({"agent:worker-3"}),
    derived_from=frozenset({"subject:S-4417"}),
    content="re-derived from pre-erasure context window",
)
try:
    write_with_provenance_check(laundered, tombstones)
except ErasureContractViolation as e:
    # Correct outcome: write blocked, tombstone ID surfaced for audit.
    pass
else:
    raise ErasureContractViolation("laundering guard failed to block re-introduction")
