# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-tombstone-resurrection-when-a-scoped-erasure-memory-api-re-admits-a-forgotten-key-from-a-stale-replica.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-tombstone-resurrection-when-a-scoped-erasure-memory-api-re-admits-a-forgotten-key-from-a-stale-replica.warrant.json
# Markdown SHA-256:   97c070d42230955eeafa9c50b0aa37a607765de990a4f6be06d07d76f67e2979
# Code AST SHA-256:   2507464ab92cbfacb88a4978e27ef4cc55eec2760b42a21d86dbe7598cf20131
# Verified Classes:   ResurrectionDetected, StaleReplicaRead, Tombstone, RecallResult, ErasureLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ResurrectionDetected(RuntimeError):
    """Raised when recall returns a value written after a hard-erasure tombstone."""


class StaleReplicaRead(RuntimeError):
    """Raised when recall is served by a replica whose applied fence predates the tombstone."""


@dataclass
class Tombstone:
    tombstone_id: str
    scope: str
    key: str
    ts: float
    erasure: str  # "rtbf" for hard erasure, "ttl" for soft expiry


@dataclass
class RecallResult:
    value: Optional[str]
    write_ts: float
    replica_id: str
    applied_fence: float  # timestamp of newest tombstone this replica has applied


@dataclass
class ErasureLedger:
    """Durable per-instance record of tombstones issued but not yet verified globally fenced."""
    tombstones: dict = field(default_factory=dict)  # (scope, key) -> Tombstone

    def record(self, t: Tombstone) -> None:
        self.tombstones[(t.scope, t.key)] = t

    def lookup(self, scope: str, key: str) -> Optional[Tombstone]:
        return self.tombstones.get((scope, key))


def verified_recall(
    ledger: ErasureLedger,
    recall_fn,
    scope: str,
    key: str,
    max_retries: int = 3,
) -> Optional[str]:
    """
    Wrap a memory.recall call with tombstone-fence verification.
    Returns the value only if it is provably not a resurrection of a hard-erased key.
    """
    tomb = ledger.lookup(scope, key)
    last_error: Optional[Exception] = None

    for attempt in range(max_retries):
        result: RecallResult = recall_fn(scope, key)

        if result.value is None:
            # Absence is only proof of erasure if the replica has applied the fence.
            if tomb is not None and result.applied_fence < tomb.ts:
                last_error = StaleReplicaRead(
                    f"replica {result.replica_id} applied_fence={result.applied_fence} "
                    f"predates tombstone {tomb.tombstone_id} ts={tomb.ts}; absence unproven"
                )
                time.sleep(0.05 * (2 ** attempt))
                continue
            return None

        if tomb is None:
            return result.value

        if result.write_ts < tomb.ts:
            # Stale read: value predates erasure. Retry against a fresher replica.
            last_error = StaleReplicaRead(
                f"replica {result.replica_id} served write_ts={result.write_ts} "
                f"older than tombstone {tomb.tombstone_id} ts={tomb.ts}"
            )
            time.sleep(0.05 * (2 ** attempt))
            continue

        # write_ts >= tomb.ts on a hard-erased key: resurrection.
        if tomb.erasure == "rtbf":
            raise ResurrectionDetected(
                f"key ({scope}, {key}) resurrected after RTBF tombstone "
                f"{tomb.tombstone_id} (ts={tomb.ts}); "
                f"resurrecting write_ts={result.write_ts} on replica {result.replica_id}. "
                f"Quarantine key, re-issue forget with re-admission warrant, emit compliance event."
            )
        # Soft TTL expiry: value is live, not a resurrection.
        return result.value

    raise StaleReplicaRead(
        f"exhausted {max_retries} retries verifying ({scope}, {key}) against tombstone; "
        f"last error: {last_error}"
    )
