# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-when-a-forget-call-races-an-in-flight-write-against-the-same-memory-key.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-when-a-forget-call-races-an-in-flight-write-against-the-same-memory-key.warrant.json
# Markdown SHA-256:   03c799f067181089aeb421018c5db3b194b1853dd31446e16fcf53d4751a3528
# Code AST SHA-256:   99f1aad15b678addd8b6a03375540e372e9a2114014595a96c1af00fcb9d3efe
# Verified Classes:   ErasureBarrierViolation, MemoryStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ErasureBarrierViolation(RuntimeError):
    """Raised when a write attempts to commit under an epoch older than the key's erasure barrier."""
    pass


class MemoryStore:
    def __init__(self):
        self._rows = {}          # key -> (value, epoch)
        self._barriers = {}      # key -> barrier_epoch

    def forget(self, key: str, reason: str) -> dict:
        current = self._rows.get(key)
        next_epoch = (current[1] + 1) if current else 1
        self._barriers[key] = next_epoch
        self._rows.pop(key, None)
        return {"status": "erased", "barrier_epoch": next_epoch, "reason": reason}

    def write(self, key: str, value: str, epoch: int) -> dict:
        barrier = self._barriers.get(key, 0)
        if epoch < barrier:
            # Non-retryable: the content was erased; re-deriving it from agent state re-persists it.
            raise ErasureBarrierViolation(
                f"write to key={key!r} at epoch={epoch} precedes erasure barrier={barrier}; "
                f"discard this write, do not retry with a refreshed epoch"
            )
        self._rows[key] = (value, epoch)
        return {"status": "committed", "epoch": epoch}

    def read(self, key: str) -> str | None:
        barrier = self._barriers.get(key, 0)
        row = self._rows.get(key)
        if row is None or row[1] < barrier:
            return None
        return row[0]
