# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-has-been-re-materialized-by-a-lossy-forget-path-in-read-write-forget-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-has-been-re-materialized-by-a-lossy-forget-path-in-read-write-forget-memory-tool-apis.warrant.json
# Markdown SHA-256:   073551de3aca75725780933f58b904fd75b0b41288112fcfcdb0a80df1886da2
# Code AST SHA-256:   98966068c82d2bbb3836685fc5672ae4dfd7db4d172972a9f66866743d804eac
# Verified Classes:   TombstoneDivergenceError, MemoryRecord, TombstoneLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class TombstoneDivergenceError(RuntimeError):
    """Raised when a record reads live but its provenance chain references an active tombstone."""


@dataclass(frozen=True)
class MemoryRecord:
    key: str
    value: object
    state: str                      # "live" | "tombstoned" | "purged"
    provenance: tuple[str, ...] = ()
    tombstone_ref: str | None = None


@dataclass
class TombstoneLedger:
    # tombstone_id -> state ("forgotten" | "purged")
    _entries: dict[str, str] = field(default_factory=dict)

    def record(self, tombstone_id: str, state: str) -> None:
        self._entries[tombstone_id] = state

    def is_active(self, tombstone_id: str) -> bool:
        return self._entries.get(tombstone_id) == "forgotten"

    def is_purged(self, tombstone_id: str) -> bool:
        return self._entries.get(tombstone_id) == "purged"


def assert_reachable_only_through_live(
    record: MemoryRecord,
    ledger: TombstoneLedger,
    ancestors: Iterable[MemoryRecord],
) -> None:
    """Gate a read of `record` on the liveness of its provenance ancestors.

    Raises TombstoneDivergenceError if the record reads live while any ancestor
    is tombstoned (not purged) -- i.e., the forget path re-materialized content.
    """
    if record.state != "live":
        return

    # Cheapest structural signal: two fields in one record disagreeing.
    if record.tombstone_ref is not None and ledger.is_active(record.tombstone_ref):
        raise TombstoneDivergenceError(
            f"record {record.key!r} reads live but carries active tombstone_ref "
            f"{record.tombstone_ref!r}; split-brain between content and provenance planes"
        )

    for anc in ancestors:
        if anc.state == "tombstoned" or (
            anc.tombstone_ref is not None and ledger.is_active(anc.tombstone_ref)
        ):
            raise TombstoneDivergenceError(
                f"record {record.key!r} derives from tombstoned ancestor {anc.key!r} "
                f"(tombstone {anc.tombstone_ref!r}); quarantine and re-forget with cascade"
            )
        if anc.tombstone_ref is not None and ledger.is_purged(anc.tombstone_ref):
            # Legitimate orphaned derivation: content was hard-deleted, not soft-forgotten.
            # Caller should rewrite provenance to drop the dangling reference.
            continue


def safe_read(
    record: MemoryRecord,
    ledger: TombstoneLedger,
    ancestors: Iterable[MemoryRecord],
) -> object | None:
    if record.state == "tombstoned" or record.state == "purged":
        return None
    assert_reachable_only_through_live(record, ledger, ancestors)
    return record.value
