# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-tombstone-durability-when-a-gdpr-deletion-request-races-an-in-flight-episodic-write.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-tombstone-durability-when-a-gdpr-deletion-request-races-an-in-flight-episodic-write.warrant.json
# Markdown SHA-256:   5993e31eef60522a5d2cac476b19d1bea1c9a4637a8f6bdd3384a604510b4570
# Code AST SHA-256:   113a40f1cf01d5cc85a7292b061cf3187147ea3cb0a6dd69716f0c46ab1993ff
# Verified Classes:   TombstoneWriteRaceError, Provenance, Tombstone, EpisodicStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TombstoneWriteRaceError(RuntimeError):
    """Raised when a write is accepted for a subject whose tombstone supersedes it."""


@dataclass(frozen=True)
class Provenance:
    writer_instance: str
    session: str
    ts: float          # accept-time, monotonic, not commit-time
    tool_call_id: int  # monotonic per-instance


@dataclass(frozen=True)
class Tombstone:
    subject_id: str
    tombstone_ts: float
    forget_call_id: str


class EpisodicStore:
    def __init__(self, tombstone_log: dict[str, list[Tombstone]]):
        self._tombstones = tombstone_log

    def latest_tombstone(self, subject_id: str) -> Optional[Tombstone]:
        entries = self._tombstones.get(subject_id)
        return max(entries, key=lambda t: t.tombstone_ts) if entries else None

    def accept_write(self, subject_id: str, prov: Provenance) -> None:
        # Accept-time tombstone check: the only placement that preserves
        # the linearizability claim made by forget()'s return value.
        tomb = self.latest_tombstone(subject_id)
        if tomb is not None and prov.ts <= tomb.tombstone_ts:
            raise TombstoneWriteRaceError(
                f"write for subject={subject_id!r} tool_call_id={prov.tool_call_id} "
                f"accepted at ts={prov.ts} is superseded by tombstone "
                f"forget_call_id={tomb.forget_call_id} at ts={tomb.tombstone_ts}; "
                f"reject terminally, do not retry"
            )
        # ... commit path ...


def guarded_write(store: EpisodicStore, subject_id: str, prov: Provenance) -> None:
    if prov.ts <= 0:
        raise TombstoneWriteRaceError("provenance.ts must be accept-time, not commit-time")
    store.accept_write(subject_id, prov)
