# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-ttl-expiry-against-a-provenance-linked-erasure-warrant-when-a-memory-tool-s-read-path-resurrects-tombstoned-records.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-ttl-expiry-against-a-provenance-linked-erasure-warrant-when-a-memory-tool-s-read-path-resurrects-tombstoned-records.warrant.json
# Markdown SHA-256:   32699a3d2be197c6c587acb66ca9add67e29db671d0af46331f30d427dff0317
# Code AST SHA-256:   0de97895fdc6fe8fefabf20e36ed3a8c159d0522f81d3fdbd6db3ed27ea5da12
# Verified Classes:   ErasureClosureError, RecordState, Record, MemoryStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ErasureClosureError(RuntimeError):
    """Raised when an erasure warrant cannot be proven complete over the
    provenance DAG — e.g., a provenance edge targets a hard-deleted record,
    or a derived record survives that is reachable from the subject."""
    pass


class RecordState(Enum):
    LIVE = "live"
    EXPIRED = "expired"
    TOMBSTONED = "tombstoned"


@dataclass
class Record:
    id: str
    subject: Optional[str]
    provenance: list[str]          # IDs this record was derived from
    ttl_s: int
    created_at: int
    state: RecordState = RecordState.LIVE
    content: str = ""


@dataclass
class MemoryStore:
    records: dict[str, Record] = field(default_factory=dict)
    # Edges are retained even after a record TTL-expires, so closure is computable.

    def read(self, rid: str, now: int) -> Record:
        r = self.records[rid]
        if r.state is RecordState.TOMBSTONED:
            raise ErasureClosureError(f"read of tombstoned record {rid}")
        if now >= r.created_at + r.ttl_s:
            # Expired: addressable for provenance, but content is withheld.
            r.state = RecordState.EXPIRED
            r.content = ""
        return r

    def write(self, r: Record) -> None:
        for src in r.provenance:
            if src not in self.records:
                raise ErasureClosureError(
                    f"write references unknown provenance {src}; chain broken"
                )
            if self.records[src].state is RecordState.TOMBSTONED:
                raise ErasureClosureError(
                    f"write derives from tombstoned record {src}; "
                    f"resurrection of erased data rejected"
                )
        self.records[r.id] = r

    def forget(self, subject: str, now: int) -> dict:
        # Roots: any record attributed to the subject, regardless of TTL state.
        roots = [r.id for r in self.records.values() if r.subject == subject]
        # Transitive closure over provenance edges.
        closure: set[str] = set()
        stack = list(roots)
        while stack:
            rid = stack.pop()
            if rid in closure:
                continue
            if rid not in self.records:
                raise ErasureClosureError(
                    f"provenance edge to hard-deleted record {rid}; "
                    f"erasure cannot be proven complete"
                )
            closure.add(rid)
            stack.extend(self.records[rid].provenance)

        if not closure:
            # No roots found is only valid if no derivation ever occurred;
            # the caller must treat this as unproven, not as success.
            raise ErasureClosureError(
                f"no records attributable to {subject}; erasure unproven"
            )

        for rid in closure:
            self.records[rid].state = RecordState.TOMBSTONED
            self.records[rid].content = ""

        return {
            "subject": subject,
            "tombstoned": sorted(closure),
            "edges_traversed": sum(
                len(self.records[rid].provenance) for rid in closure
            ),
            "status": "complete",
        }
