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/// The header a set of recovery frames would write to page 0, if they hold
15/// one that parses.
16fn page_zero_header(frames: &[(u64, Vec<u8>)]) -> Option<Header> {
17 frames
18 .iter()
19 .find(|(page_no, _)| *page_no == 0)
20 .and_then(|(_, bytes)| Header::from_page(bytes).ok())
21}
22
23/// Whether `h` is a v9 header sealed under `dek` (RB-007.2). The version
24/// matters: `validate_seal` passes any header older than v7, which has no
25/// seal.
26fn sealed_under(h: &Header, dek: &[u8; crypto::KEY_LEN]) -> bool {
27 h.version >= VERSION_V9 && h.validate_seal(dek).is_ok()
28}
29
30/// Walk the file for every 8 KiB-aligned page whose first four bytes are
31/// `MWAL`, treating each as a candidate WAL-region start, and return the
32/// frames of the highest-`txn_id` committed transaction whose header
33/// frame fully validates under `passphrase`.
34///
35/// A candidate is accepted only if:
36/// * `wal::scan_committed_txn` returns a committed transaction (chained
37/// CRC verifies, single `txn_id`, `KIND_COMMIT` closes it);
38/// * that transaction contains a `(0, header_page)` frame;
39/// * the header parses with `wal_start == candidate_page_no` and
40/// `wal_seq == txn_id` (so a frame cannot forge a region it was not
41/// written into);
42/// * deriving the KEK from `passphrase + header.salt`, unwrapping the
43/// wrapped DEK, and validating the header seal all succeed.
44///
45/// Returns `Ok(None)` when the scan finds no valid candidate — the
46/// caller is expected to propagate the original parse error so
47/// non-mnemo files still report `BadMagic`.
48///
49/// DUR-1 (R-002.1 part 2): there is no fixed scan window — the whole
50/// file is scanned. Reading at page granularity (not byte granularity)
51/// is sufficient because every WAL region in the format is page-aligned
52/// and every WAL commit writes its first frame at the region's start.
53fn scan_header_recovery_candidates(
54 file: &mut File,
55 secret: &[u8],
56 held_dek: Option<&[u8; crypto::KEY_LEN]>,
57) -> Result<Option<Vec<wal::Frame>>> {
58 let mut best: Option<(u64, Vec<wal::Frame>)> = None;
59 for_each_wal_candidate(file, &mut |file, page_no| {
60 if let Some((txn_id, frames)) = try_recover_candidate(file, page_no, secret, held_dek)? {
61 if best.as_ref().is_none_or(|(id, _)| txn_id > *id) {
62 best = Some((txn_id, frames));
63 }
64 }
65 Ok(())
66 })?;
67 Ok(best.map(|(_, f)| f))
68}
69
70/// Call `f` with every page-aligned page past page 0 whose first four bytes
71/// are `MWAL`: the candidate WAL-region starts the torn-header scan walks.
72fn for_each_wal_candidate(
73 file: &mut File,
74 f: &mut dyn FnMut(&mut File, u64) -> Result<()>,
75) -> Result<()> {
76 let file_len = file.seek(SeekFrom::End(0))?;
77 if file_len < PAGE_SIZE as u64 * 2 {
78 return Ok(()); // No room for even one WAL page past the header.
79 }
80 let page_sz = PAGE_SIZE as u64;
81 let mut offset = page_sz; // Skip page 0.
82
83 // Stream through the file in 1 MiB chunks, scanning each chunk for
84 // page-aligned `MWAL` candidates. Each candidate's frame chain is
85 // then read incrementally via `wal::scan_committed_txn`, which has
86 // no window cap — a 1M-vector IVF+PQ relocation can span tens of
87 // MiB in one committed transaction.
88 let mut chunk = vec![0u8; TORN_HEADER_SCAN_CHUNK];
89 while offset < file_len {
90 let want = (TORN_HEADER_SCAN_CHUNK as u64).min(file_len - offset) as usize;
91 chunk.resize(want, 0);
92 file.seek(SeekFrom::Start(offset))?;
93 let mut filled = 0;
94 while filled < want {
95 match file.read(&mut chunk[filled..])? {
96 0 => break,
97 n => filled += n,
98 }
99 }
100 if filled == 0 {
101 break;
102 }
103 let mut inner = 0usize;
104 while inner + 4 <= filled {
105 if &chunk[inner..inner + 4] == wal::FRAME_MAGIC_BYTES {
106 let page_no = (offset + inner as u64) / page_sz;
107 f(file, page_no)?;
108 }
109 inner += PAGE_SIZE;
110 }
111 offset += filled as u64;
112 }
113 Ok(())
114}
115
116/// 12.3 step 2 (the keys note, section 6): the salts and KDF parameters in
117/// the header frames of the file's committed WAL transactions, newest first
118/// and each salt once, read **without a key** (a WAL frame holds a plaintext
119/// page-0 image). For finding a key-store entry when page 0 doesn't parse.
120/// Nothing here is trusted: the open that follows verifies it all, and heals
121/// the header.
122pub(crate) fn wal_header_salts(path: &Path) -> Result<Vec<([u8; crypto::SALT_LEN], KdfParams)>> {
123 let mut file = File::open(path)?;
124 let mut found: Vec<(u64, [u8; crypto::SALT_LEN], KdfParams)> = Vec::new();
125 for_each_wal_candidate(&mut file, &mut |file, page_no| {
126 if let Some((txn_id, _, h)) = committed_header_candidate(file, page_no)? {
127 found.push((
128 txn_id,
129 h.salt,
130 KdfParams {
131 m_cost: h.m_cost,
132 t_cost: h.t_cost,
133 p_cost: h.p_cost,
134 },
135 ));
136 }
137 Ok(())
138 })?;
139 found.sort_by_key(|f| std::cmp::Reverse(f.0));
140 let mut out: Vec<([u8; crypto::SALT_LEN], KdfParams)> = Vec::new();
141 for (_, salt, kdf) in found {
142 if !out.iter().any(|(s, _)| *s == salt) {
143 out.push((salt, kdf));
144 }
145 }
146 Ok(out)
147}
148
149/// A committed WAL transaction starting at `candidate_page_no` whose header
150/// frame parses and names that region (`wal_start`, `wal_seq`), before any
151/// key is involved.
152fn committed_header_candidate(
153 file: &mut File,
154 candidate_page_no: u64,
155) -> Result<Option<(u64, Vec<wal::Frame>, Header)>> {
156 let Some((txn_id, frames)) = wal::scan_committed_txn(file, candidate_page_no)? else {
157 return Ok(None);
158 };
159 let header_bytes = match frames.iter().find(|(p, _)| *p == 0) {
160 Some((_, b)) => b,
161 None => return Ok(None),
162 };
163 if header_bytes.len() != PAGE_SIZE {
164 return Ok(None);
165 }
166 let mut hbuf = [0u8; PAGE_SIZE];
167 hbuf.copy_from_slice(header_bytes);
168 let Ok(candidate) = Header::from_page(&hbuf) else {
169 return Ok(None);
170 };
171 if candidate.wal_start != candidate_page_no || candidate.wal_seq != txn_id {
172 return Ok(None);
173 }
174 Ok(Some((txn_id, frames, candidate)))
175}
176
177/// Try to recover a committed transaction from `candidate_page_no`,
178/// returning `(txn_id, frames)` only if the candidate's
179/// `(0, header_page)` frame fully validates: the frame chain commits
180/// (via [`wal::scan_committed_txn`]'s streaming reader), the header
181/// parses with `wal_start == candidate_page_no` **and**
182/// `wal_seq == txn_id`, the DEK unwraps under `passphrase`, and the
183/// AES-GCM seal validates. DUR-1 (R-002.1 item 2) requires the
184/// `wal_seq == txn_id` check and no fixed scan window — the streaming
185/// reader handles transactions of arbitrary size.
186fn try_recover_candidate(
187 file: &mut File,
188 candidate_page_no: u64,
189 secret: &[u8],
190 held_dek: Option<&[u8; crypto::KEY_LEN]>,
191) -> Result<Option<(u64, Vec<wal::Frame>)>> {
192 // A header frame at page 0 whose claimed region matches where we found
193 // it, and whose `wal_seq` matches the committed transaction's `txn_id`
194 // — this is what pins the frame to the region it was written into and
195 // keeps a stale checkpointed-and-copied frame from being accepted as a
196 // new region's root.
197 let Some((txn_id, frames, candidate)) = committed_header_candidate(file, candidate_page_no)?
198 else {
199 return Ok(None);
200 };
201 // RB-007.2: a shared handle's data key, when the candidate's seal
202 // verifies under it, without the KDF.
203 if let Some(held) = held_dek {
204 if sealed_under(&candidate, held) {
205 return Ok(Some((txn_id, frames)));
206 }
207 }
208 // DEK unwrap under this candidate's own salt + KDF params.
209 let kdf = KdfParams {
210 m_cost: candidate.m_cost,
211 t_cost: candidate.t_cost,
212 p_cost: candidate.p_cost,
213 };
214 let kek = match crypto::derive_kek(secret, &candidate.salt, kdf) {
215 Ok(k) => k,
216 Err(_) => return Ok(None),
217 };
218 let dek = match crypto::unwrap_dek(&kek, &candidate.dek_nonce, &candidate.wrapped_dek) {
219 Ok(d) => d,
220 Err(_) => return Ok(None),
221 };
222 if candidate.validate_seal(&dek).is_err() {
223 return Ok(None);
224 }
225
226 Ok(Some((txn_id, frames)))
227}
228
229impl Mnemo {
230 /// Create a brand-new encrypted database at `path`.
231 pub fn create(
232 path: impl Into<PathBuf>,
233 passphrase: &str,
234 config: MnemoConfig,
235 ) -> Result<Mnemo> {
236 Self::create_secret(path, passphrase.as_bytes(), SecretKind::Passphrase, config)
237 }
238
239 /// PERF-1 step 7 (R-004.5): create a database unlocked by a **raw
240 /// 256-bit key** instead of a passphrase, for keys held by an OS
241 /// keychain or keystore. The key must be uniformly random (see
242 /// [`Mnemo::generate_key`]); it gets no stretching. The header records
243 /// minimal Argon2id parameters ([`KdfParams::raw_key`]), so opening
244 /// costs microseconds instead of tens of milliseconds. `config.kdf` is
245 /// ignored. No format change: the key goes through the same KEK
246 /// derivation a passphrase does.
247 pub fn create_with_key(
248 path: impl Into<PathBuf>,
249 key: &[u8; crypto::KEY_LEN],
250 config: MnemoConfig,
251 ) -> Result<Mnemo> {
252 let config = MnemoConfig {
253 kdf: KdfParams::raw_key(),
254 ..config
255 };
256 Self::create_secret(path, key, SecretKind::Key, config)
257 }
258
259 /// A fresh random 256-bit key for [`Mnemo::create_with_key`], from the
260 /// thread-local CSPRNG (seeded from the OS). Store it in a keychain;
261 /// it can't be recovered from the file.
262 pub fn generate_key() -> [u8; crypto::KEY_LEN] {
263 *crypto::random_dek()
264 }
265
266 pub(super) fn create_secret(
267 path: impl Into<PathBuf>,
268 secret: &[u8],
269 kind: SecretKind,
270 config: MnemoConfig,
271 ) -> Result<Mnemo> {
272 Self::create_secret_as(path.into(), secret, kind, config, Create::Truncate, None)
273 }
274
275 /// [`Mnemo::create_secret`] for a temp file: `Create::New` refuses a
276 /// name that already exists (a symlink included), with `AlreadyExists`.
277 /// `salt` is the salt to keep (a compaction's, 12.3's salt rule), or
278 /// `None` for a fresh one.
279 pub(super) fn create_secret_new(
280 path: &Path,
281 secret: &[u8],
282 kind: SecretKind,
283 config: MnemoConfig,
284 salt: Option<[u8; crypto::SALT_LEN]>,
285 ) -> Result<Mnemo> {
286 Self::create_secret_as(path.to_path_buf(), secret, kind, config, Create::New, salt)
287 }
288
289 /// Where every create meets. 12.3: a passphrase with raw-key parameters
290 /// is refused here, before anything touches the disk (the keys note,
291 /// section 1, rule 2).
292 pub(super) fn create_secret_as(
293 path: PathBuf,
294 secret: &[u8],
295 kind: SecretKind,
296 config: MnemoConfig,
297 create: Create,
298 salt: Option<[u8; crypto::SALT_LEN]>,
299 ) -> Result<Mnemo> {
300 crypto::check_kdf_for(kind, config.kdf)?;
301 if config.dimensions == 0 {
302 return Err(MnemoError::Invalid("dimensions must be > 0".into()));
303 }
304 let version = resolve_format_version(config.format_version)?;
305 if version >= VERSION_V9 && veccol::per_page(config.dimensions) == 0 {
306 return Err(MnemoError::Invalid(format!(
307 "a v9 file supports up to {} dimensions for now (one fp16 vector \
308 must fit a page); vector entries that span pages are not supported yet",
309 (PAYLOAD - veccol::PAGE_HEADER - 4) / 2
310 )));
311 }
312 let flags = if version >= VERSION_V9 && config.store_float_vectors {
313 FLAG_ENCRYPTED | FLAG_FLOAT_VECTORS
314 } else {
315 FLAG_ENCRYPTED
316 };
317 // Exclusive lock covers the write path; second writer sees `Locked`.
318 let file = open_with_lock(&path, /*write=*/ true, create)?;
319
320 let salt = salt.unwrap_or_else(crypto::random_salt);
321 let dek = crypto::random_dek();
322 let kek = crypto::derive_kek(secret, &salt, config.kdf)?;
323 let dek_nonce = crypto::random_nonce();
324 let wrapped = crypto::wrap_dek(&kek, &dek_nonce, &dek)?;
325 if wrapped.len() != WRAPPED_DEK_LEN {
326 return Err(MnemoError::Crypto("unexpected wrapped DEK length".into()));
327 }
328 let mut wrapped_dek = [0u8; WRAPPED_DEK_LEN];
329 wrapped_dek.copy_from_slice(&wrapped);
330
331 let mut header = Header {
332 version,
333 page_size: PAGE_SIZE as u32,
334 flags,
335 dimensions: config.dimensions as u32,
336 created_at: memory::now_secs(),
337 write_counter: 0,
338 // Page 0 is the header; pages 1..=wal_pages are the WAL;
339 // record/catalog/index pages start after it. Initial WAL size is
340 // chosen per-config (default 8 pages = 64 KiB) and clamped to a
341 // sane floor so the first transaction can always commit.
342 next_page: 1 + config.wal_pages_initial.max(MIN_WAL_PAGES),
343 catalog_start: 0,
344 catalog_pages: 0,
345 catalog_len: 0,
346 vector_count: 0,
347 m_cost: config.kdf.m_cost,
348 t_cost: config.kdf.t_cost,
349 p_cost: config.kdf.p_cost,
350 salt,
351 dek_nonce,
352 wrapped_dek,
353 index_start: 0,
354 index_pages: 0,
355 index_len: 0,
356 wal_start: 1,
357 wal_pages: config.wal_pages_initial.max(MIN_WAL_PAGES),
358 wal_seq: 0,
359 manifest_start: 0,
360 manifest_pages: 0,
361 manifest_len: 0,
362 // Regenerated per write by `apply_seal`; `None` until we seal.
363 seal_nonce: None,
364 seal_tag: None,
365 // v8+ result-cache pointer — zero-initialized on create,
366 // populated only when `cache_put` runs at least once and
367 // the next `flush` seals a directory run.
368 cache_start: 0,
369 cache_pages: 0,
370 cache_len: 0,
371 // FMT-9 v9 fields; all zero on a fresh file (and unused on v8).
372 catalog_gen: 0,
373 index_gen: 0,
374 manifest_gen: 0,
375 cache_gen: 0,
376 free: RunPtr::default(),
377 keys: RunPtr::default(),
378 bm25: RunPtr::default(),
379 index_delta: RunPtr::default(),
380 catalog_delta: RunPtr::default(),
381 };
382
383 let mut pager = Pager::new(file, dek, 0, version);
384 let mut page = header.to_page();
385 header.apply_seal(&mut page, pager.dek())?;
386 pager.write_raw(0, &page)?;
387 pager.sync()?;
388
389 Ok(Mnemo {
390 pager,
391 header,
392 catalog: Vec::new(),
393 index: IdIndex::default(),
394 path: absolute(path),
395 dimensions: config.dimensions,
396 kdf: config.kdf,
397 dirty_catalog: false,
398 ann: None,
399 dirty_index: false,
400 index_persist: IndexPersist::default(),
401 ann_unloaded: false,
402 manifest: Vec::new(),
403 // FMT-9c: v9 keeps fewer snapshots by default: with page reuse,
404 // retention is what pins pages.
405 max_snapshots: if version >= VERSION_V9 && config.max_snapshots == DEFAULT_MAX_SNAPSHOTS
406 {
407 V9_DEFAULT_MAX_SNAPSHOTS
408 } else {
409 config.max_snapshots
410 },
411 read_only: false,
412 cache_dir: Vec::new(),
413 cache_idx: DirectoryIndex::new(),
414 dirty_cache: false,
415 cache_budgets: std::collections::HashMap::new(),
416 cache_flush_policy: CacheFlushPolicy::default(),
417 cache_batch: BatchState::default(),
418 cache_counters: CounterState::default(),
419 embedder: None,
420 fsyncs_last_flush: 0,
421 agent_set: None,
422 key_index: None,
423 superseded: None,
424 layers: None,
425 rekey_cleanup: None,
426 access_delta: None,
427 commit_point: None,
428 lock_note: None,
429 notices: Vec::new(),
430 window_committed: false,
431 shared: false,
432 turn_compress_after: DEFAULT_TURN_COMPRESS_AFTER_SECS,
433 free: FreeList::default(),
434 pending_free: Vec::new(),
435 free_dirty: false,
436 key_slots: KeySlotRun::default(),
437 dirty_keys: false,
438 gen_leased: false,
439 col: VecColumn::default(),
440 recs: RecPages::default(),
441 bm25: Bm25State::default(),
442 kw: None,
443 index_layout_override: None,
444 dirty_rows: std::collections::BTreeSet::new(),
445 delta_chain: Vec::new(),
446 delta_rows: 0,
447 catalog_rewrite: false,
448 index_chain: Vec::new(),
449 index_chain_ops: 0,
450 index_rebase: false,
451 index_delta_ops: None,
452 snapshot_cap_explicit: config.max_snapshots != DEFAULT_MAX_SNAPSHOTS,
453 direct_writes: false,
454 vector_cache_budget: DEFAULT_VECTOR_CACHE_BUDGET,
455 })
456 }
457
458 /// Open an existing database. A wrong passphrase fails cleanly with
459 /// [`MnemoError::WrongPassphrase`]. Takes an OS exclusive lock for
460 /// the lifetime of the returned handle; a second concurrent open
461 /// (from any process) returns [`MnemoError::Locked`].
462 ///
463 /// For a caller that only needs to read (and can tolerate the
464 /// pending-recovery / pending-migration cases documented on
465 /// [`Mnemo::open_read_only`]), prefer that entry point — it takes a
466 /// shared lock and coexists with other readers.
467 pub fn open(path: impl Into<PathBuf>, passphrase: &str) -> Result<Mnemo> {
468 Self::open_secret(path, passphrase.as_bytes()).map(passphrase_opened)
469 }
470
471 /// PERF-1 step 7: open a database created by [`Mnemo::create_with_key`]
472 /// (or rekeyed with [`Mnemo::rekey_with_key`]) with its raw key.
473 pub fn open_with_key(path: impl Into<PathBuf>, key: &[u8; crypto::KEY_LEN]) -> Result<Mnemo> {
474 Self::open_secret(path, key)
475 }
476
477 pub(super) fn open_secret(path: impl Into<PathBuf>, secret: &[u8]) -> Result<Mnemo> {
478 Self::open_secret_with(path, secret, false)
479 }
480
481 /// The read-write open. `allow_old` lets a file older than v9 open (and
482 /// migrate in memory to v8): only compaction uses it, to read a v4–v8
483 /// file and write the v9 copy. Every public read-write open refuses
484 /// those with [`MnemoError::FormatTooOld`] (the v8 sunset, v0.13).
485 pub(super) fn open_secret_with(
486 path: impl Into<PathBuf>,
487 secret: &[u8],
488 allow_old: bool,
489 ) -> Result<Mnemo> {
490 let path: PathBuf = path.into();
491 let file = open_with_lock(&path, /*write=*/ true, Create::No)?;
492 Self::load_locked(path, file, secret, allow_old)
493 }
494
495 /// Open read-write through 12.4's lock layer, for a long operation that
496 /// must not run alongside shared handles' calls: an import, a rekey, a
497 /// compaction ([`Mnemo::compact_file`] does this itself).
498 ///
499 /// Unlike [`Mnemo::open`], which tries the lock once and fails with
500 /// [`MnemoError::Locked`], this waits up to `opts.deadline` with writer
501 /// preference (the intent lock), so busy shared readers can't keep it
502 /// out. Once it holds the lock it writes a `lock-info` note naming `op`,
503 /// so a shared caller that times out learns what holds the file. The
504 /// handle keeps the exclusive lock until it's dropped or closed, like
505 /// any read-write handle.
506 ///
507 /// Where shared mode isn't available (a network or synced filesystem
508 /// without `opts.allow_network_fs`, or a Windows build made with Rust
509 /// before 1.85) it opens as [`Mnemo::open`] does: one try, no note.
510 pub fn open_exclusive(
511 path: impl AsRef<Path>,
512 passphrase: &str,
513 op: &str,
514 opts: crate::SharedOptions,
515 ) -> Result<Mnemo> {
516 Self::open_exclusive_secret(path.as_ref(), passphrase.as_bytes(), op, &opts, false)
517 .map(passphrase_opened)
518 }
519
520 /// [`Mnemo::open_exclusive`] for a raw-key file.
521 pub fn open_exclusive_with_key(
522 path: impl AsRef<Path>,
523 key: &[u8; crypto::KEY_LEN],
524 op: &str,
525 opts: crate::SharedOptions,
526 ) -> Result<Mnemo> {
527 Self::open_exclusive_secret(path.as_ref(), key, op, &opts, false)
528 }
529
530 pub(super) fn open_exclusive_secret(
531 path: &Path,
532 secret: &[u8],
533 op: &str,
534 opts: &crate::SharedOptions,
535 allow_old: bool,
536 ) -> Result<Mnemo> {
537 let path = absolute(path.to_path_buf());
538 let (file, note) = lock_exclusive(&path, op, opts)?;
539 let mut db = Self::load_locked(path, file, secret, allow_old)?;
540 db.lock_note = note;
541 Ok(db)
542 }
543
544 /// The read-write open's work on a file its caller already holds
545 /// exclusively: heal a torn header, replay a pending WAL, derive the key
546 /// from `secret`, and build the handle. A shared-mode handle (12.4)
547 /// reloads through it with the call's locked file.
548 pub(super) fn load_locked(
549 path: PathBuf,
550 file: LockedFile,
551 secret: &[u8],
552 allow_old: bool,
553 ) -> Result<Mnemo> {
554 Self::load_locked_with(path, file, secret, None, allow_old)
555 }
556
557 /// [`Mnemo::load_locked`], with a data key the caller already holds (a
558 /// shared handle's, RB-007.2). The torn-header scan accepts a candidate
559 /// whose seal verifies under it, and a pending WAL is replayed with it
560 /// when the header the replay writes verifies under it, without running
561 /// the KDF: a rekey changes the secret, never the data key. Anything
562 /// that doesn't verify under it is checked with `secret`, as an open
563 /// does.
564 pub(super) fn load_locked_with(
565 path: PathBuf,
566 mut file: LockedFile,
567 secret: &[u8],
568 held_dek: Option<&[u8; crypto::KEY_LEN]>,
569 allow_old: bool,
570 ) -> Result<Mnemo> {
571 let mut hbuf = [0u8; PAGE_SIZE];
572 file.seek(SeekFrom::Start(0))?;
573 file.read_exact(&mut hbuf)?;
574 let mut header = match Header::from_page(&hbuf) {
575 Ok(h) => h,
576 Err(e) => {
577 // DUR-1 (R-002.1 part 2+3): page 0 did not parse — any
578 // error is treated as a torn-header candidate, not just
579 // `HeaderChecksum`. The whole 294-byte header lives in
580 // the first 512-byte sector, so the realistic failure is
581 // the sector zeroed or garbled, which returns `BadMagic`
582 // or `UnsupportedVersion` *before* the CRC gate.
583 //
584 // Scan the file for valid committed header-frame WAL
585 // regions, pick the highest `txn_id`, and replay it. If
586 // nothing valid is found, return the *original* error so
587 // non-mnemo files still report `BadMagic`.
588 let scan = scan_header_recovery_candidates(&mut file, secret, held_dek)?;
589 let frames = scan.ok_or(e)?;
590 // RB-003.3: the scan has checked the key; refuse an old
591 // format before healing anything.
592 if !allow_old {
593 if let Some(h) = page_zero_header(&frames) {
594 if h.version < VERSION_V9 {
595 return Err(MnemoError::FormatTooOld { version: h.version });
596 }
597 }
598 }
599 for (page_no, bytes) in &frames {
600 if bytes.len() != PAGE_SIZE {
601 return Err(MnemoError::Invalid("WAL frame is not page-sized".into()));
602 }
603 file.seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
604 file.write_all(bytes)?;
605 }
606 file.sync_all()?;
607 crate::bump_fsync();
608 file.seek(SeekFrom::Start(0))?;
609 file.read_exact(&mut hbuf)?;
610 Header::from_page(&hbuf)?
611 }
612 };
613
614 // Crash recovery: a committed-but-uncheckpointed transaction is
615 // replayed below. Each frame is a finished page image; the header
616 // frame, replayed to page 0, supersedes the header just read.
617 let pending = wal::recover(
618 &mut file,
619 header.wal_start,
620 header.wal_pages,
621 header.wal_seq,
622 )?;
623
624 // RB-003.3: settle the key and the format before writing anything,
625 // so a wrong secret or a refused old format leaves the file
626 // byte-identical. Both are checked against the header the file will
627 // have once the WAL is replayed (its page-0 frame, else the current
628 // header), since that header is the one the secret must open. No write
629 // the engine makes leaves a pending page-0 frame whose key wrap differs
630 // from page 0's (a rekey logs its new page 0 into a fresh WAL region,
631 // so a cut-off rekey leaves the old secret or the new one, never a
632 // mix), but checking against the replay's header is the right
633 // defence if one ever does.
634 let target = match pending.as_deref().and_then(page_zero_header) {
635 Some(h) => h,
636 None => header.clone(),
637 };
638 let kdf = KdfParams {
639 m_cost: target.m_cost,
640 t_cost: target.t_cost,
641 p_cost: target.p_cost,
642 };
643 let dek = match held_dek {
644 Some(held) if sealed_under(&target, held) => zeroize::Zeroizing::new(*held),
645 _ => {
646 let kek = crypto::derive_kek(secret, &target.salt, kdf)?;
647 crypto::unwrap_dek(&kek, &target.dek_nonce, &target.wrapped_dek)?
648 }
649 };
650 if !allow_old && target.version < VERSION_V9 {
651 return Err(MnemoError::FormatTooOld {
652 version: target.version,
653 });
654 }
655
656 if let Some(frames) = pending {
657 for (page_no, bytes) in &frames {
658 if bytes.len() != PAGE_SIZE {
659 return Err(MnemoError::Invalid("WAL frame is not page-sized".into()));
660 }
661 file.seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
662 file.write_all(bytes)?;
663 }
664 file.sync_all()?;
665 crate::bump_fsync();
666 // Re-read the now-current header from the replayed page 0.
667 file.seek(SeekFrom::Start(0))?;
668 file.read_exact(&mut hbuf)?;
669 header = Header::from_page(&hbuf)?;
670 }
671
672 Self::from_locked(path, file, header, dek, kdf, allow_old)
673 }
674
675 /// Build a read-write handle from a locked file whose page 0 is
676 /// `header`, with the data key already unwrapped. The shared-mode reload
677 /// (12.4) comes here directly when the seal verifies under the key it
678 /// holds, so it pays no KDF.
679 pub(super) fn from_locked(
680 path: PathBuf,
681 file: LockedFile,
682 mut header: Header,
683 dek: zeroize::Zeroizing<[u8; crypto::KEY_LEN]>,
684 kdf: KdfParams,
685 allow_old: bool,
686 ) -> Result<Mnemo> {
687 // Validate the v7 header seal now that we have the DEK. Returns
688 // `MnemoError::HeaderTampered` if any of the sealed mutable fields
689 // were rewritten after the last legitimate flush. No-op for v6 and
690 // older — pre-v7 files don't carry a seal.
691 //
692 // DUR-1 (Planner decision 2026-11-01, Option B): a seal failure is
693 // **always** reported as tampering, never auto-healed. R-002.1
694 // part 3's seal-mismatch WAL fallback is withdrawn: the seal
695 // exists for tamper-evidence; silently loading a stale committed
696 // header from the WAL would erase that evidence. A real crash
697 // cannot produce "CRC valid + seal invalid" either, because the
698 // whole 294-byte header lies inside sector 0 which storage
699 // writes atomically — a torn sector breaks magic, version or
700 // CRC first, and *those* are healed by the scan above.
701 header.validate_seal(&dek)?;
702
703 // Build the pager at the file's *current* version so initial reads
704 // use the matching AAD scheme — `Pager::page_aad` returns empty AAD
705 // for v4/v5 (no page binding) and `page_no.to_le_bytes()` for v6+.
706 let on_disk_version = header.version;
707 // The v8 sunset (v0.13): a read-write handle is v9. Older files open
708 // read-only (v8) or through `compact_file`, which converts them.
709 if !allow_old && on_disk_version < VERSION_V9 {
710 return Err(MnemoError::FormatTooOld {
711 version: on_disk_version,
712 });
713 }
714 let mut pager = Pager::new(file, dek, header.write_counter, on_disk_version);
715 let dimensions = header.dimensions as usize;
716
717 // === v4→v5 catalog migration =====================================
718 // v6 reads directly; v5 reads directly; v4 replays the catalog into
719 // the v5 shape by reading each memory's body to populate the new
720 // `accessed_at` / `access_count` fields. All page reads here still
721 // use the v4/v5 AAD scheme (none).
722 let (catalog, migrated_from_v4) = if on_disk_version >= 5 {
723 (
724 load_catalog(
725 &mut pager,
726 header.catalog_start,
727 header.catalog_pages,
728 header.catalog_len,
729 header.catalog_gen,
730 )?,
731 false,
732 )
733 } else if on_disk_version == 4 {
734 let v4 = load_catalog_v4(
735 &mut pager,
736 header.catalog_start,
737 header.catalog_pages,
738 header.catalog_len,
739 )?;
740 (migrate_v4_catalog(&mut pager, v4)?, true)
741 } else {
742 return Err(MnemoError::UnsupportedVersion(on_disk_version));
743 };
744 // FMT-9c.2: replay the v9 delta chain onto the base catalog.
745 let (catalog, delta_chain, delta_rows) =
746 apply_delta_chain(&mut pager, catalog, header.catalog_delta)?;
747 let index = build_id_index(&catalog);
748 // PERF-1 step 3: the ANN index loads on first use, not at open. A
749 // v5→v6 page migration is the exception: it must read the index
750 // now, under the old page AAD, to rewrite it.
751 let ann = if on_disk_version < 6 {
752 load_index(
753 &mut pager,
754 header.index_start,
755 header.index_pages,
756 header.index_len,
757 header.index_gen,
758 dimensions,
759 )?
760 } else {
761 None
762 };
763 let ann_unloaded = ann.is_none() && header.index_pages > 0;
764 let mut manifest = load_manifest(
765 &mut pager,
766 header.manifest_start,
767 header.manifest_pages,
768 header.manifest_len,
769 header.manifest_gen,
770 )?;
771
772 // === v5→v6 page-encryption migration =============================
773 // Pre-v6 data pages were encrypted under no AAD; v6 binds the home
774 // `page_no` as AAD so a page-transplant attack fails authentication
775 // on read. Re-stage every live record page through `write_page` so
776 // the next flush re-encrypts it under v6 AAD at the same home slot.
777 // Tombstoned entries skip — they're reclaimed by `compact_file`.
778 // Old catalog / ANN / manifest pages stay as orphan ciphertext;
779 // the next flush writes the new runs at fresh slots.
780 let migrated_pages_to_v6 = on_disk_version < 6;
781 if migrated_pages_to_v6 {
782 for e in &catalog {
783 if e.deleted {
784 continue;
785 }
786 for i in 0..e.page_count as u64 {
787 let payload = pager.read_page(e.start_page + i, 0)?;
788 pager.write_page(e.start_page + i, 0, &payload)?;
789 }
790 }
791 pager.set_version(6);
792 }
793
794 // === v6→v7 header-seal migration =================================
795 // v7 adds an AES-GCM seal at the tail of the header page that
796 // authenticates every mutable header field. Pre-v7 files have no
797 // seal — we just bump the version in memory and mark `dirty_catalog`
798 // so the next flush writes a sealed v7 header. Pages are untouched
799 // (page crypto is unchanged from v6).
800 let migrated_header_to_v7 = on_disk_version < 7;
801 if migrated_header_to_v7 {
802 pager.set_version(7);
803 }
804
805 // === v7→v8 cache-directory migration =============================
806 // v8 adds three u64 header fields (cache_start/pages/len) for the
807 // result-cache directory (Phase 10.1). Pre-v8 files have those
808 // three bytes as zero (the on-disk region beyond the v7 seal is
809 // zero-initialized), which is the legal "empty cache directory"
810 // state — no data migration required. We bump the version in
811 // memory and mark dirty_catalog so the next flush writes a
812 // v8-sealed header with the new AAD shape covering the cache
813 // pointer. Pages are untouched.
814 let migrated_header_to_v8 = on_disk_version < 8;
815 if migrated_header_to_v8 {
816 pager.set_version(VERSION);
817 }
818
819 let migrated = migrated_from_v4
820 || migrated_pages_to_v6
821 || migrated_header_to_v7
822 || migrated_header_to_v8;
823 if migrated {
824 // Stamp the version forward in memory; the next flush persists
825 // it via the WAL-committed header frame (and the v7 seal).
826 header.version = VERSION;
827 // Snapshots written under an older format reference page runs
828 // encrypted under the old AAD scheme; this build can't decrypt
829 // them under the new pager. Drop the manifest so the next
830 // flush records a fresh snapshot of the migrated state.
831 // Point-in-time recovery into the pre-migration past is
832 // sacrificed for migration simplicity. Old pages remain on
833 // disk until `compact_file`. (For v6→v7 alone — which doesn't
834 // change page crypto — the old snapshots would technically
835 // still be readable, but dropping them uniformly keeps the
836 // migration policy simple.)
837 manifest.clear();
838 }
839
840 // The ANN index pages on disk were sealed under the *old* AAD scheme
841 // if we migrated pages to v6; force a rewrite at fresh v6-encrypted
842 // slots on the next flush so a future reopen doesn't try to read
843 // them under the new AAD and fail. (Catalog and manifest already
844 // get rewritten via dirty_catalog and the manifest.clear() above.)
845 let dirty_index = migrated_pages_to_v6 && ann.is_some();
846
847 // Load the cache directory (v8+ only). Pre-v8 files have
848 // cache_pages == 0 by header layout, so this trivially yields
849 // an empty directory without touching the disk.
850 let cache_dir = load_cache_directory(
851 &mut pager,
852 header.cache_start,
853 header.cache_pages,
854 header.cache_len,
855 header.cache_gen,
856 )?;
857 let cache_idx = DirectoryIndex::build(&cache_dir);
858 // FMT-9 (a)/(b): the free list and key-slot run (empty pointers on
859 // v8, so these don't touch the disk there).
860 let free = load_free_list(&mut pager, header.free)?;
861 let key_slots = load_key_slots(&mut pager, header.keys)?;
862 let col = VecColumn::from_catalog(&catalog);
863 let recs = RecPages::from_catalog(&catalog);
864 let bm25_manifest = load_bm25_manifest(&mut pager, header.bm25)?;
865 let max_snapshots = if header.version >= VERSION_V9 {
866 V9_DEFAULT_MAX_SNAPSHOTS
867 } else {
868 DEFAULT_MAX_SNAPSHOTS
869 };
870
871 Ok(Mnemo {
872 pager,
873 header,
874 catalog,
875 index,
876 path: absolute(path),
877 dimensions,
878 kdf,
879 dirty_catalog: migrated,
880 ann,
881 dirty_index,
882 // A v5→v6 page migration leaves the index sealed under the old
883 // page AAD, so it must be rewritten on the next flush.
884 index_persist: IndexPersist {
885 forced: dirty_index,
886 ..IndexPersist::default()
887 },
888 ann_unloaded,
889 manifest,
890 // `Mnemo::open` has no [`MnemoConfig`] to read; default the cap
891 // to [`DEFAULT_MAX_SNAPSHOTS`]. Override with
892 // [`Mnemo::set_max_snapshots`] right after open if you need
893 // unlimited retention or a different cap for this handle.
894 max_snapshots,
895 read_only: false,
896 cache_dir,
897 cache_idx,
898 dirty_cache: false,
899 cache_budgets: std::collections::HashMap::new(),
900 cache_flush_policy: CacheFlushPolicy::default(),
901 cache_batch: BatchState::default(),
902 cache_counters: CounterState::default(),
903 embedder: None,
904 fsyncs_last_flush: 0,
905 agent_set: None,
906 key_index: None,
907 superseded: None,
908 layers: None,
909 rekey_cleanup: None,
910 access_delta: None,
911 commit_point: None,
912 lock_note: None,
913 notices: Vec::new(),
914 window_committed: false,
915 shared: false,
916 turn_compress_after: DEFAULT_TURN_COMPRESS_AFTER_SECS,
917 free,
918 pending_free: Vec::new(),
919 free_dirty: false,
920 key_slots,
921 dirty_keys: false,
922 gen_leased: false,
923 col,
924 recs,
925 bm25: Bm25State {
926 manifest: bm25_manifest,
927 ..Bm25State::default()
928 },
929 kw: None,
930 index_layout_override: None,
931 dirty_rows: std::collections::BTreeSet::new(),
932 delta_chain,
933 delta_rows,
934 catalog_rewrite: false,
935 index_chain: Vec::new(),
936 index_chain_ops: 0,
937 index_rebase: false,
938 index_delta_ops: None,
939 snapshot_cap_explicit: false,
940 direct_writes: false,
941 vector_cache_budget: DEFAULT_VECTOR_CACHE_BUDGET,
942 })
943 }
944
945 /// Open an existing database in **read-only** mode. Takes an OS shared
946 /// lock; multiple read-only handles can coexist, but any attempt to
947 /// open the same file read-write elsewhere returns
948 /// [`MnemoError::Locked`]. All mutating methods on the returned handle
949 /// return [`MnemoError::ReadOnly`], including `recall` with
950 /// `track_access(true)`.
951 ///
952 /// Two conditions block a read-only open and return
953 /// [`MnemoError::NeedsWriteOpen`]:
954 ///
955 /// 1. The file has a committed-but-uncheckpointed WAL transaction that
956 /// would ordinarily be replayed on open. A read-only handle
957 /// cannot write the recovered pages back.
958 /// 2. The on-disk format version is older than the current
959 /// `format::VERSION`, requiring an on-disk migration.
960 ///
961 /// In either case, open the file read-write once (which recovers /
962 /// migrates in place), close the handle cleanly, and reopen
963 /// read-only. This is documented in the README's Durability section.
964 pub fn open_read_only(path: impl Into<PathBuf>, passphrase: &str) -> Result<Mnemo> {
965 Self::open_read_only_secret(path, passphrase.as_bytes()).map(passphrase_opened)
966 }
967
968 /// PERF-1 step 7: [`Mnemo::open_read_only`] for a raw-key database.
969 pub fn open_read_only_with_key(
970 path: impl Into<PathBuf>,
971 key: &[u8; crypto::KEY_LEN],
972 ) -> Result<Mnemo> {
973 Self::open_read_only_secret(path, key)
974 }
975
976 /// The embedding width the file at `path` records, read from its header
977 /// (page 0 is sealed, not encrypted): no key, no lock, no KDF. A caller
978 /// that embeds before it takes the lock uses it to build its embedder's
979 /// identity (12.4: slow work first, unlocked). A torn header is an
980 /// error here (a read-write open heals it).
981 pub fn peek_dimensions(path: impl AsRef<std::path::Path>) -> Result<usize> {
982 let mut file = File::open(path.as_ref())?;
983 let mut hbuf = [0u8; PAGE_SIZE];
984 file.read_exact(&mut hbuf)?;
985 Ok(Header::from_page(&hbuf)?.dimensions as usize)
986 }
987
988 /// Whether `key` opens the raw-key file at `path`, decided from its
989 /// header alone: no catalog load, no lock, microseconds. `Ok(false)` is
990 /// "not this key". Unlike a read-only open, it answers for a file that
991 /// has a WAL transaction to recover (the state a kill between a commit
992 /// and its checkpoint leaves), so a caller trying each of its keys in
993 /// turn isn't stopped by [`MnemoError::NeedsWriteOpen`]. A torn header is
994 /// judged from the WAL frame that would heal it. Other failures (not a
995 /// `.mnemo` file, a tampered header, an I/O error) are errors. Added in
996 /// v0.12.2 (RB-001.23).
997 pub fn key_opens(
998 path: impl AsRef<std::path::Path>,
999 key: &[u8; crypto::KEY_LEN],
1000 ) -> Result<bool> {
1001 let mut file = File::open(path.as_ref())?;
1002 let mut hbuf = [0u8; PAGE_SIZE];
1003 file.seek(SeekFrom::Start(0))?;
1004 file.read_exact(&mut hbuf)?;
1005 let header = match Header::from_page(&hbuf) {
1006 Ok(h) => h,
1007 // A candidate frame only counts when it validates with `key`.
1008 Err(parse_err) => {
1009 return match scan_header_recovery_candidates(&mut file, key, None)? {
1010 Some(_) => Ok(true),
1011 None => Err(parse_err),
1012 }
1013 }
1014 };
1015 let kdf = KdfParams {
1016 m_cost: header.m_cost,
1017 t_cost: header.t_cost,
1018 p_cost: header.p_cost,
1019 };
1020 let kek = crypto::derive_kek(key, &header.salt, kdf)?;
1021 let dek = match crypto::unwrap_dek(&kek, &header.dek_nonce, &header.wrapped_dek) {
1022 Ok(dek) => dek,
1023 Err(MnemoError::WrongPassphrase) => return Ok(false),
1024 Err(e) => return Err(e),
1025 };
1026 header.validate_seal(&dek)?;
1027 Ok(true)
1028 }
1029
1030 pub(super) fn open_read_only_secret(path: impl Into<PathBuf>, secret: &[u8]) -> Result<Mnemo> {
1031 let path: PathBuf = path.into();
1032 let file = open_with_lock(&path, /*write=*/ false, Create::No)?;
1033 Self::read_only_from_locked(path, file, secret)
1034 }
1035
1036 /// [`Mnemo::open_read_only`] through 12.4's lock layer: it waits up to
1037 /// `opts.deadline` for a writer (a plain handle, a shared write, a
1038 /// compaction) instead of failing at once with `Locked`, and runs
1039 /// alongside other readers. The handle then holds the shared lock for
1040 /// its life, as any read-only handle does; close it promptly. A `Locked`
1041 /// after the wait names what holds the file when it left a note.
1042 ///
1043 /// Like `open_read_only`, it never recovers anything: a pending WAL or
1044 /// a torn header gives [`MnemoError::NeedsWriteOpen`]. Where shared
1045 /// mode isn't available it tries once, as `open_read_only` does.
1046 pub fn open_read_only_waiting(
1047 path: impl AsRef<Path>,
1048 passphrase: &str,
1049 opts: crate::SharedOptions,
1050 ) -> Result<Mnemo> {
1051 Self::open_read_only_waiting_secret(path.as_ref(), passphrase.as_bytes(), &opts)
1052 .map(passphrase_opened)
1053 }
1054
1055 /// [`Mnemo::open_read_only_waiting`] for a raw-key file.
1056 pub fn open_read_only_waiting_with_key(
1057 path: impl AsRef<Path>,
1058 key: &[u8; crypto::KEY_LEN],
1059 opts: crate::SharedOptions,
1060 ) -> Result<Mnemo> {
1061 Self::open_read_only_waiting_secret(path.as_ref(), key, &opts)
1062 }
1063
1064 fn open_read_only_waiting_secret(
1065 path: &Path,
1066 secret: &[u8],
1067 opts: &crate::SharedOptions,
1068 ) -> Result<Mnemo> {
1069 let path = absolute(path.to_path_buf());
1070 let file = lock_shared(&path, opts)?;
1071 Self::read_only_from_locked(path, file, secret)
1072 }
1073
1074 /// The read-only open's work on a file its caller holds the shared lock
1075 /// on.
1076 fn read_only_from_locked(path: PathBuf, mut file: LockedFile, secret: &[u8]) -> Result<Mnemo> {
1077 let mut hbuf = [0u8; PAGE_SIZE];
1078 file.seek(SeekFrom::Start(0))?;
1079 file.read_exact(&mut hbuf)?;
1080 // A torn header on a read-only open cannot be healed (that requires
1081 // writing recovered frames back). Surface as `NeedsWriteOpen` so the
1082 // caller knows to reopen read-write once. DUR-1 (R-002.1 part 4):
1083 // any `Header::from_page` failure (`BadMagic`,
1084 // `UnsupportedVersion`, `HeaderChecksum`) qualifies — but only
1085 // when the file-wide scan actually finds a valid committed
1086 // header frame to recover from, so a non-mnemo file still
1087 // reports `BadMagic` cleanly. A `validate_seal` failure is NOT
1088 // routed here (Option B: tampering is never auto-healed).
1089 let header = match Header::from_page(&hbuf) {
1090 Ok(h) => h,
1091 Err(parse_err) => {
1092 let recoverable = scan_header_recovery_candidates(&mut file, secret, None)?;
1093 return Err(match (parse_err, recoverable) {
1094 // RB-004.5 item 2: as for a pending WAL (RB-003.3), a
1095 // pre-v9 file can't be opened read-write, so the advice
1096 // names the step that does heal it.
1097 (_, Some(frames))
1098 if page_zero_header(&frames).is_some_and(|h| h.version < VERSION_V9) =>
1099 {
1100 MnemoError::NeedsWriteOpen {
1101 reason: "torn header page in a pre-v9 file; run `mnemo compact \
1102 <file>` (with `--key-file <key>` for a raw-key file), \
1103 which recovers it and converts the file to v9",
1104 }
1105 }
1106 (_, Some(_)) => MnemoError::NeedsWriteOpen {
1107 reason: "torn header page needs recovery from WAL",
1108 },
1109 (e, None) => e,
1110 });
1111 }
1112 };
1113
1114 // Refuse to migrate on read-only opens. v6→v7 is header-only
1115 // (no page writes required), but even that bumps `version` on
1116 // disk and re-seals the header — which needs write access. Keep
1117 // the policy uniform across all sub-version bumps.
1118 // A v4–v7 file needs migrating, which a read-only handle can't do,
1119 // and since v0.13 no read-write handle opens it either: compaction
1120 // converts it to v9.
1121 if header.version < VERSION {
1122 return Err(MnemoError::FormatTooOld {
1123 version: header.version,
1124 });
1125 }
1126
1127 // Refuse if there is a committed-but-uncheckpointed transaction
1128 // waiting for `wal::recover` to fold it into home pages.
1129 if wal::recover(
1130 &mut file,
1131 header.wal_start,
1132 header.wal_pages,
1133 header.wal_seq,
1134 )?
1135 .is_some()
1136 {
1137 // RB-003.3: a pre-v9 file can't be opened read-write any more,
1138 // so the usual advice would send the user in a circle.
1139 // Compaction recovers the WAL and converts the file.
1140 return Err(MnemoError::NeedsWriteOpen {
1141 reason: if header.version < VERSION_V9 {
1142 "pending WAL recovery in a pre-v9 file; run `mnemo compact <file>` \
1143 (with `--key-file <key>` for a raw-key file), which recovers it and \
1144 converts the file to v9"
1145 } else {
1146 "pending WAL recovery"
1147 },
1148 });
1149 }
1150
1151 let kdf = KdfParams {
1152 m_cost: header.m_cost,
1153 t_cost: header.t_cost,
1154 p_cost: header.p_cost,
1155 };
1156 let kek = crypto::derive_kek(secret, &header.salt, kdf)?;
1157 let dek = crypto::unwrap_dek(&kek, &header.dek_nonce, &header.wrapped_dek)?;
1158 header.validate_seal(&dek)?;
1159
1160 let mut pager = Pager::new(file, dek, header.write_counter, header.version);
1161 let dimensions = header.dimensions as usize;
1162
1163 let catalog = load_catalog(
1164 &mut pager,
1165 header.catalog_start,
1166 header.catalog_pages,
1167 header.catalog_len,
1168 header.catalog_gen,
1169 )?;
1170 // FMT-9c.2: replay the v9 delta chain onto the base catalog.
1171 let (catalog, delta_chain, delta_rows) =
1172 apply_delta_chain(&mut pager, catalog, header.catalog_delta)?;
1173 let index = build_id_index(&catalog);
1174 // PERF-1 step 3: the ANN index loads on first use, not at open.
1175 let ann: Option<IvfPqIndex> = None;
1176 let ann_unloaded = header.index_pages > 0;
1177 let manifest = load_manifest(
1178 &mut pager,
1179 header.manifest_start,
1180 header.manifest_pages,
1181 header.manifest_len,
1182 header.manifest_gen,
1183 )?;
1184 let cache_dir = load_cache_directory(
1185 &mut pager,
1186 header.cache_start,
1187 header.cache_pages,
1188 header.cache_len,
1189 header.cache_gen,
1190 )?;
1191 let cache_idx = DirectoryIndex::build(&cache_dir);
1192 let free = load_free_list(&mut pager, header.free)?;
1193 let key_slots = load_key_slots(&mut pager, header.keys)?;
1194 let col = VecColumn::from_catalog(&catalog);
1195 let recs = RecPages::from_catalog(&catalog);
1196 let bm25_manifest = load_bm25_manifest(&mut pager, header.bm25)?;
1197 let max_snapshots = if header.version >= VERSION_V9 {
1198 V9_DEFAULT_MAX_SNAPSHOTS
1199 } else {
1200 DEFAULT_MAX_SNAPSHOTS
1201 };
1202
1203 Ok(Mnemo {
1204 pager,
1205 header,
1206 catalog,
1207 index,
1208 path: absolute(path),
1209 dimensions,
1210 kdf,
1211 // No mutation is possible; leave both dirty flags false so
1212 // `close()` is a genuine no-op even if we later add an
1213 // auto-flush on drop.
1214 dirty_catalog: false,
1215 ann,
1216 dirty_index: false,
1217 index_persist: IndexPersist::default(),
1218 ann_unloaded,
1219 manifest,
1220 max_snapshots,
1221 read_only: true,
1222 cache_dir,
1223 cache_idx,
1224 dirty_cache: false,
1225 cache_budgets: std::collections::HashMap::new(),
1226 cache_flush_policy: CacheFlushPolicy::default(),
1227 cache_batch: BatchState::default(),
1228 cache_counters: CounterState::default(),
1229 embedder: None,
1230 fsyncs_last_flush: 0,
1231 agent_set: None,
1232 key_index: None,
1233 superseded: None,
1234 layers: None,
1235 rekey_cleanup: None,
1236 access_delta: None,
1237 commit_point: None,
1238 lock_note: None,
1239 notices: Vec::new(),
1240 window_committed: false,
1241 shared: false,
1242 turn_compress_after: DEFAULT_TURN_COMPRESS_AFTER_SECS,
1243 free,
1244 pending_free: Vec::new(),
1245 free_dirty: false,
1246 key_slots,
1247 dirty_keys: false,
1248 gen_leased: false,
1249 col,
1250 recs,
1251 bm25: Bm25State {
1252 manifest: bm25_manifest,
1253 ..Bm25State::default()
1254 },
1255 kw: None,
1256 index_layout_override: None,
1257 dirty_rows: std::collections::BTreeSet::new(),
1258 delta_chain,
1259 delta_rows,
1260 catalog_rewrite: false,
1261 index_chain: Vec::new(),
1262 index_chain_ops: 0,
1263 index_rebase: false,
1264 index_delta_ops: None,
1265 snapshot_cap_explicit: false,
1266 direct_writes: false,
1267 vector_cache_budget: DEFAULT_VECTOR_CACHE_BUDGET,
1268 })
1269 }
1270
1271 /// FMT-9e: compress v9 thread-turn records once they're older than
1272 /// `secs` (by their `created_at`). The default,
1273 /// [`DEFAULT_TURN_COMPRESS_AFTER_SECS`], is 7 days: recent turns stay
1274 /// plain, so a live session reads them at full speed, and each commit
1275 /// compresses up to 256 turns that have aged past the cutoff. `0`
1276 /// compresses every turn as it's written. Compaction always compresses
1277 /// every turn, and so does a vacuum that moves one. Applies to this
1278 /// handle only (not persisted); a no-op on v8 files, which never
1279 /// compress. Reading never depends on it.
1280 pub fn set_turn_compress_after(&mut self, secs: u64) {
1281 self.turn_compress_after = secs.min(i64::MAX as u64) as i64;
1282 }
1283
1284 /// Override the manifest snapshot cap on this open handle. `0` disables
1285 /// the cap; any positive value keeps the most-recent `max` snapshots and
1286 /// drops the rest on the next flush. See [`MnemoConfig::max_snapshots`].
1287 pub fn set_max_snapshots(&mut self, max: usize) {
1288 self.max_snapshots = max;
1289 // FMT-9c: an explicit count is a hard cap on v9 (see
1290 // `apply_retention`).
1291 self.snapshot_cap_explicit = true;
1292 }
1293
1294 /// 12.3: the salt in this handle's header, which names its keychain
1295 /// entry (the keys note, section 4).
1296 pub(crate) fn header_salt(&self) -> [u8; crypto::SALT_LEN] {
1297 self.header.salt
1298 }
1299
1300 /// 12.3: the salt in page 0 as it is on disk now, read through this
1301 /// handle's own file (a second open would fail against Windows' lock).
1302 /// After a failed rekey it tells which salt is in force.
1303 pub(crate) fn disk_salt(&mut self) -> Result<[u8; crypto::SALT_LEN]> {
1304 let page = self.pager.read_raw(0)?;
1305 Ok(Header::from_page(&page)?.salt)
1306 }
1307
1308 /// 12.3: what this handle has to tell its owner, once each: today, that
1309 /// a passphrase opened a file whose KDF parameters are the raw-key kind
1310 /// (the keys note, section 1, rule 7), with the fix. Empty otherwise.
1311 pub fn notices(&self) -> &[String] {
1312 &self.notices
1313 }
1314
1315 /// Embedding dimensionality this database expects.
1316 pub fn dimensions(&self) -> usize {
1317 self.dimensions
1318 }
1319
1320 /// Number of live (non-deleted) memories.
1321 pub fn len(&self) -> usize {
1322 self.catalog.iter().filter(|e| !e.deleted).count()
1323 }
1324
1325 /// True if the database holds no live memories.
1326 pub fn is_empty(&self) -> bool {
1327 self.len() == 0
1328 }
1329
1330 // --- internal page/record helpers -------------------------------------
1331}
1332
1333/// 12.3 (the keys note, section 1, rule 7): the notice for a file a
1334/// passphrase opened whose KDF parameters are the raw-key kind, if it is one.
1335pub(crate) fn passphrase_floor_notice(path: &Path, kdf: KdfParams) -> Option<String> {
1336 kdf.below_passphrase_floor().then(|| {
1337 format!(
1338 "{} is protected by a passphrase on raw-key KDF parameters ({} KiB, {} pass), \
1339 which makes each guess of it cheap; `mnemo rekey` or `mnemo compact` raises \
1340 the parameters",
1341 path.display(),
1342 kdf.m_cost,
1343 kdf.t_cost
1344 )
1345 })
1346}
1347
1348/// A handle a passphrase just opened, with [`passphrase_floor_notice`] added.
1349fn passphrase_opened(mut db: Mnemo) -> Mnemo {
1350 if let Some(n) = passphrase_floor_notice(&db.path, db.kdf) {
1351 db.notices.push(n);
1352 }
1353 db
1354}