# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resurrect-a-tombstoned-memory-record-when-a-write-arrives-concurrently-with-an-erasure-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resurrect-a-tombstoned-memory-record-when-a-write-arrives-concurrently-with-an-erasure-propagation.warrant.json
# Markdown SHA-256:   1eb760699de2acc2117d637c665ef11b79cef270cbffd4fb24a9c266dceb3b57
# Code AST SHA-256:   af7de7ffc1f075bbd8c89a0a9662a1c425dcf3003c838e671cdb967e733570f7
# Verified Classes:   ErasureConflictError, RetentionPolicyViolation, Tombstone
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class ErasureConflictError(RuntimeError):
    """Raised when a write would resurrect a record covered by an unexpired tombstone."""


class RetentionPolicyViolation(RuntimeError):
    """Raised when tombstone retention R is shorter than max propagation delay P."""


@dataclass(frozen=True)
class Tombstone:
    key: str
    version: int          # monotonic; causally greater than any pre-erasure write
    created_at: float
    retention_s: float    # R
    propagated_by: float  # absolute deadline = created_at + P


def resolve_write(
    *,
    key: str,
    write_causal_version: Optional[int],  # None => blind upsert
    now: float,
    tombstone: Optional[Tombstone],
    max_propagation_s: float,  # P
    recreate_token: Optional[str] = None,
) -> str:
    if tombstone is None:
        return "created"

    # Fail closed if retention is misconfigured relative to propagation.
    if tombstone.retention_s < max_propagation_s:
        raise RetentionPolicyViolation(
            f"key={key!r} retention R={tombstone.retention_s}s < P={max_propagation_s}s; "
            "store cannot guarantee erasure durability"
        )

    expired = now > tombstone.created_at + tombstone.retention_s
    if expired:
        return "created"  # key genuinely free

    # Unexpired tombstone covers the key.
    if write_causal_version is not None and write_causal_version <= tombstone.version:
        raise ErasureConflictError(
            f"write to key={key!r} at causal v{write_causal_version} "
            f"precedes tombstone v{tombstone.version}; resurrection refused"
        )

    if write_causal_version is None and recreate_token is None:
        raise ErasureConflictError(
            f"blind upsert to tombstones key={key!r}; "
            "supply recreate_token or re-issue against post-erasure snapshot"
        )

    return "recreated_with_override" if recreate_token else "created"
