# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-deletion-tombstones-when-the-memory-write-tool-acknowledges-a-forget-before-the-vector-index-has-compacted.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-deletion-tombstones-when-the-memory-write-tool-acknowledges-a-forget-before-the-vector-index-has-compacted.warrant.json
# Markdown SHA-256:   e4aa1fcb9d2baa4461fa86658a4e0247c7436b5c2ec88d36d8b42a793d844f0d
# Code AST SHA-256:   085b9723e1b8bf8d60c1eab28a76110222a9705a6decc0bae1f3e03f5c2a7000
# Verified Classes:   ForgottenMemoryResurrection, DeletionLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ForgottenMemoryResurrection(RuntimeError):
    """Raised when a read returns a record the agent has already acknowledged as forgotten
    but whose tombstone has not yet been confirmed compacted."""
    pass


@dataclass
class DeletionLedger:
    # memory_id -> tombstone_id, for forgets acknowledged but not yet compaction-confirmed
    pending: dict[str, str] = field(default_factory=dict)
    # memory_id set that is fully compacted and safe to consider unreachable
    confirmed: set[str] = field(default_factory=set)

    def record_forget(self, memory_id: str, ack: dict) -> None:
        if ack.get("status") != "forgotten":
            raise ForgottenMemoryResurrection(
                f"forget({memory_id}) did not return a forgotten status: {ack!r}"
            )
        tomb = ack.get("tombstone_id")
        if not tomb:
            raise ForgottenMemoryResurrection(
                f"forget({memory_id}) acknowledged without a tombstone_id; "
                "cannot track compaction"
            )
        self.pending[memory_id] = tomb

    def confirm_compaction(self, tombstone_id: str) -> None:
        for mid, tomb in list(self.pending.items()):
            if tomb == tombstone_id:
                del self.pending[mid]
                self.confirmed.add(mid)

    def filter_read(self, results: list[dict]) -> list[dict]:
        """Drop any record that is pending-compaction or confirmed-forgotten.
        The ledger, not the index, is authoritative until compaction is confirmed."""
        safe = []
        for r in results:
            mid = r.get("memory_id")
            if mid is None:
                # Cannot attribute the record to a deletion decision; refuse to use it
                # for any decision touching a forgotten subject.
                raise ForgottenMemoryResurrection(
                    "read result missing memory_id; cannot verify against deletion ledger"
                )
            if mid in self.pending or mid in self.confirmed:
                # Resurrection attempt: index served a record the ledger says is gone.
                continue
            safe.append(r)
        return safe


def guarded_read(ledger: DeletionLedger, read_fn, query: str, k: int) -> list[dict]:
    raw = read_fn(query=query, k=k)
    filtered = ledger.filter_read(raw)
    # If any forgotten record was served, that is an operational event worth surfacing;
    # here we only hard-fail when filtering left us with nothing to ground on.
    if not filtered and ledger.pending:
        raise ForgottenMemoryResurrection(
            f"query={query!r} returned only records pending compaction; "
            f"pending={list(ledger.pending)}; refuse to ground on resurrected content"
        )
    return filtered
