# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-a-memory-it-just-invalidated-contradiction-aware-invalidation-and-the-write-order-dependency-in-memory-tool-interfaces.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-a-memory-it-just-invalidated-contradiction-aware-invalidation-and-the-write-order-dependency-in-memory-tool-interfaces.warrant.json
# Markdown SHA-256:   240ef0c78ff111a845cfad1a4c2885057d17cb1c247e6ac13a956094a7925057
# Code AST SHA-256:   bd339a3b82f28d5c58a2a9777be9d5c329d5b3a01dd431b1cbf0dcb050ac4926
# Verified Classes:   MemoryResurrectionError, MemoryRecord, ContradictionAwareStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class MemoryResurrectionError(RuntimeError):
    """Raised when a read returns a record the write path already invalidated."""


@dataclass
class MemoryRecord:
    id: str
    key: str
    value: str
    created_at: float
    superseded_at: Optional[float] = None
    supersedes: list = field(default_factory=list)


class ContradictionAwareStore:
    """Toy store whose read path deliberately does NOT filter tombstones,
    to model the observed failure. Production stores must filter."""

    def __init__(self):
        self._records: dict[str, MemoryRecord] = {}
        self._seq = 0

    def write(self, key: str, value: str, supersedes: Optional[str] = None) -> dict:
        self._seq += 1
        now = time.time()
        rec = MemoryRecord(id=f"mem_{self._seq:04d}", key=key, value=value, created_at=now)
        invalidated = []
        if supersedes is not None:
            for r in self._records.values():
                if r.key == key and r.value == supersedes and r.superseded_at is None:
                    r.superseded_at = now
                    rec.supersedes.append(r.id)
                    invalidated.append(r.id)
        self._records[rec.id] = rec
        return {"status": "ok", "id": rec.id, "invalidated": invalidated}

    def read(self, key: str) -> list[MemoryRecord]:
        # BUG MODELED: returns tombstones; ranking ignores superseded_at.
        return [r for r in self._records.values() if r.key == key]


def invalidating_write_with_readback(
    store: ContradictionAwareStore, key: str, new_value: str, old_value: str
) -> str:
    ack = store.write(key=key, value=new_value, supersedes=old_value)
    if ack.get("status") != "ok":
        raise MemoryResurrectionError(f"write not acknowledged: {ack}")
    # Read-back assertion: the invalidated ids must not appear as live.
    results = store.read(key)
    for r in results:
        if r.id in ack["invalidated"] and r.superseded_at is None:
            raise MemoryResurrectionError(
                f"resurrection: {r.id} reported live after invalidation at write ack"
            )
    # The real failure: tombstoned record is still returned by read.
    live = [r for r in results if r.superseded_at is None]
    tombstoned = [r for r in results if r.superseded_at is not None]
    if tombstoned:
        raise MemoryResurrectionError(
            f"read surfaced {len(tombstoned)} tombstoned record(s) for key={key!r}; "
            f"read path does not filter superseded_at — refusing to act"
        )
    if not live:
        raise MemoryResurrectionError(f"no live record for key={key!r} after write")
    return live[0].value


if __name__ == "__main__":
    store = ContradictionAwareStore()
    store.write(key="region", value="us-east-1")
    try:
        invalidating_write_with_readback(store, "region", "eu-west-1", "us-east-1")
    except MemoryResurrectionError as e:
        print(f"HALTED: {e}")
