# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstoned-memory-record-is-still-leaking-through-a-stale-embedding-index-after-ttl-scoped-erasure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstoned-memory-record-is-still-leaking-through-a-stale-embedding-index-after-ttl-scoped-erasure.warrant.json
# Markdown SHA-256:   f212a87143e99f7a9a2a93d11f5541497a0a814e49e3c82cfae98962aa34047e
# Code AST SHA-256:   00fd473d7ae81e59de81c0f7cb86e95e089b9e99310794c68b04c0c53d863447
# Verified Classes:   TombstoneLeakError, MemoryRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TombstoneLeakError(RuntimeError):
    """Raised when a retrieval hit has no live backing record or has poisoned lineage."""
    pass


@dataclass
class MemoryRecord:
    record_id: Optional[str]
    content: str
    scope: str
    derived_from: list[str] = field(default_factory=list)
    deleted: bool = False
    invalidated: bool = False


def read_and_validate(
    hits: list[MemoryRecord],
    forgotten_ids: set[str],
    store_lookup,
) -> list[MemoryRecord]:
    """Filter retrieval hits down to records safe to place in agent context.

    Enforces the three-state invariant: live, tombstoned, derived.
    Raises rather than silently dropping, so the leak is observable.
    """
    safe: list[MemoryRecord] = []
    for hit in hits:
        # Rule 1: null record_id with content is a tombstone bleeding through
        # the index. It has no live authority and may carry an erasure duty.
        if hit.record_id is None:
            raise TombstoneLeakError(
                f"retrieval hit with null record_id (scope={hit.scope!r}); "
                f"index entry outlived store row — treat as erasure leak"
            )

        # Rule 2: record must still resolve in the authoritative store.
        if not store_lookup(hit.record_id):
            raise TombstoneLeakError(
                f"record {hit.record_id!r} returned by index but absent from store; "
                f"compaction has not caught up — do not use content"
            )

        # Rule 3: derivation lineage must not intersect any forgotten id.
        # This is the transitive-closure check the flat forget path omits.
        poisoned = set(hit.derived_from) & forgotten_ids
        if poisoned:
            raise TombstoneLeakError(
                f"record {hit.record_id!r} derived from forgotten ids {sorted(poisoned)}; "
                f"lineage cascade did not invalidate this artifact"
            )

        if hit.deleted or hit.invalidated:
            raise TombstoneLeakError(
                f"record {hit.record_id!r} flagged deleted/invalidated but still "
                f"returned by retrieval path"
            )

        safe.append(hit)
    return safe


def forget_with_cascade(
    target_ids: set[str],
    all_records: list[MemoryRecord],
    store_delete,
) -> int:
    """Erase targets and every record whose derivation closure touches them.

    Returns count of records invalidated. A forget that returns without
    cascading derived artifacts is unsound whenever distillation exists.
    """
    to_erase = set(target_ids)
    changed = True
    while changed:
        changed = False
        for rec in all_records:
            if rec.record_id in to_erase:
                continue
            if set(rec.derived_from) & to_erase:
                to_erase.add(rec.record_id)
                changed = True

    if not to_erase:
        raise TombstoneLeakError(
            "forget matched zero records; verify scope_filter targets the "
            "partition that actually holds derived artifacts, not just sources"
        )

    for rid in to_erase:
        store_delete(rid)
    return len(to_erase)
