# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-tombstoned-but-resurrected-memory-write-when-a-forget-scope-and-a-concurrent-write-scope-overlap-at-the-retention-bounda.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-tombstoned-but-resurrected-memory-write-when-a-forget-scope-and-a-concurrent-write-scope-overlap-at-the-retention-bounda.warrant.json
# Markdown SHA-256:   cc91f33ef0812aaf6ab05b9ae4ac0c8f7d6f4cb4bd494201ebe6372c8e789bf6
# Code AST SHA-256:   8302e5a29b01cbf807f1197e5bd2a5fb5696044a362b3070517597a2a81a5c5f
# Verified Classes:   ResurrectionArtifactError, WriteReceipt, ScopeState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResurrectionArtifactError(RuntimeError):
    """Raised when a write receipt's epoch predates the scope's committed tombstone epoch."""
    pass


@dataclass(frozen=True)
class WriteReceipt:
    scope: str
    epoch: int
    key_hash: str
    reissued_to: Optional[str] = None


@dataclass(frozen=True)
class ScopeState:
    scope: str
    committed_epoch: int
    tombstoned: bool


def reconcile_receipt(receipt: WriteReceipt, scope_state: ScopeState) -> None:
    """
    Called at checkpoint resume for every remember receipt before any
    error-recovery branch re-issues a write. Raises if the receipt is a
    resurrection artifact.
    """
    if receipt.epoch < scope_state.committed_epoch:
        raise ResurrectionArtifactError(
            f"receipt for scope={receipt.scope!r} epoch={receipt.epoch} "
            f"predates committed_epoch={scope_state.committed_epoch} "
            f"(tombstoned={scope_state.tombstoned}); "
            f"reissued_to={receipt.reissued_to!r}. Quarantine task and "
            f"transitively tombstone reissued scope."
        )
    if receipt.reissued_to is not None and receipt.reissued_to != receipt.scope:
        raise ResurrectionArtifactError(
            f"receipt laundered from scope={receipt.scope!r} into "
            f"scope={receipt.reissued_to!r}; resurrection amplifier detected."
        )


def resume_from_checkpoint(receipts: list[WriteReceipt], scopes: dict[str, ScopeState]) -> None:
    for r in receipts:
        state = scopes.get(r.scope)
        if state is None:
            raise ResurrectionArtifactError(f"no committed scope state for {r.scope!r}")
        reconcile_receipt(r, state)
    # Only reached if every receipt's epoch chain matches committed epochs.
