# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-forget-acknowledgment-as-a-tombstone-rather-than-a-deletion.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-forget-acknowledgment-as-a-tombstone-rather-than-a-deletion.warrant.json
# Markdown SHA-256:   c0356bc9642a8d1af8c72b5e31c8b3903bde2d03cd181ab84d6ccbc9131ead20
# Code AST SHA-256:   173841942b71b93d7833d35b1d710b9270b4fe48ff7f127e46769bd77daa67f7
# Verified Classes:   TombstoneViolation, Record, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class TombstoneViolation(RuntimeError):
    """Raised when a read/write would resurface or re-establish forgotten state."""

@dataclass
class Record:
    scope: str
    subjects: frozenset[str]
    content: str
    ttl_seconds: int

@dataclass
class MemoryStore:
    records: dict[str, Record] = field(default_factory=dict)
    # subject -> remaining tombstone lifetime (seconds); 0 means expired
    tombstones: dict[str, int] = field(default_factory=dict)

    def forget(self, subjects: Iterable[str], horizon_seconds: int) -> dict:
        subj = frozenset(subjects)
        # 1. seal the subject for the full horizon (covers derivatives + replica lag)
        for s in subj:
            self.tombstones[s] = max(self.tombstones.get(s, 0), horizon_seconds)
        # 2. purge primary records touching the subject
        purged = [k for k, r in self.records.items() if r.subjects & subj]
        for k in purged:
            del self.records[k]
        # 3. acknowledge only as pending until horizon elapses elsewhere
        return {"status": "pending", "sealed_subjects": sorted(subj),
                "purged": len(purged), "horizon": horizon_seconds}

    def read(self, scope: str) -> list[Record]:
        out = []
        for r in self.records.values():
            if r.scope != scope:
                continue
            if any(self.tombstones.get(s, 0) > 0 for s in r.subjects):
                # derivative survived under a different scope: do not serve
                raise TombstoneViolation(
                    f"read of scope={scope!r} blocked: record touches live tombstone "
                    f"{sorted(s for s in r.subjects if self.tombstones.get(s, 0) > 0)}"
                )
            out.append(r)
        return out

    def write(self, rec: Record) -> None:
        live = {s for s in rec.subjects if self.tombstones.get(s, 0) > 0}
        if live:
            raise TombstoneViolation(
                f"write rejected: subjects {sorted(live)} are under active tombstone; "
                f"cannot re-establish forgotten state"
            )
        self.records[rec.scope + ":" + str(len(self.records))] = rec
