# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-the-write-that-succeeded-the-tombstone-ack-race-in-provenance-tracked-memory-tools.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-the-write-that-succeeded-the-tombstone-ack-race-in-provenance-tracked-memory-tools.warrant.json
# Markdown SHA-256:   7d36795f75e9a9cfd53f7fd6e5511091f632bd19ffe8b64d8ec7b7bdc5cd7642
# Code AST SHA-256:   444cb617002396aef69b11f8b03644f234b8a4c4e5b02dceeaa0156b3a3e138b
# Verified Classes:   StaleProvenanceError, Provenance, MemoryClient
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StaleProvenanceError(RuntimeError):
    """Raised when a read returns a record whose epoch is below the caller's
    last-known tombstone high-water mark, i.e. the record may have been
    forgotten but not yet reaped from the read path."""
    pass


@dataclass
class Provenance:
    record_id: str
    content_hash: str
    written_at: float
    epoch: int  # monotonic; must advance on every forget


@dataclass
class MemoryClient:
    _tombstone_epoch: int = 0
    _forgotten_ids: set = field(default_factory=set)

    def forget(self, record_id: str) -> dict:
        # Tool contract: returns the epoch advanced to, and distinguishes
        # already_deleted from deleted. Never returns not_found for a record
        # the caller has read.
        if record_id in self._forgotten_ids:
            return {"status": "already_deleted", "epoch": self._tombstone_epoch}
        self._forgotten_ids.add(record_id)
        self._tombstone_epoch += 1
        return {"status": "deleted", "epoch": self._tombstone_epoch}

    def read(self, query: str) -> list[Provenance]:
        # Backing store may lag; simulate a replica returning a forgotten
        # record with origin-only provenance at an old epoch.
        return [
            Provenance("m_4471", "a1", written_at=1.0, epoch=0),
            Provenance("m_4502", "b2", written_at=4.0, epoch=self._tombstone_epoch),
        ]

    def safe_read(self, query: str) -> list[Provenance]:
        results = self.read(query)
        for rec in results:
            if rec.epoch < self._tombstone_epoch or rec.record_id in self._forgotten_ids:
                raise StaleProvenanceError(
                    f"record {rec.record_id} epoch={rec.epoch} < "
                    f"tombstone_epoch={self._tombstone_epoch}; "
                    f"liveness unproven, refuse to act"
                )
        return results


def act_on_deploy_target(client: MemoryClient) -> str:
    client.forget("m_4471")
    # A naive client would call client.read() here and act on m_4471.
    # The guarded client refuses until the read path catches up.
    records = client.safe_read("deploy target")
    if not records:
        raise StaleProvenanceError("no live deploy-target record after forget")
    return records[0].content_hash


if __name__ == "__main__":
    c = MemoryClient()
    try:
        act_on_deploy_target(c)
    except StaleProvenanceError as e:
        print(f"blocked: {e}")
