# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-scoped-retention-tombstones-before-honoring-a-forget-request-the-write-after-forget-resurrection-race-in-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-scoped-retention-tombstones-before-honoring-a-forget-request-the-write-after-forget-resurrection-race-in-agent-memory.warrant.json
# Markdown SHA-256:   052fb19283fb508e7952efdddbb201d22adf8484a532fc4d7ca1e6b1db8a0403
# Code AST SHA-256:   b2af7d248df58566bad42c78a9fe01a77fef20cbfc4ac023e96194bdbbc68399
# Verified Classes:   ResurrectionRaceError, ScopeToken, Tombstone
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime


class ResurrectionRaceError(RuntimeError):
    """Raised when a write would resurrect a tombstoned key via a stale scope token."""


@dataclass(frozen=True)
class ScopeToken:
    scope: str
    epoch: int
    minted_at: datetime


@dataclass(frozen=True)
class Tombstone:
    scope: str
    key: str
    epoch: int
    committed_at: datetime


def admit_write(
    token: ScopeToken,
    key: str,
    tombstone: Tombstone | None,
) -> None:
    """Enforce token-mint ordering against the key's tombstone.

    Rejects any write whose scope token was minted at or before the tombstone
    committed, even if the write arrives after the tombstone in wall-clock time.
    """
    if tombstone is None:
        return

    if token.scope != tombstone.scope or key != tombstone.key:
        return

    # The invariant: ordering is by token mint time, not by write receipt time.
    if token.minted_at <= tombstone.committed_at:
        raise ResurrectionRaceError(
            f"write to {token.scope}/{key} carries token minted at "
            f"{token.minted_at.isoformat()} (epoch {token.epoch}), but tombstone "
            f"committed at {tombstone.committed_at.isoformat()} (epoch "
            f"{tombstone.epoch}); re-mint scope token and retry"
        )

    # Even a post-tombstone token must strictly exceed the tombstone epoch,
    # otherwise a replayed token from the same mint batch can slip through.
    if token.epoch <= tombstone.epoch:
        raise ResurrectionRaceError(
            f"write to {token.scope}/{key} epoch {token.epoch} does not strictly "
            f"exceed tombstone epoch {tombstone.epoch}"
        )
