mnemo_engine/store/maintenance.rs
1//! Maintenance: export, rekey, verify, stats, and compaction (which also upgrades v8 files to v9).
2
3use super::*;
4
5impl Mnemo {
6 /// Return the KDF (Argon2id) parameters this file currently uses to
7 /// wrap its DEK. Needed by callers that want to [`rekey`] while
8 /// keeping the file's original protection level (e.g. the Python
9 /// binding's `rekey(fast=False)`, whose docstring promises exactly
10 /// that). FIX-1 R-001.5.
11 pub fn kdf_params(&self) -> KdfParams {
12 self.kdf
13 }
14
15 /// Flush any pending writes, then stream the (encrypted) file to
16 /// `dest` atomically: writes to a sibling temp file in `dest`'s
17 /// parent directory, `sync_all`s it, renames onto `dest`, and
18 /// fsyncs the parent directory on Unix so a crash never leaves a
19 /// partial export.
20 ///
21 /// Refuses when `dest` resolves to the file this handle has open
22 /// — that case would otherwise `File::create`-truncate the live
23 /// database to 0 bytes (`fs::copy` on Unix reads *after* the
24 /// `O_TRUNC`, so a naive export-to-self destroys the source).
25 /// Unix: compares `(dev, ino)` of both paths via `MetadataExt`,
26 /// catching symlinks and hard links. Windows: compares
27 /// canonicalized paths; a rename onto an open file also fails on
28 /// Windows because of the mandatory lock the handle holds, so the
29 /// rename step is a second line of defense.
30 ///
31 /// Reads the bytes from the already-open file handle, not by
32 /// `fs::copy`. On Windows that matters: `LockFileEx` locks are
33 /// mandatory, so a second handle opened by `fs::copy` would fail
34 /// while this writer still holds the lock.
35 ///
36 /// FIX-1 R-001.5 + R-002.2 part 3.
37 pub fn export_encrypted(&mut self, dest: impl AsRef<Path>) -> Result<()> {
38 let dest = dest.as_ref();
39
40 // Step 1 — refuse export to the open file itself. We compare
41 // by identity, not string, so symlinks and hard links to
42 // `self.path` are caught too. The check runs before any flush
43 // so a self-targeted export is a pure no-op.
44 if paths_refer_to_same_file(&self.path, dest).unwrap_or(false) {
45 return Err(MnemoError::Invalid(format!(
46 "export_encrypted refuses to overwrite the open database at {}",
47 dest.display()
48 )));
49 }
50
51 // Step 2 — flush, so on-disk bytes match the live state.
52 if !self.read_only {
53 self.flush()?;
54 }
55
56 // Step 3 — stream from the open handle into a sibling temp.
57 // Using the open handle (instead of a second open on `self.path`)
58 // means a Windows mandatory lock can't block the copy.
59 let parent = dest.parent().ok_or_else(|| {
60 MnemoError::Invalid(format!(
61 "export_encrypted: dest {} has no parent directory",
62 dest.display()
63 ))
64 })?;
65 let tmp = temp_sibling(dest);
66 // Scope the temp handle so it closes before the rename on
67 // Windows (which refuses to rename over an open file).
68 {
69 let src = self.pager.file_mut();
70 src.seek(SeekFrom::Start(0))?;
71 let mut out = OpenOptions::new()
72 .write(true)
73 .create(true)
74 .truncate(true)
75 .open(&tmp)?;
76 let mut buf = vec![0u8; 1 << 20]; // 1 MiB
77 loop {
78 let n = src.read(&mut buf)?;
79 if n == 0 {
80 break;
81 }
82 out.write_all(&buf[..n])?;
83 }
84 out.sync_all()?;
85 crate::bump_fsync();
86 }
87
88 // Step 4 — atomic rename onto `dest`.
89 if let Err(e) = std::fs::rename(&tmp, dest) {
90 // Best-effort cleanup; propagate the rename error.
91 let _ = std::fs::remove_file(&tmp);
92 return Err(MnemoError::Io(e));
93 }
94
95 // Step 5 — fsync the parent directory on Unix so the rename
96 // itself is durable. On Windows directory syncs aren't
97 // supported; the rename above is atomic enough on NTFS.
98 #[cfg(unix)]
99 {
100 if let Ok(dir) = File::open(parent) {
101 let _ = dir.sync_all();
102 crate::bump_fsync();
103 }
104 }
105 #[cfg(not(unix))]
106 {
107 let _ = parent;
108 }
109
110 Ok(())
111 }
112
113 /// Change the passphrase. Cheap: re-derives the KEK and re-wraps the DEK;
114 /// the encrypted pages are never rewritten.
115 ///
116 /// **This changes the secret that opens this file from now on; anyone who
117 /// had the file and the old secret can still read it and later writes.**
118 /// The data key stays the same, so an earlier copy of the file (or of
119 /// just its header) and the old passphrase still unlock it. The old wrap
120 /// is scrubbed from this file (the previous WAL region is zeroed, and any
121 /// stale copy of the old header's key wrap is overwritten); that's
122 /// hygiene, not revocation. **To revoke, rotate:** rekey, then
123 /// [`Mnemo::compact_file`] (`mnemo rekey --rotate`), which rewrites the
124 /// file under a fresh data key. Rotation can't erase old ciphertext the storage hardware still holds: flash keeps rewritten blocks until it reuses them, and that's out of the engine's hands.
125 pub fn rekey(&mut self, new_passphrase: &str, kdf: KdfParams) -> Result<()> {
126 self.rekey_secret(new_passphrase.as_bytes(), kdf)
127 }
128
129 /// PERF-1 step 7: switch to (or rotate) a raw 256-bit key, recording
130 /// [`KdfParams::raw_key`] in the header. Like [`Mnemo::rekey`], only the
131 /// wrapped DEK changes; pages aren't rewritten, and it doesn't revoke
132 /// the old key (see [`Mnemo::rekey`]).
133 pub fn rekey_with_key(&mut self, new_key: &[u8; crypto::KEY_LEN]) -> Result<()> {
134 self.rekey_secret(new_key, KdfParams::raw_key())
135 }
136
137 pub(super) fn rekey_secret(&mut self, secret: &[u8], kdf: KdfParams) -> Result<()> {
138 if self.read_only {
139 return Err(MnemoError::ReadOnly);
140 }
141 self.flush()?;
142 let new_salt = crypto::random_salt();
143 let new_kek = crypto::derive_kek(secret, &new_salt, kdf)?;
144 let new_nonce = crypto::random_nonce();
145 let wrapped = crypto::wrap_dek(&new_kek, &new_nonce, self.pager.dek())?;
146 if wrapped.len() != WRAPPED_DEK_LEN {
147 return Err(MnemoError::Crypto("unexpected wrapped DEK length".into()));
148 }
149 let mut wrapped_dek = [0u8; WRAPPED_DEK_LEN];
150 wrapped_dek.copy_from_slice(&wrapped);
151
152 // SEC-2: the old header's key wrap (salt, DEK nonce, wrapped DEK, as
153 // laid out at header bytes 86..162), to scrub once the new header
154 // is committed.
155 let mut old_wrap =
156 Vec::with_capacity(crypto::SALT_LEN + crypto::NONCE_LEN + WRAPPED_DEK_LEN);
157 old_wrap.extend_from_slice(&self.header.salt);
158 old_wrap.extend_from_slice(&self.header.dek_nonce);
159 old_wrap.extend_from_slice(&self.header.wrapped_dek);
160
161 self.header.salt = new_salt;
162 self.header.dek_nonce = new_nonce;
163 self.header.wrapped_dek = wrapped_dek;
164 self.header.m_cost = kdf.m_cost;
165 self.header.t_cost = kdf.t_cost;
166 self.header.p_cost = kdf.p_cost;
167 self.kdf = kdf;
168
169 // DUR-1 (R-002.1): WAL-log the new page 0 before touching it.
170 // Allocate a fresh WAL region at the tail so that a crash during
171 // the rekey leaves either the old region (old passphrase works)
172 // or the new region (new passphrase works) fully committed —
173 // overwriting the existing region would risk destroying both.
174 let old_wal_start = self.header.wal_start;
175 let new_pages = self.header.wal_pages;
176 let new_start = self.header.next_page;
177 self.header.next_page += new_pages;
178 self.header.wal_start = new_start;
179 self.header.wal_pages = new_pages;
180 self.header.wal_seq += 1;
181 self.relocate_header_through_wal(old_wal_start)?;
182 // SEC-2 (RB-001.30): the old region holds page-0 images with the old
183 // wrap; `relocate_header_through_wal` only zeroed its first frame
184 // header. Zero all of it, then overwrite any other stale copy of
185 // the old wrap in the file (an earlier, grown or relocated region).
186 // Hygiene only: a copy of the file taken before the rekey still
187 // opens with the old secret (see `rekey`).
188 wal::scrub_region(self.pager.file_mut(), old_wal_start, new_pages)?;
189 scrub_bytes(self.pager.file_mut(), &old_wrap)?;
190 // FMT-9 (a): the old region is freed by the next commit (see
191 // `ensure_wal_capacity`).
192 self.release_pages(old_wal_start, new_pages);
193 Ok(())
194 }
195
196 /// SEC-2 (RB-001.30): write a copy of this database at `dest` under a
197 /// **fresh data key**, protected by `passphrase` through `kdf`. It goes
198 /// through the compaction path (live memories, the result cache and
199 /// the index, no history), so the copy shares no key material with
200 /// this file: neither this file's passphrase nor its data key opens
201 /// it, and its passphrase opens nothing here. This file is flushed
202 /// first (unless read-only) and is otherwise unchanged; `dest` must not
203 /// exist. The copy is v9.
204 pub fn export_rekeyed(
205 &mut self,
206 dest: impl AsRef<Path>,
207 passphrase: &str,
208 kdf: KdfParams,
209 ) -> Result<CompactReport> {
210 self.export_rekeyed_secret(dest.as_ref(), passphrase.as_bytes(), kdf)
211 }
212
213 /// [`Mnemo::export_rekeyed`] protected by a raw 256-bit key (no KDF).
214 pub fn export_rekeyed_with_key(
215 &mut self,
216 dest: impl AsRef<Path>,
217 key: &[u8; crypto::KEY_LEN],
218 ) -> Result<CompactReport> {
219 self.export_rekeyed_secret(dest.as_ref(), key, KdfParams::raw_key())
220 }
221
222 pub(super) fn export_rekeyed_secret(
223 &mut self,
224 dest: &Path,
225 secret: &[u8],
226 kdf: KdfParams,
227 ) -> Result<CompactReport> {
228 if paths_refer_to_same_file(&self.path, dest).unwrap_or(false) {
229 return Err(MnemoError::Invalid(format!(
230 "export_rekeyed refuses to overwrite the open database at {}",
231 dest.display()
232 )));
233 }
234 if dest.exists() {
235 return Err(MnemoError::Invalid(format!(
236 "{} already exists",
237 dest.display()
238 )));
239 }
240 if !self.read_only {
241 self.flush()?;
242 }
243 let mut name = dest.file_name().unwrap_or_default().to_os_string();
244 name.push(".export-tmp");
245 let tmp = dest.with_file_name(name);
246 let _ = std::fs::remove_file(&tmp);
247 let result = (|| {
248 let mut new = Mnemo::create_secret(
249 &tmp,
250 secret,
251 MnemoConfig {
252 dimensions: self.dimensions,
253 kdf,
254 store_float_vectors: self.float_vectors(),
255 ..Default::default()
256 },
257 )?;
258 let report = self.copy_live_into(&mut new)?;
259 new.flush()?;
260 drop(new);
261 std::fs::rename(&tmp, dest)?;
262 Ok(report)
263 })();
264 if result.is_err() {
265 let _ = std::fs::remove_file(&tmp);
266 }
267 result
268 }
269
270 /// The compaction copy: every live, unexpired memory and cache entry of
271 /// `self` into `new` (a freshly created file), and the index if `self`
272 /// has one. Counts as [`CompactReport`].
273 pub(super) fn copy_live_into(&mut self, new: &mut Mnemo) -> Result<CompactReport> {
274 // FMT-9e: compaction rewrites everything, so it compresses every
275 // thread turn, recent or not.
276 new.turn_compress_after = 0;
277 // ANN-1.1: compaction is "re-tune for the current size" by
278 // default. Pass IndexConfig::default() so partitions,
279 // subspaces, n_probe and n_rerank are all re-derived from the
280 // compacted vector count. Previously we froze the pre-compact
281 // (n_probe, n_rerank), which left the new index on stale
282 // numbers for the smaller post-compact corpus.
283 let want_index = self.has_index();
284 let now = memory::now_secs();
285 let all = self.memories()?;
286 let before = all.len();
287 let mut after = 0;
288 let mut zero_vector_manifests = 0;
289 let mut zero_vector_memories = 0;
290 for mut m in all {
291 if m.is_expired(now) {
292 continue;
293 }
294 // A file from before the zero-vector rule (Phase 3 PR 10a) can
295 // hold all-zero vectors. A legacy onboarding or manifest memory
296 // gets the sentinel unit vector a current manifest has, so it
297 // behaves like a new one; any other is carried unchanged.
298 if embed::is_zero_vector(&m.vector) {
299 if crud::is_onboarding(&m) || is_manifest(&m) {
300 m.vector = Memory::scaffold_manifest(self.dimensions).vector;
301 zero_vector_manifests += 1;
302 } else {
303 zero_vector_memories += 1;
304 }
305 }
306 // The engine's own copy: `_mnemo.*` keys come through as they
307 // are, and the write-time zero-vector check doesn't apply.
308 new.put_existing(m)?;
309 after += 1;
310 }
311 if want_index && after > 0 {
312 new.build_index_with(IndexConfig::default())?;
313 }
314
315 // Count + copy cache entries. We walk `self.cache_dir` by index
316 // so each hop reads the directory's live `accessed_at` /
317 // `access_count` directly rather than going through
318 // `cache_get` (which would also treat read-only semantics,
319 // tombstones, etc. — we want the raw, authoritative values).
320 let mut cache_before = 0usize;
321 let mut cache_after = 0usize;
322 let positions: Vec<usize> = (0..self.cache_dir.len()).collect();
323 for pos in positions {
324 let (keep, reserved) = {
325 let e = &self.cache_dir[pos];
326 (
327 !e.deleted && !e.is_expired(now),
328 embed::is_reserved_namespace(&e.namespace),
329 )
330 };
331 if keep {
332 // EMBED-ID-1: the engine's own entries (the embedder
333 // identity) are copied but not counted.
334 new.copy_cache_entry_from(self, pos)?;
335 if !reserved {
336 cache_before += 1;
337 cache_after += 1;
338 }
339 }
340 }
341 Ok(CompactReport {
342 before,
343 after,
344 cache_before,
345 cache_after,
346 zero_vector_manifests,
347 zero_vector_memories,
348 })
349 }
350
351 /// Decrypt and validate every live record. Returns the count verified
352 /// across memories **and** cache entries (FIX-1 R-001.1: now that the
353 /// cache survives compaction, `verify()` has to walk it too — the
354 /// pre-FIX-1 implementation only checked `self.catalog`, so a
355 /// corrupted cache record went unnoticed).
356 pub fn verify(&mut self) -> Result<usize> {
357 Ok(self.verify_report()?.records)
358 }
359
360 /// [`Mnemo::verify`], also counting the memories whose vector is all
361 /// zeros. A file written before the zero-vector rule (Phase 3 PR 10a)
362 /// can hold them; they decode fine but score 0.0 on every vector query.
363 /// `mnemo verify` warns about them, and compaction carries them
364 /// (giving a legacy manifest the sentinel vector).
365 pub fn verify_report(&mut self) -> Result<VerifyReport> {
366 let entries: Vec<CatalogEntry> = self
367 .catalog
368 .iter()
369 .filter(|e| !e.deleted)
370 .cloned()
371 .collect();
372 let mut n = entries.len();
373 let mut zero_vector_memories = 0;
374 for e in &entries {
375 let bytes = self.read_record(e)?;
376 let m: Memory = self.decode_memory(&bytes)?;
377 // FMT-9b: and the row's vector column entry.
378 let zero = if e.v9.is_some() {
379 let (h, _) = self.column_entry(e)?;
380 if h.len() != self.dimensions {
381 return Err(MnemoError::Invalid(
382 "vector entry has the wrong width".into(),
383 ));
384 }
385 // fp16 +0.0 and -0.0.
386 !h.is_empty() && h.iter().all(|b| b & 0x7fff == 0)
387 } else {
388 embed::is_zero_vector(&m.vector)
389 };
390 if zero {
391 zero_vector_memories += 1;
392 }
393 }
394
395 // Also decode every live cache entry. Tombstoned entries are
396 // skipped — their pages are orphan ciphertext awaiting
397 // `compact_file`, same as deleted memories. Expired entries
398 // are *still* on disk until compaction, so we verify them too.
399 let cache_positions: Vec<(u64, u32, u32, u64, bool)> = self
400 .cache_dir
401 .iter()
402 .filter(|e| !e.deleted)
403 .map(|e| {
404 let reserved = embed::is_reserved_namespace(&e.namespace);
405 (e.start_page, e.page_count, e.len, e.gen, reserved)
406 })
407 .collect();
408 for (start_page, page_count, len, gen, reserved) in cache_positions {
409 let buf = self.read_record_run(start_page, page_count, len, gen)?;
410 let _c: CacheEntry = rmp_serde::from_slice(&buf)
411 .map_err(|err| MnemoError::Serialize(err.to_string()))?;
412 // EMBED-ID-1: the engine's own entries are checked, not counted.
413 if !reserved {
414 n += 1;
415 }
416 }
417 // FMT-9 (a): no free run may overlap a page the committed state
418 // references (records, cache entries, control runs, the WAL).
419 if self.is_v9() {
420 self.check_free_list_disjoint()?;
421 }
422 Ok(VerifyReport {
423 records: n,
424 zero_vector_memories,
425 })
426 }
427
428 /// FMT-9 (a): fail if the free list (or a pending free) overlaps any
429 /// page the current state references.
430 pub(super) fn check_free_list_disjoint(&self) -> Result<()> {
431 let h = &self.header;
432 let mut live: Vec<(u64, u64, &str)> = vec![
433 (h.wal_start, h.wal_pages, "WAL region"),
434 (h.catalog_start, h.catalog_pages, "catalog run"),
435 (h.index_start, h.index_pages, "index run"),
436 (h.manifest_start, h.manifest_pages, "manifest run"),
437 (h.cache_start, h.cache_pages, "cache directory run"),
438 (h.free.start, h.free.pages, "free-list run"),
439 (h.keys.start, h.keys.pages, "key-slot run"),
440 ];
441 live.extend(
442 self.catalog
443 .iter()
444 .filter(|e| !e.deleted)
445 .map(|e| (e.start_page, e.page_count as u64, "record")),
446 );
447 live.extend(
448 self.cache_dir
449 .iter()
450 .filter(|e| !e.deleted)
451 .map(|e| (e.start_page, e.page_count as u64, "cache entry")),
452 );
453 live.extend(self.col.page_rows.keys().map(|&p| (p, 1, "vector page")));
454 live.extend(
455 self.delta_chain
456 .iter()
457 .map(|r| (r.start, r.pages, "catalog delta run")),
458 );
459 live.extend(
460 self.index_chain
461 .iter()
462 .map(|r| (r.start, r.pages, "index delta run")),
463 );
464 live.push((
465 self.header.bm25.start,
466 self.header.bm25.pages,
467 "BM25 manifest",
468 ));
469 live.extend(
470 self.bm25
471 .manifest
472 .segments
473 .iter()
474 .map(|t| (t.0, t.1, "BM25 segment")),
475 );
476 for (p, c, what) in live {
477 if c == 0 {
478 continue;
479 }
480 if self.free.overlaps(p, c) {
481 return Err(MnemoError::Invalid(format!(
482 "free list overlaps a live {what} at page {p} (+{c})"
483 )));
484 }
485 if self
486 .pending_free
487 .iter()
488 .any(|&(q, n)| q < p + c && p < q + n)
489 {
490 return Err(MnemoError::Invalid(format!(
491 "a pending free overlaps a live {what} at page {p} (+{c})"
492 )));
493 }
494 }
495 Ok(())
496 }
497
498 /// The statistics that need no record decrypts and no index load
499 /// (v0.12.2, RB-002.3): counts, sizes, the format, whether an index
500 /// exists, the recall mode and the bytes the vector column needs. The
501 /// first [`Mnemo::stats`] on a handle decrypts every record (for its
502 /// agent list) and loads a persisted index; this is what a phone app
503 /// polling the recall mode should call.
504 pub fn stats_summary(&self) -> StatsSummary {
505 let deleted = self.catalog.iter().filter(|e| e.deleted).count();
506 let v9 = self.is_v9();
507 let column = if v9 {
508 (self.scored_rows() * crate::veccol::entry_len(self.dimensions)) as u64
509 } else {
510 0
511 };
512 let recall_mode = if self.has_index() {
513 RecallMode::Indexed
514 } else if v9 && column <= self.vector_cache_budget as u64 {
515 RecallMode::ExactResident
516 } else {
517 RecallMode::ExactPaged
518 };
519 let rp = self.restore_points();
520 StatsSummary {
521 memories: self.len(),
522 deleted,
523 dimensions: self.dimensions,
524 file_bytes: self.header.next_page * PAGE_SIZE as u64,
525 format_version: self.header.version,
526 wal_pages: self.header.wal_pages,
527 has_index: self.has_index(),
528 recall_mode,
529 vector_column_bytes: column,
530 snapshots_retained: rp.retained,
531 oldest_restorable_at: rp.oldest_at,
532 snapshot_pinned_bytes: rp.pinned_bytes,
533 }
534 }
535
536 /// Summary statistics for the open database. The first call on a
537 /// handle decrypts every record (to list the agents) and loads a
538 /// persisted index; [`Mnemo::stats_summary`] does neither.
539 pub fn stats(&mut self) -> Result<Stats> {
540 let deleted = self.catalog.iter().filter(|e| e.deleted).count();
541 // FIX-1 R-001.8 part 2: build the agent set lazily on first
542 // call per handle, then maintain in `put` / invalidate in
543 // `delete`. Pre-FIX-1 every `stats()` call decrypted every
544 // live memory (O(N) AES-GCM decrypts just to list a usually-
545 // tiny set of distinct agent IDs). On a 1M-memory database
546 // this was in the multi-second range on hardware AES.
547 if self.agent_set.is_none() {
548 let built: std::collections::BTreeSet<String> =
549 self.memories()?.into_iter().map(|m| m.agent_id).collect();
550 self.agent_set = Some(built);
551 }
552 let agents: Vec<String> = self
553 .agent_set
554 .as_ref()
555 .expect("agent_set just filled above")
556 .iter()
557 .cloned()
558 .collect();
559 let file_bytes = self.header.next_page * PAGE_SIZE as u64;
560 let recall_mode = self.recall_mode()?;
561 let rp = self.restore_points();
562 Ok(Stats {
563 memories: self.len(),
564 deleted,
565 dimensions: self.dimensions,
566 file_bytes,
567 agents,
568 encrypted: self.header.flags & FLAG_ENCRYPTED != 0,
569 created_at: self.header.created_at,
570 index: {
571 self.ensure_ann()?;
572 self.ann.as_ref().map(|a| a.info())
573 },
574 wal_pages: self.header.wal_pages,
575 fsyncs_last_flush: self.fsyncs_last_flush,
576 format_version: self.header.version,
577 recall_mode,
578 snapshots_retained: rp.retained,
579 oldest_restorable_at: rp.oldest_at,
580 snapshot_pinned_bytes: rp.pinned_bytes,
581 })
582 }
583
584 /// Rewrite the file, dropping tombstoned and expired memories and
585 /// reclaiming stale pages left by updates. Done out-of-place via a temp
586 /// file and an atomic rename.
587 ///
588 /// FIX-1 R-001.1 + R-002.2 part 2: the result cache now survives
589 /// compaction. Every live, non-expired directory entry is copied
590 /// into the new file verbatim — `created_at`, `ttl_secs`,
591 /// `cost_hint_ms`, `key_preview`, `size_bytes`, `content_type`,
592 /// `vector` and `model` come from the record body; `accessed_at`
593 /// and `access_count` come from the *directory* (the record body
594 /// only holds the insert-time snapshot — the directory is the
595 /// source of truth for the live counts, as of v5's recall trick).
596 /// Tombstoned and TTL-expired entries are dropped. Pre-FIX-1
597 /// compaction kept only the memory catalog and silently emptied
598 /// the cache; the Planner's interim README caveat (c417d2e) called
599 /// that out — this PR removes the surprise.
600 ///
601 /// The output is always v9, so this is also how a v4–v8 file is
602 /// converted: the only read-write open that accepts one (the v8
603 /// sunset, v0.13). It keeps every live memory.
604 pub fn compact_file(path: &str, passphrase: &str) -> Result<CompactReport> {
605 Self::compact_file_secret(path, passphrase.as_bytes(), 0)
606 }
607
608 /// PERF-1 step 7: [`Mnemo::compact_file`] for a raw-key database.
609 pub fn compact_file_with_key(path: &str, key: &[u8; crypto::KEY_LEN]) -> Result<CompactReport> {
610 Self::compact_file_secret(path, key, 0)
611 }
612
613 pub(super) fn compact_file_secret(
614 path: &str,
615 secret: &[u8],
616 format_version: u16,
617 ) -> Result<CompactReport> {
618 // The one read-write open that takes a v4–v8 file (the v8 sunset).
619 let mut old = Mnemo::open_secret_with(path, secret, true)?;
620 let dims = old.dimensions;
621 let kdf = old.kdf;
622 let tmp = format!("{path}.compact-tmp");
623
624 let mut new = Mnemo::create_secret(
625 &tmp,
626 secret,
627 MnemoConfig {
628 dimensions: dims,
629 kdf,
630 // FMT-9f: compaction writes v9 (upgrading a v8 file),
631 // unless `compact_file_to` asked for v8. A v9 file that
632 // keeps float vectors keeps them.
633 format_version,
634 store_float_vectors: old.float_vectors(),
635 ..Default::default()
636 },
637 )?;
638 let report = old.copy_live_into(&mut new)?;
639
640 new.flush()?;
641 drop(new);
642 drop(old);
643
644 std::fs::rename(&tmp, path)?;
645 Ok(report)
646 }
647
648 /// Copy one live cache entry from `old` at directory position
649 /// `pos` into `self` (a freshly-created compaction target).
650 /// Decrypts the old record body, substitutes the old *directory*'s
651 /// `accessed_at` + `access_count` (the record body's copies are
652 /// stale as of v5's directory-only hit path), re-encodes, writes
653 /// a fresh record run, and pushes a matching directory entry.
654 ///
655 /// Caller is expected to have already filtered out tombstoned /
656 /// expired entries and to call this on a read-write handle.
657 pub(crate) fn copy_cache_entry_from(&mut self, old: &mut Mnemo, pos: usize) -> Result<()> {
658 if self.read_only {
659 return Err(MnemoError::ReadOnly);
660 }
661 // Snapshot the directory fields we need, so the borrow on
662 // `old.cache_dir` ends before we touch `old.pager`.
663 let (start_page, page_count, len, dir_accessed_at, dir_access_count, old_gen) = {
664 let e = &old.cache_dir[pos];
665 (
666 e.start_page,
667 e.page_count,
668 e.len,
669 e.accessed_at,
670 e.access_count,
671 e.gen,
672 )
673 };
674
675 // Read + decrypt the old record body.
676 let buf = old.read_record_run(start_page, page_count, len, old_gen)?;
677 let mut entry: CacheEntry =
678 rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))?;
679
680 // Overwrite the stale body copies with the directory's live
681 // values before persisting. Everything else — `created_at`,
682 // `ttl_secs`, `cost_hint_ms`, `key_preview`, `size_bytes`,
683 // `content_type`, `value`, `vector`, `model` — stays as the
684 // body already recorded it.
685 entry.accessed_at = dir_accessed_at;
686 entry.access_count = dir_access_count;
687
688 let bytes =
689 rmp_serde::to_vec(&entry).map_err(|err| MnemoError::Serialize(err.to_string()))?;
690 let (new_start_page, new_page_count, gen) = self.write_record(&bytes)?;
691
692 let dir_entry = CacheDirectoryEntry {
693 namespace: entry.namespace.clone(),
694 key_hash: entry.key_hash,
695 start_page: new_start_page,
696 page_count: new_page_count,
697 len: bytes.len() as u32,
698 deleted: false,
699 accessed_at: dir_accessed_at,
700 access_count: dir_access_count,
701 size_bytes: entry.size_bytes,
702 ttl_secs: entry.ttl_secs,
703 created_at: entry.created_at,
704 vector: entry.vector.clone(),
705 model: entry.model.clone(),
706 gen,
707 };
708 let new_pos = self.cache_dir.len();
709 self.cache_idx
710 .insert(&entry.namespace, entry.key_hash, new_pos);
711 self.cache_dir.push(dir_entry);
712 self.dirty_cache = true;
713 Ok(())
714 }
715}
716
717/// SEC-2 (RB-001.30): overwrite every occurrence of `needle` in the file
718/// with zeros, then sync. Rekey uses it for stale copies of the old header's
719/// key wrap: they're plaintext (page 0 is sealed, not encrypted) and can sit
720/// in WAL regions that were grown, relocated or freed. Every other page is
721/// AES-GCM ciphertext, where a 76-byte random match doesn't happen.
722pub(super) fn scrub_bytes(file: &mut std::fs::File, needle: &[u8]) -> Result<usize> {
723 if needle.is_empty() {
724 return Ok(0);
725 }
726 let len = file.seek(SeekFrom::End(0))?;
727 let chunk = 1 << 20;
728 let overlap = needle.len() - 1;
729 let mut hits: Vec<u64> = Vec::new();
730 let mut buf = vec![0u8; chunk + overlap];
731 let mut pos: u64 = 0;
732 while pos < len {
733 let want = (chunk as u64 + overlap as u64).min(len - pos) as usize;
734 file.seek(SeekFrom::Start(pos))?;
735 file.read_exact(&mut buf[..want])?;
736 let mut i = 0;
737 while i + needle.len() <= want {
738 if buf[i..i + needle.len()] == *needle {
739 hits.push(pos + i as u64);
740 i += needle.len();
741 } else {
742 i += 1;
743 }
744 }
745 pos += chunk as u64;
746 }
747 hits.dedup();
748 let zeros = vec![0u8; needle.len()];
749 for off in &hits {
750 file.seek(SeekFrom::Start(*off))?;
751 file.write_all(&zeros)?;
752 }
753 if !hits.is_empty() {
754 file.sync_all()?;
755 crate::bump_fsync();
756 }
757 Ok(hits.len())
758}