# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-tool-tombstone-as-a-hard-read-barrier-rather-than-a-soft-hint.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-tool-tombstone-as-a-hard-read-barrier-rather-than-a-soft-hint.warrant.json
# Markdown SHA-256:   d4ce7c0e45fe55b43bf6d0cf80e4f273fd89ccf2df56230df7ec6bb17137267a
# Code AST SHA-256:   bdfc96137a0d16282d9bbc802b0823828fa20d1e3195a09ba38893735661e579
# Verified Classes:   TombstoneBarrierError, MemoryRecord, TombstoneIndex
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TombstoneBarrierError(RuntimeError):
    """Raised when a memory read cannot prove tombstone consultation for every returned record."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    scope: str | None
    derived_from: tuple[str, ...] = ()


@dataclass
class TombstoneIndex:
    tombstoned_ids: set[str] = field(default_factory=set)
    tombstoned_scopes: set[str] = field(default_factory=set)
    compaction_watermark: float = 0.0


def guarded_read(
    records: Iterable[MemoryRecord],
    query_scope: str,
    tombstones: TombstoneIndex,
    now: float,
) -> list[MemoryRecord]:
    """Read that enforces the hard tombstone barrier.

    A record is returnable only if it can prove it is outside every tombstoned
    scope AND outside the provenance closure of every tombstoned record.
    Unprovable scope during an open compaction window fails closed.
    """
    results: list[MemoryRecord] = []
    for rec in records:
        if rec.record_id in tombstones.tombstoned_ids:
            continue
        if rec.scope in tombstones.tombstoned_scopes:
            continue
        if rec.scope is None:
            # No scope tag: unprovable. Only safe if no compaction is in flight
            # and no tombstone in this query's scope could have derived it.
            if now < tombstones.compaction_watermark:
                raise TombstoneBarrierError(
                    f"record {rec.record_id} has no scope tag and compaction is "
                    f"open until {tombstones.compaction_watermark}; cannot prove "
                    f"it is outside tombstoned scope {query_scope!r}"
                )
            if query_scope in tombstones.tombstoned_scopes:
                raise TombstoneBarrierError(
                    f"record {rec.record_id} lacks scope metadata but query scope "
                    f"{query_scope!r} is tombstoned; provenance unprovable"
                )
        if set(rec.derived_from) & tombstones.tombstoned_ids:
            raise TombstoneBarrierError(
                f"record {rec.record_id} derives from tombstoned sources "
                f"{sorted(set(rec.derived_from) & tombstones.tombstoned_ids)}"
            )
        results.append(rec)
    return results


def guarded_write(
    target_scope: str,
    tombstones: TombstoneIndex,
    now: float,
) -> None:
    """Refuse writes into a tombstoned scope while compaction is open,
    to prevent re-seeding forgotten content as a fresh record."""
    if target_scope in tombstones.tombstoned_scopes and now < tombstones.compaction_watermark:
        raise TombstoneBarrierError(
            f"write into tombstoned scope {target_scope!r} refused: compaction "
            f"open until {tombstones.compaction_watermark}; write would re-seed "
            f"content that the tombstone set does not yet cover"
        )
