# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-ttl-based-forgetting-tombstone-has-been-resurrected-by-an-in-flight-episodic-write.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-ttl-based-forgetting-tombstone-has-been-resurrected-by-an-in-flight-episodic-write.warrant.json
# Markdown SHA-256:   d53a6118cd22d828b2bde99e3e95223b2b6ac102f9bfe2ffaba2fa359b3eb068
# Code AST SHA-256:   2a18a1b710c8448807706e016bb193ee17da49deaba28004771d60929715f896
# Verified Classes:   ResurrectionViolation, MemoryRecord, ScopedMemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResurrectionViolation(RuntimeError):
    """Raised when a write's lineage intersects a tombstone newer than its snapshot epoch."""
    pass


class MemoryRecord:
    def __init__(self, mem_id, payload, scope, snapshot_epoch, derived_from=None, ttl=3600):
        self.mem_id = mem_id
        self.payload = payload
        self.scope = scope
        self.snapshot_epoch = snapshot_epoch
        self.derived_from = derived_from or []
        self.ttl = ttl


class ScopedMemoryStore:
    def __init__(self):
        self.tombstones = {}       # mem_id -> tombstone_epoch
        self.records = {}          # mem_id -> MemoryRecord
        self.epoch = 0

    def forget(self, mem_id):
        self.epoch += 1
        self.tombstones[mem_id] = self.epoch
        self.records.pop(mem_id, None)
        return {"ok": True, "tombstone_epoch": self.epoch}

    def write(self, record):
        # Enforce the continuity invariant: no write whose causal snapshot
        # predates a tombstone in its lineage may become visible.
        for ancestor in record.derived_from:
            tomb = self.tombstones.get(ancestor)
            if tomb is not None and tomb > record.snapshot_epoch:
                raise ResurrectionViolation(
                    f"write {record.mem_id} derives from {ancestor} "
                    f"tombstoned at epoch {tomb} but snapshotted at "
                    f"{record.snapshot_epoch}; erasure would be resurrected"
                )
        self.epoch += 1
        self.records[record.mem_id] = record
        return {"ok": True, "commit_epoch": self.epoch}

    def retrieve(self, scope, query):
        # Scoped retrieval must filter on lineage closure, not just primary ids.
        tombstoned = set(self.tombstones)
        out = []
        for rec in self.records.values():
            if rec.scope != scope:
                continue
            if any(a in tombstoned for a in rec.derived_from):
                continue
            out.append(rec)
        return out


def distill_and_write(store, source_id, summary, scope, snapshot_epoch):
    src = store.records.get(source_id)
    if src is None and source_id in store.tombstones:
        # The agent still holds the payload in context; it must not re-emit it.
        raise ResurrectionViolation(
            f"source {source_id} is tombstoned; distillation of in-context "
            f"payload is prohibited, re-derive from a post-tombstone source"
        )
    rec = MemoryRecord(
        mem_id=f"{source_id}_v2",
        payload=summary,
        scope=scope,
        snapshot_epoch=snapshot_epoch,
        derived_from=[source_id],
    )
    return store.write(rec)


if __name__ == "__main__":
    store = ScopedMemoryStore()
    store.write(MemoryRecord("mem_4471", "billing address ...", "user:alice",
                             snapshot_epoch=9179))
    store.forget("mem_4471")  # tombstone_epoch = 9181
    # Agent's context still holds the payload; snapshot_epoch predates tombstone.
    distill_and_write(store, "mem_4471", "distilled billing info", "user:alice",
                      snapshot_epoch=9179)  # raises ResurrectionViolation
