# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-from-stale-read-replicas-in-agent-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-from-stale-read-replicas-in-agent-memory-tool-apis.warrant.json
# Markdown SHA-256:   809794fcbad1cbfcf7eb3c379f57d3ef0c73a465241dbb8f5415fcf74575dd84
# Code AST SHA-256:   04b8b1ebbc44a82fba54008fdb984a8c081038d230bea8e7430e07a2ded0c3d2
# Verified Classes:   TombstoneResurrectionError, Tombstone, ReadResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class TombstoneResurrectionError(RuntimeError):
    """Raised when a write descends from a read that predates a covering tombstone."""
    pass


@dataclass(frozen=True)
class Tombstone:
    key: str
    scope: str
    tombstone_id: str
    log_index: int
    content_fingerprint: str


@dataclass(frozen=True)
class ReadResult:
    key: str
    scope: str
    value: Optional[str]
    log_index: int
    read_epoch: int


def fingerprint(value: str) -> str:
    return hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]


def guarded_write(
    key: str,
    scope: str,
    value: str,
    derived_from: ReadResult,
    tombstones: list[Tombstone],
) -> dict:
    """Enforce provenance-aware tombstone invariant on write."""
    if derived_from.value is None:
        raise TombstoneResurrectionError(
            f"write to {key} in {scope} derived from a null read; refusing"
        )

    write_fp = fingerprint(value)
    for tb in tombstones:
        if tb.scope != scope:
            continue
        # Tombstone covers this content if fingerprints match, regardless of key.
        if tb.content_fingerprint == write_fp:
            if derived_from.read_epoch <= tb.log_index:
                raise TombstoneResurrectionError(
                    f"write to {key} in {scope} descends from read_epoch "
                    f"{derived_from.read_epoch} which predates tombstone "
                    f"{tb.tombstone_id} at log_index {tb.log_index}; "
                    f"content fingerprint {write_fp} matches tombstoned payload"
                )
    return {
        "key": key,
        "scope": scope,
        "fingerprint": write_fp,
        "derived_from_epoch": derived_from.read_epoch,
        "accepted": True,
    }


def barrier_read(
    key: str,
    scope: str,
    min_log_index: int,
    replicas: list[ReadResult],
) -> ReadResult:
    """Return a read that provably observes log state at or beyond min_log_index."""
    eligible = [r for r in replicas if r.log_index >= min_log_index]
    if not eligible:
        raise TombstoneResurrectionError(
            f"no replica for {key} in {scope} has reached log_index "
            f"{min_log_index}; refusing to serve a potentially stale read"
        )
    return max(eligible, key=lambda r: r.log_index)
