# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-erases-a-memory-that-a-live-agent-s-context-still-cites-ttl-gdpr-erasure-propagation-versus-in-flight-context-citations.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-erases-a-memory-that-a-live-agent-s-context-still-cites-ttl-gdpr-erasure-propagation-versus-in-flight-context-citations.warrant.json
# Markdown SHA-256:   95d753afd5cf88723844975b41313bd73dd152a4c0553eb965f2424aa374ada1
# Code AST SHA-256:   52e992fc8729bc17aeee1c1f35cd6286b45d70cb60b9c3567d3f7f16abdf89bb
# Verified Classes:   ErasurePropagationError, Lease, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field

class ErasurePropagationError(RuntimeError):
    """Raised when a write or tool call references an erased/expired memory lease."""

@dataclass
class Lease:
    handle: str
    subject: str
    epoch: int
    expires_at: float
    content_hash: str

@dataclass
class MemoryStore:
    epochs: dict = field(default_factory=dict)          # subject -> current epoch
    erased_hashes: set = field(default_factory=set)     # bloom-filter stand-in
    records: dict = field(default_factory=dict)         # handle -> (subject, epoch, content)

    def read(self, subject: str, handle: str, content: str) -> Lease:
        epoch = self.epochs.get(subject, 0)
        h = hashlib.sha256(content.encode()).hexdigest()
        self.records[handle] = (subject, epoch, content)
        return Lease(handle, subject, epoch, time.time() + 3600, h)

    def forget(self, subject: str) -> int:
        # Eager fence: bump epoch, quarantine hashes, drop records.
        self.epochs[subject] = self.epochs.get(subject, 0) + 1
        n = 0
        for h, (s, e, c) in list(self.records.items()):
            if s == subject:
                self.erased_hashes.add(hashlib.sha256(c.encode()).hexdigest())
                del self.records[h]
                n += 1
        return n

    def validate_write(self, lease: Lease, derived_content: str) -> None:
        # C1: handle must still resolve to a live, same-epoch record.
        if lease.handle not in self.records:
            raise ErasurePropagationError(
                f"lease {lease.handle} unresolved; subject {lease.subject} erased"
            )
        # C2: epoch fencing.
        if self.epochs.get(lease.subject, 0) != lease.epoch:
            raise ErasurePropagationError(
                f"stale epoch {lease.epoch} != {self.epochs.get(lease.subject)}"
            )
        # C3: content-hash resurrection check on derived writes.
        if hashlib.sha256(derived_content.encode()).hexdigest() in self.erased_hashes:
            raise ErasurePropagationError("derived write resurrects erased content")

    def write(self, lease: Lease, derived_content: str) -> str:
        self.validate_write(lease, derived_content)
        handle = f"mem://{lease.subject}/derived-{len(self.records)}"
        self.records[handle] = (lease.subject, lease.epoch, derived_content)
        return handle

# Failure trace: agent holds a pre-erasure lease and attempts a derived write.
store = MemoryStore()
lease = store.read("S", "mem://S/r3", "prefers email contact at x@example.com")
store.forget("S")                       # controller issues GDPR erasure
store.write(lease, "user prefers email")  # raises ErasurePropagationError
