# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-forgotten-memory-on-rehydration-scoped-retention-tombstones-vs-snapshot-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-forgotten-memory-on-rehydration-scoped-retention-tombstones-vs-snapshot-replay.warrant.json
# Markdown SHA-256:   1bf2c164d20b51894ac1aebfd6055b4c3b3cbd4b736000d45c8d92678cfda8a1
# Code AST SHA-256:   9ea7371564e8ed8becb7531fa4dd04192ecc4fce7093ba1fce78035a0f05c7d6
# Verified Classes:   MemoryResurrectionError, Record, Snapshot
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class MemoryResurrectionError(RuntimeError):
    """Raised when a rehydrated memory violates the tombstone-inclusion invariant."""


@dataclass
class Record:
    key: str
    value: str
    written_at: float
    seq: int
    generation: int = 0


@dataclass
class Snapshot:
    payload: dict[str, Record]
    # Watermark must be the max seq of records ACTUALLY serialized, not log head.
    watermark: int
    # Tombstones folded into this snapshot, keyed by key -> seq of forget.
    tombstones: dict[str, int] = field(default_factory=dict)
    # Scope-level erasure generation at snapshot time.
    scope_generation: int = 0


def rehydrate(snapshot: Snapshot, oplog: list[tuple[str, str, int]]) -> dict[str, Record]:
    """
    oplog entries are (op, key, seq) with op in {"write", "forget"}.
    Replay must apply tombstones carried in the snapshot BEFORE payload,
    and must reject any payload record whose key is tombstoned at seq >= record.seq.
    """
    state: dict[str, Record] = {}

    # 1) Apply snapshot payload, but first validate against tombstone set.
    for key, rec in snapshot.payload.items():
        tomb_seq = snapshot.tombstones.get(key)
        if tomb_seq is not None and tomb_seq >= rec.seq:
            # The snapshot claims inclusion of a forget that should have removed this.
            raise MemoryResurrectionError(
                f"snapshot watermark={snapshot.watermark} includes tombstone "
                f"seq={tomb_seq} for key={key!r} but payload still carries "
                f"record seq={rec.seq}; snapshot/watermark non-atomic"
            )
        if rec.generation < snapshot.scope_generation:
            # Scope was erased after this record was written; drop it.
            continue
        state[key] = rec

    # 2) Replay oplog strictly above watermark, in seq order.
    for op, key, seq in sorted(oplog, key=lambda e: e[2]):
        if seq <= snapshot.watermark:
            continue
        if op == "forget":
            state.pop(key, None)
        elif op == "write":
            raise MemoryResurrectionError(
                f"oplog write for {key!r} at seq={seq} missing payload; "
                f"snapshot watermark={snapshot.watermark} is not a valid inclusion proof"
            )
        else:
            raise MemoryResurrectionError(f"unknown op {op!r} at seq={seq}")

    return state


def cold_start(snapshot: Snapshot, oplog: list[tuple[str, str, int]],
               required_keys: set[str]) -> dict[str, Record]:
    state = rehydrate(snapshot, oplog)
    missing = required_keys - state.keys()
    if missing:
        # Fail closed: do not silently re-plan around a resurrected/missing dependency.
        raise MemoryResurrectionError(
            f"required keys absent after rehydration: {sorted(missing)}"
        )
    return state
