Skip to main content

mnemo_engine/store/
open.rs

1//! Create, open (read-write, read-only, raw key) and the handle's basic accessors and per-handle settings.
2
3use super::*;
4
5/// Chunk size for the torn-header scan's streaming read of the file.
6/// We walk the file 1 MiB at a time looking for 8 KiB-aligned `MWAL`
7/// magic. There is **no** cap on how far a given candidate's frame
8/// chain may extend — a 1M-vector IVF+PQ relocation can push a single
9/// transaction well past 16 MiB — so each candidate is read frame by
10/// frame via [`wal::scan_committed_txn`] rather than slurped into a
11/// bounded buffer. (DUR-1 R-002.1 part 2.)
12const TORN_HEADER_SCAN_CHUNK: usize = 1 << 20; // 1 MiB
13
14/// Walk the file for every 8 KiB-aligned page whose first four bytes are
15/// `MWAL`, treating each as a candidate WAL-region start, and return the
16/// frames of the highest-`txn_id` committed transaction whose header
17/// frame fully validates under `passphrase`.
18///
19/// A candidate is accepted only if:
20/// * `wal::scan_committed_txn` returns a committed transaction (chained
21///   CRC verifies, single `txn_id`, `KIND_COMMIT` closes it);
22/// * that transaction contains a `(0, header_page)` frame;
23/// * the header parses with `wal_start == candidate_page_no` and
24///   `wal_seq == txn_id` (so a frame cannot forge a region it was not
25///   written into);
26/// * deriving the KEK from `passphrase + header.salt`, unwrapping the
27///   wrapped DEK, and validating the header seal all succeed.
28///
29/// Returns `Ok(None)` when the scan finds no valid candidate — the
30/// caller is expected to propagate the original parse error so
31/// non-mnemo files still report `BadMagic`.
32///
33/// DUR-1 (R-002.1 part 2): there is no fixed scan window — the whole
34/// file is scanned. Reading at page granularity (not byte granularity)
35/// is sufficient because every WAL region in the format is page-aligned
36/// and every WAL commit writes its first frame at the region's start.
37fn scan_header_recovery_candidates(
38    file: &mut File,
39    secret: &[u8],
40) -> Result<Option<Vec<wal::Frame>>> {
41    let file_len = file.seek(SeekFrom::End(0))?;
42    if file_len < PAGE_SIZE as u64 * 2 {
43        return Ok(None); // No room for even one WAL page past the header.
44    }
45
46    let mut best: Option<(u64, Vec<wal::Frame>)> = None;
47    let page_sz = PAGE_SIZE as u64;
48    let mut offset = page_sz; // Skip page 0.
49
50    // Stream through the file in 1 MiB chunks, scanning each chunk for
51    // page-aligned `MWAL` candidates. Each candidate's frame chain is
52    // then read incrementally via `wal::scan_committed_txn`, which has
53    // no window cap — a 1M-vector IVF+PQ relocation can span tens of
54    // MiB in one committed transaction.
55    let mut chunk = vec![0u8; TORN_HEADER_SCAN_CHUNK];
56    while offset < file_len {
57        let want = (TORN_HEADER_SCAN_CHUNK as u64).min(file_len - offset) as usize;
58        chunk.resize(want, 0);
59        file.seek(SeekFrom::Start(offset))?;
60        let mut filled = 0;
61        while filled < want {
62            match file.read(&mut chunk[filled..])? {
63                0 => break,
64                n => filled += n,
65            }
66        }
67        if filled == 0 {
68            break;
69        }
70        let mut inner = 0usize;
71        while inner + 4 <= filled {
72            if &chunk[inner..inner + 4] == wal::FRAME_MAGIC_BYTES {
73                let page_no = (offset + inner as u64) / page_sz;
74                if let Some((txn_id, frames)) = try_recover_candidate(file, page_no, secret)? {
75                    let keep = match &best {
76                        None => true,
77                        Some((id, _)) => txn_id > *id,
78                    };
79                    if keep {
80                        best = Some((txn_id, frames));
81                    }
82                }
83            }
84            inner += PAGE_SIZE;
85        }
86        offset += filled as u64;
87    }
88
89    Ok(best.map(|(_, f)| f))
90}
91
92/// Try to recover a committed transaction from `candidate_page_no`,
93/// returning `(txn_id, frames)` only if the candidate's
94/// `(0, header_page)` frame fully validates: the frame chain commits
95/// (via [`wal::scan_committed_txn`]'s streaming reader), the header
96/// parses with `wal_start == candidate_page_no` **and**
97/// `wal_seq == txn_id`, the DEK unwraps under `passphrase`, and the
98/// AES-GCM seal validates. DUR-1 (R-002.1 item 2) requires the
99/// `wal_seq == txn_id` check and no fixed scan window — the streaming
100/// reader handles transactions of arbitrary size.
101fn try_recover_candidate(
102    file: &mut File,
103    candidate_page_no: u64,
104    secret: &[u8],
105) -> Result<Option<(u64, Vec<wal::Frame>)>> {
106    let Some((txn_id, frames)) = wal::scan_committed_txn(file, candidate_page_no)? else {
107        return Ok(None);
108    };
109
110    // Must contain a header frame at page 0.
111    let header_bytes = match frames.iter().find(|(p, _)| *p == 0) {
112        Some((_, b)) => b,
113        None => return Ok(None),
114    };
115    if header_bytes.len() != PAGE_SIZE {
116        return Ok(None);
117    }
118    let mut hbuf = [0u8; PAGE_SIZE];
119    hbuf.copy_from_slice(header_bytes);
120    let candidate = match Header::from_page(&hbuf) {
121        Ok(h) => h,
122        Err(_) => return Ok(None),
123    };
124
125    // The frame's claimed region must match where we found it, and the
126    // header frame's `wal_seq` must match the committed transaction's
127    // `txn_id` — this is what pins the frame to the region it was
128    // written into and keeps a stale checkpointed-and-copied frame
129    // from being accepted as a new region's root.
130    if candidate.wal_start != candidate_page_no || candidate.wal_seq != txn_id {
131        return Ok(None);
132    }
133    // DEK unwrap under this candidate's own salt + KDF params.
134    let kdf = KdfParams {
135        m_cost: candidate.m_cost,
136        t_cost: candidate.t_cost,
137        p_cost: candidate.p_cost,
138    };
139    let kek = match crypto::derive_kek(secret, &candidate.salt, kdf) {
140        Ok(k) => k,
141        Err(_) => return Ok(None),
142    };
143    let dek = match crypto::unwrap_dek(&kek, &candidate.dek_nonce, &candidate.wrapped_dek) {
144        Ok(d) => d,
145        Err(_) => return Ok(None),
146    };
147    if candidate.validate_seal(&dek).is_err() {
148        return Ok(None);
149    }
150
151    Ok(Some((txn_id, frames)))
152}
153
154impl Mnemo {
155    /// Create a brand-new encrypted database at `path`.
156    pub fn create(
157        path: impl Into<PathBuf>,
158        passphrase: &str,
159        config: MnemoConfig,
160    ) -> Result<Mnemo> {
161        Self::create_secret(path, passphrase.as_bytes(), config)
162    }
163
164    /// PERF-1 step 7 (R-004.5): create a database unlocked by a **raw
165    /// 256-bit key** instead of a passphrase, for keys held by an OS
166    /// keychain or keystore. The key must be uniformly random (see
167    /// [`Mnemo::generate_key`]); it gets no stretching. The header records
168    /// minimal Argon2id parameters ([`KdfParams::raw_key`]), so opening
169    /// costs microseconds instead of tens of milliseconds. `config.kdf` is
170    /// ignored. No format change: the key goes through the same KEK
171    /// derivation a passphrase does.
172    pub fn create_with_key(
173        path: impl Into<PathBuf>,
174        key: &[u8; crypto::KEY_LEN],
175        config: MnemoConfig,
176    ) -> Result<Mnemo> {
177        let config = MnemoConfig {
178            kdf: KdfParams::raw_key(),
179            ..config
180        };
181        Self::create_secret(path, key, config)
182    }
183
184    /// A fresh random 256-bit key for [`Mnemo::create_with_key`], from the
185    /// thread-local CSPRNG (seeded from the OS). Store it in a keychain;
186    /// it can't be recovered from the file.
187    pub fn generate_key() -> [u8; crypto::KEY_LEN] {
188        *crypto::random_dek()
189    }
190
191    pub(super) fn create_secret(
192        path: impl Into<PathBuf>,
193        secret: &[u8],
194        config: MnemoConfig,
195    ) -> Result<Mnemo> {
196        let path: PathBuf = path.into();
197        if config.dimensions == 0 {
198            return Err(MnemoError::Invalid("dimensions must be > 0".into()));
199        }
200        let version = resolve_format_version(config.format_version)?;
201        if version >= VERSION_V9 && veccol::per_page(config.dimensions) == 0 {
202            return Err(MnemoError::Invalid(format!(
203                "a v9 file supports up to {} dimensions for now (one fp16 vector \
204                 must fit a page); vector entries that span pages are not supported yet",
205                (PAYLOAD - veccol::PAGE_HEADER - 4) / 2
206            )));
207        }
208        let flags = if version >= VERSION_V9 && config.store_float_vectors {
209            FLAG_ENCRYPTED | FLAG_FLOAT_VECTORS
210        } else {
211            FLAG_ENCRYPTED
212        };
213        // Exclusive lock covers the write path; second writer sees `Locked`.
214        let file = open_with_lock(&path, /*write=*/ true, /*create=*/ true)?;
215
216        let salt = crypto::random_salt();
217        let dek = crypto::random_dek();
218        let kek = crypto::derive_kek(secret, &salt, config.kdf)?;
219        let dek_nonce = crypto::random_nonce();
220        let wrapped = crypto::wrap_dek(&kek, &dek_nonce, &dek)?;
221        if wrapped.len() != WRAPPED_DEK_LEN {
222            return Err(MnemoError::Crypto("unexpected wrapped DEK length".into()));
223        }
224        let mut wrapped_dek = [0u8; WRAPPED_DEK_LEN];
225        wrapped_dek.copy_from_slice(&wrapped);
226
227        let mut header = Header {
228            version,
229            page_size: PAGE_SIZE as u32,
230            flags,
231            dimensions: config.dimensions as u32,
232            created_at: memory::now_secs(),
233            write_counter: 0,
234            // Page 0 is the header; pages 1..=wal_pages are the WAL;
235            // record/catalog/index pages start after it. Initial WAL size is
236            // chosen per-config (default 8 pages = 64 KiB) and clamped to a
237            // sane floor so the first transaction can always commit.
238            next_page: 1 + config.wal_pages_initial.max(MIN_WAL_PAGES),
239            catalog_start: 0,
240            catalog_pages: 0,
241            catalog_len: 0,
242            vector_count: 0,
243            m_cost: config.kdf.m_cost,
244            t_cost: config.kdf.t_cost,
245            p_cost: config.kdf.p_cost,
246            salt,
247            dek_nonce,
248            wrapped_dek,
249            index_start: 0,
250            index_pages: 0,
251            index_len: 0,
252            wal_start: 1,
253            wal_pages: config.wal_pages_initial.max(MIN_WAL_PAGES),
254            wal_seq: 0,
255            manifest_start: 0,
256            manifest_pages: 0,
257            manifest_len: 0,
258            // Regenerated per write by `apply_seal`; `None` until we seal.
259            seal_nonce: None,
260            seal_tag: None,
261            // v8+ result-cache pointer — zero-initialized on create,
262            // populated only when `cache_put` runs at least once and
263            // the next `flush` seals a directory run.
264            cache_start: 0,
265            cache_pages: 0,
266            cache_len: 0,
267            // FMT-9 v9 fields; all zero on a fresh file (and unused on v8).
268            catalog_gen: 0,
269            index_gen: 0,
270            manifest_gen: 0,
271            cache_gen: 0,
272            free: RunPtr::default(),
273            keys: RunPtr::default(),
274            bm25: RunPtr::default(),
275            index_delta: RunPtr::default(),
276            catalog_delta: RunPtr::default(),
277        };
278
279        let mut pager = Pager::new(file, dek, 0, version);
280        let mut page = header.to_page();
281        header.apply_seal(&mut page, pager.dek())?;
282        pager.write_raw(0, &page)?;
283        pager.sync()?;
284
285        Ok(Mnemo {
286            pager,
287            header,
288            catalog: Vec::new(),
289            index: IdIndex::default(),
290            path,
291            dimensions: config.dimensions,
292            kdf: config.kdf,
293            dirty_catalog: false,
294            ann: None,
295            dirty_index: false,
296            index_persist: IndexPersist::default(),
297            ann_unloaded: false,
298            manifest: Vec::new(),
299            // FMT-9c: v9 keeps fewer snapshots by default: with page reuse,
300            // retention is what pins pages.
301            max_snapshots: if version >= VERSION_V9 && config.max_snapshots == DEFAULT_MAX_SNAPSHOTS
302            {
303                V9_DEFAULT_MAX_SNAPSHOTS
304            } else {
305                config.max_snapshots
306            },
307            read_only: false,
308            cache_dir: Vec::new(),
309            cache_idx: DirectoryIndex::new(),
310            dirty_cache: false,
311            cache_budgets: std::collections::HashMap::new(),
312            cache_flush_policy: CacheFlushPolicy::default(),
313            cache_batch: BatchState::default(),
314            cache_counters: CounterState::default(),
315            embedder: None,
316            fsyncs_last_flush: 0,
317            agent_set: None,
318            key_index: None,
319            superseded: None,
320            layers: None,
321            turn_compress_after: DEFAULT_TURN_COMPRESS_AFTER_SECS,
322            free: FreeList::default(),
323            pending_free: Vec::new(),
324            free_dirty: false,
325            key_slots: KeySlotRun::default(),
326            dirty_keys: false,
327            gen_leased: false,
328            col: VecColumn::default(),
329            recs: RecPages::default(),
330            bm25: Bm25State::default(),
331            kw: None,
332            index_layout_override: None,
333            dirty_rows: std::collections::BTreeSet::new(),
334            delta_chain: Vec::new(),
335            delta_rows: 0,
336            catalog_rewrite: false,
337            index_chain: Vec::new(),
338            index_chain_ops: 0,
339            index_rebase: false,
340            index_delta_ops: None,
341            snapshot_cap_explicit: config.max_snapshots != DEFAULT_MAX_SNAPSHOTS,
342            direct_writes: false,
343            vector_cache_budget: DEFAULT_VECTOR_CACHE_BUDGET,
344        })
345    }
346
347    /// Open an existing database. A wrong passphrase fails cleanly with
348    /// [`MnemoError::WrongPassphrase`]. Takes an OS exclusive lock for
349    /// the lifetime of the returned handle; a second concurrent open
350    /// (from any process) returns [`MnemoError::Locked`].
351    ///
352    /// For a caller that only needs to read (and can tolerate the
353    /// pending-recovery / pending-migration cases documented on
354    /// [`Mnemo::open_read_only`]), prefer that entry point — it takes a
355    /// shared lock and coexists with other readers.
356    pub fn open(path: impl Into<PathBuf>, passphrase: &str) -> Result<Mnemo> {
357        Self::open_secret(path, passphrase.as_bytes())
358    }
359
360    /// PERF-1 step 7: open a database created by [`Mnemo::create_with_key`]
361    /// (or rekeyed with [`Mnemo::rekey_with_key`]) with its raw key.
362    pub fn open_with_key(path: impl Into<PathBuf>, key: &[u8; crypto::KEY_LEN]) -> Result<Mnemo> {
363        Self::open_secret(path, key)
364    }
365
366    pub(super) fn open_secret(path: impl Into<PathBuf>, secret: &[u8]) -> Result<Mnemo> {
367        Self::open_secret_with(path, secret, false)
368    }
369
370    /// The read-write open. `allow_old` lets a file older than v9 open (and
371    /// migrate in memory to v8): only compaction uses it, to read a v4–v8
372    /// file and write the v9 copy. Every public read-write open refuses
373    /// those with [`MnemoError::FormatTooOld`] (the v8 sunset, v0.13).
374    pub(super) fn open_secret_with(
375        path: impl Into<PathBuf>,
376        secret: &[u8],
377        allow_old: bool,
378    ) -> Result<Mnemo> {
379        let path: PathBuf = path.into();
380        let mut file = open_with_lock(&path, /*write=*/ true, /*create=*/ false)?;
381
382        let mut hbuf = [0u8; PAGE_SIZE];
383        file.seek(SeekFrom::Start(0))?;
384        file.read_exact(&mut hbuf)?;
385        let mut header = match Header::from_page(&hbuf) {
386            Ok(h) => h,
387            Err(e) => {
388                // DUR-1 (R-002.1 part 2+3): page 0 did not parse — any
389                // error is treated as a torn-header candidate, not just
390                // `HeaderChecksum`. The whole 294-byte header lives in
391                // the first 512-byte sector, so the realistic failure is
392                // the sector zeroed or garbled, which returns `BadMagic`
393                // or `UnsupportedVersion` *before* the CRC gate.
394                //
395                // Scan the file for valid committed header-frame WAL
396                // regions, pick the highest `txn_id`, and replay it. If
397                // nothing valid is found, return the *original* error so
398                // non-mnemo files still report `BadMagic`.
399                let scan = scan_header_recovery_candidates(&mut file, secret)?;
400                let frames = scan.ok_or(e)?;
401                for (page_no, bytes) in &frames {
402                    if bytes.len() != PAGE_SIZE {
403                        return Err(MnemoError::Invalid("WAL frame is not page-sized".into()));
404                    }
405                    file.seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
406                    file.write_all(bytes)?;
407                }
408                file.sync_all()?;
409                crate::bump_fsync();
410                file.seek(SeekFrom::Start(0))?;
411                file.read_exact(&mut hbuf)?;
412                Header::from_page(&hbuf)?
413            }
414        };
415
416        // Crash recovery: replay a committed-but-uncheckpointed transaction.
417        // Each frame is a finished page image; the header frame, replayed to
418        // page 0, supersedes the header just read.
419        if let Some(frames) = wal::recover(
420            &mut file,
421            header.wal_start,
422            header.wal_pages,
423            header.wal_seq,
424        )? {
425            for (page_no, bytes) in &frames {
426                if bytes.len() != PAGE_SIZE {
427                    return Err(MnemoError::Invalid("WAL frame is not page-sized".into()));
428                }
429                file.seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
430                file.write_all(bytes)?;
431            }
432            file.sync_all()?;
433            crate::bump_fsync();
434            // Re-read the now-current header from the replayed page 0.
435            file.seek(SeekFrom::Start(0))?;
436            file.read_exact(&mut hbuf)?;
437            header = Header::from_page(&hbuf)?;
438        }
439
440        let kdf = KdfParams {
441            m_cost: header.m_cost,
442            t_cost: header.t_cost,
443            p_cost: header.p_cost,
444        };
445        let kek = crypto::derive_kek(secret, &header.salt, kdf)?;
446        let dek = crypto::unwrap_dek(&kek, &header.dek_nonce, &header.wrapped_dek)?;
447
448        // Validate the v7 header seal now that we have the DEK. Returns
449        // `MnemoError::HeaderTampered` if any of the sealed mutable fields
450        // were rewritten after the last legitimate flush. No-op for v6 and
451        // older — pre-v7 files don't carry a seal.
452        //
453        // DUR-1 (Planner decision 2026-11-01, Option B): a seal failure is
454        // **always** reported as tampering, never auto-healed. R-002.1
455        // part 3's seal-mismatch WAL fallback is withdrawn: the seal
456        // exists for tamper-evidence; silently loading a stale committed
457        // header from the WAL would erase that evidence. A real crash
458        // cannot produce "CRC valid + seal invalid" either, because the
459        // whole 294-byte header lies inside sector 0 which storage
460        // writes atomically — a torn sector breaks magic, version or
461        // CRC first, and *those* are healed by the scan above.
462        header.validate_seal(&dek)?;
463
464        // Build the pager at the file's *current* version so initial reads
465        // use the matching AAD scheme — `Pager::page_aad` returns empty AAD
466        // for v4/v5 (no page binding) and `page_no.to_le_bytes()` for v6+.
467        let on_disk_version = header.version;
468        // The v8 sunset (v0.13): a read-write handle is v9. Older files open
469        // read-only (v8) or through `compact_file`, which converts them.
470        if !allow_old && on_disk_version < VERSION_V9 {
471            return Err(MnemoError::FormatTooOld {
472                version: on_disk_version,
473            });
474        }
475        let mut pager = Pager::new(file, dek, header.write_counter, on_disk_version);
476        let dimensions = header.dimensions as usize;
477
478        // === v4→v5 catalog migration =====================================
479        // v6 reads directly; v5 reads directly; v4 replays the catalog into
480        // the v5 shape by reading each memory's body to populate the new
481        // `accessed_at` / `access_count` fields. All page reads here still
482        // use the v4/v5 AAD scheme (none).
483        let (catalog, migrated_from_v4) = if on_disk_version >= 5 {
484            (
485                load_catalog(
486                    &mut pager,
487                    header.catalog_start,
488                    header.catalog_pages,
489                    header.catalog_len,
490                    header.catalog_gen,
491                )?,
492                false,
493            )
494        } else if on_disk_version == 4 {
495            let v4 = load_catalog_v4(
496                &mut pager,
497                header.catalog_start,
498                header.catalog_pages,
499                header.catalog_len,
500            )?;
501            (migrate_v4_catalog(&mut pager, v4)?, true)
502        } else {
503            return Err(MnemoError::UnsupportedVersion(on_disk_version));
504        };
505        // FMT-9c.2: replay the v9 delta chain onto the base catalog.
506        let (catalog, delta_chain, delta_rows) =
507            apply_delta_chain(&mut pager, catalog, header.catalog_delta)?;
508        let index = build_id_index(&catalog);
509        // PERF-1 step 3: the ANN index loads on first use, not at open. A
510        // v5→v6 page migration is the exception: it must read the index
511        // now, under the old page AAD, to rewrite it.
512        let ann = if on_disk_version < 6 {
513            load_index(
514                &mut pager,
515                header.index_start,
516                header.index_pages,
517                header.index_len,
518                header.index_gen,
519                dimensions,
520            )?
521        } else {
522            None
523        };
524        let ann_unloaded = ann.is_none() && header.index_pages > 0;
525        let mut manifest = load_manifest(
526            &mut pager,
527            header.manifest_start,
528            header.manifest_pages,
529            header.manifest_len,
530            header.manifest_gen,
531        )?;
532
533        // === v5→v6 page-encryption migration =============================
534        // Pre-v6 data pages were encrypted under no AAD; v6 binds the home
535        // `page_no` as AAD so a page-transplant attack fails authentication
536        // on read. Re-stage every live record page through `write_page` so
537        // the next flush re-encrypts it under v6 AAD at the same home slot.
538        // Tombstoned entries skip — they're reclaimed by `compact_file`.
539        // Old catalog / ANN / manifest pages stay as orphan ciphertext;
540        // the next flush writes the new runs at fresh slots.
541        let migrated_pages_to_v6 = on_disk_version < 6;
542        if migrated_pages_to_v6 {
543            for e in &catalog {
544                if e.deleted {
545                    continue;
546                }
547                for i in 0..e.page_count as u64 {
548                    let payload = pager.read_page(e.start_page + i, 0)?;
549                    pager.write_page(e.start_page + i, 0, &payload)?;
550                }
551            }
552            pager.set_version(6);
553        }
554
555        // === v6→v7 header-seal migration =================================
556        // v7 adds an AES-GCM seal at the tail of the header page that
557        // authenticates every mutable header field. Pre-v7 files have no
558        // seal — we just bump the version in memory and mark `dirty_catalog`
559        // so the next flush writes a sealed v7 header. Pages are untouched
560        // (page crypto is unchanged from v6).
561        let migrated_header_to_v7 = on_disk_version < 7;
562        if migrated_header_to_v7 {
563            pager.set_version(7);
564        }
565
566        // === v7→v8 cache-directory migration =============================
567        // v8 adds three u64 header fields (cache_start/pages/len) for the
568        // result-cache directory (Phase 10.1). Pre-v8 files have those
569        // three bytes as zero (the on-disk region beyond the v7 seal is
570        // zero-initialized), which is the legal "empty cache directory"
571        // state — no data migration required. We bump the version in
572        // memory and mark dirty_catalog so the next flush writes a
573        // v8-sealed header with the new AAD shape covering the cache
574        // pointer. Pages are untouched.
575        let migrated_header_to_v8 = on_disk_version < 8;
576        if migrated_header_to_v8 {
577            pager.set_version(VERSION);
578        }
579
580        let migrated = migrated_from_v4
581            || migrated_pages_to_v6
582            || migrated_header_to_v7
583            || migrated_header_to_v8;
584        if migrated {
585            // Stamp the version forward in memory; the next flush persists
586            // it via the WAL-committed header frame (and the v7 seal).
587            header.version = VERSION;
588            // Snapshots written under an older format reference page runs
589            // encrypted under the old AAD scheme; this build can't decrypt
590            // them under the new pager. Drop the manifest so the next
591            // flush records a fresh snapshot of the migrated state.
592            // Point-in-time recovery into the pre-migration past is
593            // sacrificed for migration simplicity. Old pages remain on
594            // disk until `compact_file`. (For v6→v7 alone — which doesn't
595            // change page crypto — the old snapshots would technically
596            // still be readable, but dropping them uniformly keeps the
597            // migration policy simple.)
598            manifest.clear();
599        }
600
601        // The ANN index pages on disk were sealed under the *old* AAD scheme
602        // if we migrated pages to v6; force a rewrite at fresh v6-encrypted
603        // slots on the next flush so a future reopen doesn't try to read
604        // them under the new AAD and fail. (Catalog and manifest already
605        // get rewritten via dirty_catalog and the manifest.clear() above.)
606        let dirty_index = migrated_pages_to_v6 && ann.is_some();
607
608        // Load the cache directory (v8+ only). Pre-v8 files have
609        // cache_pages == 0 by header layout, so this trivially yields
610        // an empty directory without touching the disk.
611        let cache_dir = load_cache_directory(
612            &mut pager,
613            header.cache_start,
614            header.cache_pages,
615            header.cache_len,
616            header.cache_gen,
617        )?;
618        let cache_idx = DirectoryIndex::build(&cache_dir);
619        // FMT-9 (a)/(b): the free list and key-slot run (empty pointers on
620        // v8, so these don't touch the disk there).
621        let free = load_free_list(&mut pager, header.free)?;
622        let key_slots = load_key_slots(&mut pager, header.keys)?;
623        let col = VecColumn::from_catalog(&catalog);
624        let recs = RecPages::from_catalog(&catalog);
625        let bm25_manifest = load_bm25_manifest(&mut pager, header.bm25)?;
626        let max_snapshots = if header.version >= VERSION_V9 {
627            V9_DEFAULT_MAX_SNAPSHOTS
628        } else {
629            DEFAULT_MAX_SNAPSHOTS
630        };
631
632        Ok(Mnemo {
633            pager,
634            header,
635            catalog,
636            index,
637            path,
638            dimensions,
639            kdf,
640            dirty_catalog: migrated,
641            ann,
642            dirty_index,
643            // A v5→v6 page migration leaves the index sealed under the old
644            // page AAD, so it must be rewritten on the next flush.
645            index_persist: IndexPersist {
646                forced: dirty_index,
647                ..IndexPersist::default()
648            },
649            ann_unloaded,
650            manifest,
651            // `Mnemo::open` has no [`MnemoConfig`] to read; default the cap
652            // to [`DEFAULT_MAX_SNAPSHOTS`]. Override with
653            // [`Mnemo::set_max_snapshots`] right after open if you need
654            // unlimited retention or a different cap for this handle.
655            max_snapshots,
656            read_only: false,
657            cache_dir,
658            cache_idx,
659            dirty_cache: false,
660            cache_budgets: std::collections::HashMap::new(),
661            cache_flush_policy: CacheFlushPolicy::default(),
662            cache_batch: BatchState::default(),
663            cache_counters: CounterState::default(),
664            embedder: None,
665            fsyncs_last_flush: 0,
666            agent_set: None,
667            key_index: None,
668            superseded: None,
669            layers: None,
670            turn_compress_after: DEFAULT_TURN_COMPRESS_AFTER_SECS,
671            free,
672            pending_free: Vec::new(),
673            free_dirty: false,
674            key_slots,
675            dirty_keys: false,
676            gen_leased: false,
677            col,
678            recs,
679            bm25: Bm25State {
680                manifest: bm25_manifest,
681                ..Bm25State::default()
682            },
683            kw: None,
684            index_layout_override: None,
685            dirty_rows: std::collections::BTreeSet::new(),
686            delta_chain,
687            delta_rows,
688            catalog_rewrite: false,
689            index_chain: Vec::new(),
690            index_chain_ops: 0,
691            index_rebase: false,
692            index_delta_ops: None,
693            snapshot_cap_explicit: false,
694            direct_writes: false,
695            vector_cache_budget: DEFAULT_VECTOR_CACHE_BUDGET,
696        })
697    }
698
699    /// Open an existing database in **read-only** mode. Takes an OS shared
700    /// lock; multiple read-only handles can coexist, but any attempt to
701    /// open the same file read-write elsewhere returns
702    /// [`MnemoError::Locked`]. All mutating methods on the returned handle
703    /// return [`MnemoError::ReadOnly`], including `recall` with
704    /// `track_access(true)`.
705    ///
706    /// Two conditions block a read-only open and return
707    /// [`MnemoError::NeedsWriteOpen`]:
708    ///
709    /// 1. The file has a committed-but-uncheckpointed WAL transaction that
710    ///    would ordinarily be replayed on open. A read-only handle
711    ///    cannot write the recovered pages back.
712    /// 2. The on-disk format version is older than the current
713    ///    `format::VERSION`, requiring an on-disk migration.
714    ///
715    /// In either case, open the file read-write once (which recovers /
716    /// migrates in place), close the handle cleanly, and reopen
717    /// read-only. This is documented in the README's Durability section.
718    pub fn open_read_only(path: impl Into<PathBuf>, passphrase: &str) -> Result<Mnemo> {
719        Self::open_read_only_secret(path, passphrase.as_bytes())
720    }
721
722    /// PERF-1 step 7: [`Mnemo::open_read_only`] for a raw-key database.
723    pub fn open_read_only_with_key(
724        path: impl Into<PathBuf>,
725        key: &[u8; crypto::KEY_LEN],
726    ) -> Result<Mnemo> {
727        Self::open_read_only_secret(path, key)
728    }
729
730    /// Whether `key` opens the raw-key file at `path`, decided from its
731    /// header alone: no catalog load, no lock, microseconds. `Ok(false)` is
732    /// "not this key". Unlike a read-only open, it answers for a file that
733    /// has a WAL transaction to recover (the state a kill between a commit
734    /// and its checkpoint leaves), so a caller trying each of its keys in
735    /// turn isn't stopped by [`MnemoError::NeedsWriteOpen`]. A torn header is
736    /// judged from the WAL frame that would heal it. Other failures (not a
737    /// `.mnemo` file, a tampered header, an I/O error) are errors. Added in
738    /// v0.12.2 (RB-001.23).
739    pub fn key_opens(
740        path: impl AsRef<std::path::Path>,
741        key: &[u8; crypto::KEY_LEN],
742    ) -> Result<bool> {
743        let mut file = File::open(path.as_ref())?;
744        let mut hbuf = [0u8; PAGE_SIZE];
745        file.seek(SeekFrom::Start(0))?;
746        file.read_exact(&mut hbuf)?;
747        let header = match Header::from_page(&hbuf) {
748            Ok(h) => h,
749            // A candidate frame only counts when it validates with `key`.
750            Err(parse_err) => {
751                return match scan_header_recovery_candidates(&mut file, key)? {
752                    Some(_) => Ok(true),
753                    None => Err(parse_err),
754                }
755            }
756        };
757        let kdf = KdfParams {
758            m_cost: header.m_cost,
759            t_cost: header.t_cost,
760            p_cost: header.p_cost,
761        };
762        let kek = crypto::derive_kek(key, &header.salt, kdf)?;
763        let dek = match crypto::unwrap_dek(&kek, &header.dek_nonce, &header.wrapped_dek) {
764            Ok(dek) => dek,
765            Err(MnemoError::WrongPassphrase) => return Ok(false),
766            Err(e) => return Err(e),
767        };
768        header.validate_seal(&dek)?;
769        Ok(true)
770    }
771
772    pub(super) fn open_read_only_secret(path: impl Into<PathBuf>, secret: &[u8]) -> Result<Mnemo> {
773        let path: PathBuf = path.into();
774        let mut file = open_with_lock(&path, /*write=*/ false, /*create=*/ false)?;
775
776        let mut hbuf = [0u8; PAGE_SIZE];
777        file.seek(SeekFrom::Start(0))?;
778        file.read_exact(&mut hbuf)?;
779        // A torn header on a read-only open cannot be healed (that requires
780        // writing recovered frames back). Surface as `NeedsWriteOpen` so the
781        // caller knows to reopen read-write once. DUR-1 (R-002.1 part 4):
782        // any `Header::from_page` failure (`BadMagic`,
783        // `UnsupportedVersion`, `HeaderChecksum`) qualifies — but only
784        // when the file-wide scan actually finds a valid committed
785        // header frame to recover from, so a non-mnemo file still
786        // reports `BadMagic` cleanly. A `validate_seal` failure is NOT
787        // routed here (Option B: tampering is never auto-healed).
788        let header = match Header::from_page(&hbuf) {
789            Ok(h) => h,
790            Err(parse_err) => {
791                let recoverable = scan_header_recovery_candidates(&mut file, secret)?;
792                return Err(match (parse_err, recoverable) {
793                    (_, Some(_)) => MnemoError::NeedsWriteOpen {
794                        reason: "torn header page needs recovery from WAL",
795                    },
796                    (e, None) => e,
797                });
798            }
799        };
800
801        // Refuse to migrate on read-only opens. v6→v7 is header-only
802        // (no page writes required), but even that bumps `version` on
803        // disk and re-seals the header — which needs write access. Keep
804        // the policy uniform across all sub-version bumps.
805        // A v4–v7 file needs migrating, which a read-only handle can't do,
806        // and since v0.13 no read-write handle opens it either: compaction
807        // converts it to v9.
808        if header.version < VERSION {
809            return Err(MnemoError::FormatTooOld {
810                version: header.version,
811            });
812        }
813
814        // Refuse if there is a committed-but-uncheckpointed transaction
815        // waiting for `wal::recover` to fold it into home pages.
816        if wal::recover(
817            &mut file,
818            header.wal_start,
819            header.wal_pages,
820            header.wal_seq,
821        )?
822        .is_some()
823        {
824            // RB-003.3: a pre-v9 file can't be opened read-write any more,
825            // so the usual advice would send the user in a circle.
826            // Compaction recovers the WAL and converts the file.
827            return Err(MnemoError::NeedsWriteOpen {
828                reason: if header.version < VERSION_V9 {
829                    "pending WAL recovery in a pre-v9 file; run `mnemo compact <file>`, \
830                     which recovers it and converts the file to v9"
831                } else {
832                    "pending WAL recovery"
833                },
834            });
835        }
836
837        let kdf = KdfParams {
838            m_cost: header.m_cost,
839            t_cost: header.t_cost,
840            p_cost: header.p_cost,
841        };
842        let kek = crypto::derive_kek(secret, &header.salt, kdf)?;
843        let dek = crypto::unwrap_dek(&kek, &header.dek_nonce, &header.wrapped_dek)?;
844        header.validate_seal(&dek)?;
845
846        let mut pager = Pager::new(file, dek, header.write_counter, header.version);
847        let dimensions = header.dimensions as usize;
848
849        let catalog = load_catalog(
850            &mut pager,
851            header.catalog_start,
852            header.catalog_pages,
853            header.catalog_len,
854            header.catalog_gen,
855        )?;
856        // FMT-9c.2: replay the v9 delta chain onto the base catalog.
857        let (catalog, delta_chain, delta_rows) =
858            apply_delta_chain(&mut pager, catalog, header.catalog_delta)?;
859        let index = build_id_index(&catalog);
860        // PERF-1 step 3: the ANN index loads on first use, not at open.
861        let ann: Option<IvfPqIndex> = None;
862        let ann_unloaded = header.index_pages > 0;
863        let manifest = load_manifest(
864            &mut pager,
865            header.manifest_start,
866            header.manifest_pages,
867            header.manifest_len,
868            header.manifest_gen,
869        )?;
870        let cache_dir = load_cache_directory(
871            &mut pager,
872            header.cache_start,
873            header.cache_pages,
874            header.cache_len,
875            header.cache_gen,
876        )?;
877        let cache_idx = DirectoryIndex::build(&cache_dir);
878        let free = load_free_list(&mut pager, header.free)?;
879        let key_slots = load_key_slots(&mut pager, header.keys)?;
880        let col = VecColumn::from_catalog(&catalog);
881        let recs = RecPages::from_catalog(&catalog);
882        let bm25_manifest = load_bm25_manifest(&mut pager, header.bm25)?;
883        let max_snapshots = if header.version >= VERSION_V9 {
884            V9_DEFAULT_MAX_SNAPSHOTS
885        } else {
886            DEFAULT_MAX_SNAPSHOTS
887        };
888
889        Ok(Mnemo {
890            pager,
891            header,
892            catalog,
893            index,
894            path,
895            dimensions,
896            kdf,
897            // No mutation is possible; leave both dirty flags false so
898            // `close()` is a genuine no-op even if we later add an
899            // auto-flush on drop.
900            dirty_catalog: false,
901            ann,
902            dirty_index: false,
903            index_persist: IndexPersist::default(),
904            ann_unloaded,
905            manifest,
906            max_snapshots,
907            read_only: true,
908            cache_dir,
909            cache_idx,
910            dirty_cache: false,
911            cache_budgets: std::collections::HashMap::new(),
912            cache_flush_policy: CacheFlushPolicy::default(),
913            cache_batch: BatchState::default(),
914            cache_counters: CounterState::default(),
915            embedder: None,
916            fsyncs_last_flush: 0,
917            agent_set: None,
918            key_index: None,
919            superseded: None,
920            layers: None,
921            turn_compress_after: DEFAULT_TURN_COMPRESS_AFTER_SECS,
922            free,
923            pending_free: Vec::new(),
924            free_dirty: false,
925            key_slots,
926            dirty_keys: false,
927            gen_leased: false,
928            col,
929            recs,
930            bm25: Bm25State {
931                manifest: bm25_manifest,
932                ..Bm25State::default()
933            },
934            kw: None,
935            index_layout_override: None,
936            dirty_rows: std::collections::BTreeSet::new(),
937            delta_chain,
938            delta_rows,
939            catalog_rewrite: false,
940            index_chain: Vec::new(),
941            index_chain_ops: 0,
942            index_rebase: false,
943            index_delta_ops: None,
944            snapshot_cap_explicit: false,
945            direct_writes: false,
946            vector_cache_budget: DEFAULT_VECTOR_CACHE_BUDGET,
947        })
948    }
949
950    /// FMT-9e: compress v9 thread-turn records once they're older than
951    /// `secs` (by their `created_at`). The default,
952    /// [`DEFAULT_TURN_COMPRESS_AFTER_SECS`], is 7 days: recent turns stay
953    /// plain, so a live session reads them at full speed, and each commit
954    /// compresses up to 256 turns that have aged past the cutoff. `0`
955    /// compresses every turn as it's written. Compaction always compresses
956    /// every turn, and so does a vacuum that moves one. Applies to this
957    /// handle only (not persisted); a no-op on v8 files, which never
958    /// compress. Reading never depends on it.
959    pub fn set_turn_compress_after(&mut self, secs: u64) {
960        self.turn_compress_after = secs.min(i64::MAX as u64) as i64;
961    }
962
963    /// Override the manifest snapshot cap on this open handle. `0` disables
964    /// the cap; any positive value keeps the most-recent `max` snapshots and
965    /// drops the rest on the next flush. See [`MnemoConfig::max_snapshots`].
966    pub fn set_max_snapshots(&mut self, max: usize) {
967        self.max_snapshots = max;
968        // FMT-9c: an explicit count is a hard cap on v9 (see
969        // `apply_retention`).
970        self.snapshot_cap_explicit = true;
971    }
972
973    /// Embedding dimensionality this database expects.
974    pub fn dimensions(&self) -> usize {
975        self.dimensions
976    }
977
978    /// Number of live (non-deleted) memories.
979    pub fn len(&self) -> usize {
980        self.catalog.iter().filter(|e| !e.deleted).count()
981    }
982
983    /// True if the database holds no live memories.
984    pub fn is_empty(&self) -> bool {
985        self.len() == 0
986    }
987
988    // --- internal page/record helpers -------------------------------------
989}