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. (The rename is no second line of defense:
28 /// renaming over a file another handle holds open and locked
29 /// succeeds on Windows too, as a 2026-11-13 CI probe showed.)
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 // A new file under a fresh name: `create_new` refuses anything
66 // already there, a symlink included, and a taken name gets another.
67 let (tmp, mut out) = {
68 let mut attempt = 0;
69 loop {
70 let tmp = temp_sibling(dest, "export");
71 match owner_only(OpenOptions::new().write(true).create_new(true)).open(&tmp) {
72 Ok(out) => break (tmp, out),
73 Err(e)
74 if e.kind() == std::io::ErrorKind::AlreadyExists
75 && attempt + 1 < TEMP_NAME_ATTEMPTS =>
76 {
77 attempt += 1;
78 }
79 Err(e) => return Err(MnemoError::Io(e)),
80 }
81 }
82 };
83 // Scope the temp handle so it closes before the rename on
84 // Windows (which refuses to rename a file this process has open).
85 {
86 let src = self.pager.file_mut();
87 src.seek(SeekFrom::Start(0))?;
88 let mut buf = vec![0u8; 1 << 20]; // 1 MiB
89 loop {
90 let n = src.read(&mut buf)?;
91 if n == 0 {
92 break;
93 }
94 out.write_all(&buf[..n])?;
95 }
96 out.sync_all()?;
97 crate::bump_fsync();
98 drop(out);
99 }
100
101 // Step 4 — atomic rename onto `dest`.
102 if let Err(e) = std::fs::rename(&tmp, dest) {
103 // Best-effort cleanup; propagate the rename error.
104 let _ = std::fs::remove_file(&tmp);
105 return Err(MnemoError::Io(e));
106 }
107
108 // Step 5 — fsync the parent directory on Unix so the rename
109 // itself is durable. On Windows directory syncs aren't
110 // supported; the rename above is atomic enough on NTFS.
111 #[cfg(unix)]
112 {
113 if let Ok(dir) = File::open(parent) {
114 let _ = dir.sync_all();
115 crate::bump_fsync();
116 }
117 }
118 #[cfg(not(unix))]
119 {
120 let _ = parent;
121 }
122
123 Ok(())
124 }
125
126 /// Change the passphrase. Cheap: re-derives the KEK and re-wraps the DEK;
127 /// the encrypted pages are never rewritten.
128 ///
129 /// **This changes the secret that opens this file from now on; anyone who
130 /// had the file and the old secret can still read it and later writes.**
131 /// The data key stays the same, so an earlier copy of the file (or of
132 /// just its header) and the old passphrase still unlock it. The old wrap
133 /// is scrubbed from this file (the previous WAL region is zeroed, and any
134 /// stale copy of the old header's key wrap is overwritten); that's
135 /// hygiene, not revocation. **To revoke, rotate:** rekey, then
136 /// [`Mnemo::compact_file`] (`mnemo rekey --rotate`), which rewrites the
137 /// 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.
138 ///
139 /// **An error means the old secret is still in force,** for this handle
140 /// and for the file, including after later writes and a close (REKEY-1).
141 /// The one exception is when the new header's write fails and putting
142 /// the old one back fails too: the error then says so, and the file may
143 /// open with either secret.
144 ///
145 /// `Ok` means the new secret is in force. Scrubbing the old wrap
146 /// afterwards is hygiene; if part of it fails, the rekey still succeeds
147 /// and [`Mnemo::rekey_cleanup_error`] says what was left.
148 pub fn rekey(&mut self, new_passphrase: &str, kdf: KdfParams) -> Result<()> {
149 self.rekey_secret(new_passphrase.as_bytes(), SecretKind::Passphrase, kdf)
150 }
151
152 /// PERF-1 step 7: switch to (or rotate) a raw 256-bit key, recording
153 /// [`KdfParams::raw_key`] in the header. Like [`Mnemo::rekey`], only the
154 /// wrapped DEK changes; pages aren't rewritten, and it doesn't revoke
155 /// the old key (see [`Mnemo::rekey`]).
156 ///
157 /// Errors and the cleanup report work as in [`Mnemo::rekey`].
158 pub fn rekey_with_key(&mut self, new_key: &[u8; crypto::KEY_LEN]) -> Result<()> {
159 self.rekey_secret(new_key, SecretKind::Key, KdfParams::raw_key())
160 }
161
162 pub(super) fn rekey_secret(
163 &mut self,
164 secret: &[u8],
165 kind: SecretKind,
166 kdf: KdfParams,
167 ) -> Result<()> {
168 if self.shared {
169 // RB-007.2: the shared handle would keep the old secret, and
170 // fail at the next compaction or recovery.
171 return Err(MnemoError::Unsupported(
172 "inside a shared-mode window, change the passphrase with SharedMnemo::rekey, \
173 which also updates the secret the handle keeps. Nothing was changed"
174 .into(),
175 ));
176 }
177 self.rekey_unchecked(secret, kind, kdf, None)
178 }
179
180 /// 12.3 (the keys note, section 4): [`Mnemo::rekey`] or
181 /// [`Mnemo::rekey_with_key`], with `before_commit` run once the new salt
182 /// is drawn and before anything is written, so a caller can store the new
183 /// secret under that salt first. An error from it stops the rekey with
184 /// nothing changed. Used by [`crate::keys::rekey_stored`].
185 pub(crate) fn rekey_staged(
186 &mut self,
187 secret: &[u8],
188 kind: SecretKind,
189 kdf: KdfParams,
190 before_commit: &mut crypto::SaltHook<'_>,
191 ) -> Result<()> {
192 if self.shared {
193 return Err(MnemoError::Unsupported(
194 "a staged rekey runs on a plain handle only".into(),
195 ));
196 }
197 self.rekey_unchecked(secret, kind, kdf, Some(before_commit))
198 }
199
200 /// The rekey itself; [`SharedMnemo::rekey`] calls it in its window. 12.3:
201 /// where every rekey meets, so a passphrase with raw-key parameters is
202 /// refused here (the keys note, section 1, rule 2).
203 pub(super) fn rekey_unchecked(
204 &mut self,
205 secret: &[u8],
206 kind: SecretKind,
207 kdf: KdfParams,
208 before_commit: Option<&mut crypto::SaltHook<'_>>,
209 ) -> Result<()> {
210 if self.read_only {
211 return Err(MnemoError::ReadOnly);
212 }
213 crypto::check_kdf_for(kind, kdf)?;
214 self.rekey_cleanup = None;
215 self.flush()?;
216 // v0.14.0 step 1: `flush` checks only when it has something to
217 // write; the rekey writes either way.
218 self.ensure_not_replaced()?;
219 let new_salt = crypto::random_salt();
220 let new_kek = crypto::derive_kek(secret, &new_salt, kdf)?;
221 let new_nonce = crypto::random_nonce();
222 let wrapped = crypto::wrap_dek(&new_kek, &new_nonce, self.pager.dek())?;
223 if wrapped.len() != WRAPPED_DEK_LEN {
224 return Err(MnemoError::Crypto("unexpected wrapped DEK length".into()));
225 }
226 let mut wrapped_dek = [0u8; WRAPPED_DEK_LEN];
227 wrapped_dek.copy_from_slice(&wrapped);
228 // 12.3: the caller stores the new secret under `new_salt` before
229 // anything is written.
230 if let Some(hook) = before_commit {
231 hook(&new_salt)?;
232 }
233
234 // SEC-2: the old header's key wrap (salt, DEK nonce, wrapped DEK, as
235 // laid out at header bytes 86..162), to scrub once the new header
236 // is committed.
237 let mut old_wrap =
238 Vec::with_capacity(crypto::SALT_LEN + crypto::NONCE_LEN + WRAPPED_DEK_LEN);
239 old_wrap.extend_from_slice(&self.header.salt);
240 old_wrap.extend_from_slice(&self.header.dek_nonce);
241 old_wrap.extend_from_slice(&self.header.wrapped_dek);
242
243 // REKEY-1 (RB-004.2): until the new page 0 is on disk, a failure puts
244 // these back, so an `Err` means "still the old secret".
245 let before = self.header.clone();
246 let before_kdf = self.kdf;
247
248 self.header.salt = new_salt;
249 self.header.dek_nonce = new_nonce;
250 self.header.wrapped_dek = wrapped_dek;
251 self.header.m_cost = kdf.m_cost;
252 self.header.t_cost = kdf.t_cost;
253 self.header.p_cost = kdf.p_cost;
254 self.kdf = kdf;
255
256 // DUR-1 (R-002.1): WAL-log the new page 0 before touching it.
257 // Allocate a fresh WAL region at the tail so that a crash during
258 // the rekey leaves either the old region (old passphrase works)
259 // or the new region (new passphrase works) fully committed —
260 // overwriting the existing region would risk destroying both.
261 let old_wal_start = self.header.wal_start;
262 let new_pages = self.header.wal_pages;
263 let new_start = self.header.next_page;
264 self.header.next_page += new_pages;
265 self.header.wal_start = new_start;
266 self.header.wal_pages = new_pages;
267 self.header.wal_seq += 1;
268
269 // The steps of `relocate_header_through_wal`, apart, so a failure
270 // can be told from one before page 0 and one after it.
271 self.header.write_counter = self.pager.write_counter;
272 let mut page = self.header.to_page();
273 if let Err(e) = self.header.apply_seal(&mut page, self.pager.dek()) {
274 return Err(self.undo_rekey(before, before_kdf, None, false, e));
275 }
276 let frames = vec![(0u64, page.to_vec())];
277 let txn_id = self.header.wal_seq;
278 if let Err(e) = wal::commit(self.pager.file_mut(), new_start, new_pages, txn_id, &frames) {
279 let region = Some((new_start, new_pages));
280 return Err(self.undo_rekey(before, before_kdf, region, false, e));
281 }
282 if let Err(e) = self
283 .pager
284 .write_raw(0, &page)
285 .and_then(|_| self.pager.sync())
286 {
287 let region = Some((new_start, new_pages));
288 return Err(self.undo_rekey(before, before_kdf, region, true, e));
289 }
290
291 // The new page 0 is on disk: the new secret is in force, and nothing
292 // below fails the rekey. SEC-2 (RB-001.30): zero the old region's
293 // first frame header (so no scan reads it as a WAL), then all of it
294 // (its frames hold page-0 images with the old wrap), then any other
295 // stale copy of the old wrap in the file (an earlier, grown or
296 // relocated region). Each step runs even if the one before failed.
297 // Hygiene only: a copy of the file taken before the rekey still
298 // opens with the old secret (see `rekey`).
299 let mut left = Vec::new();
300 if let Err(e) = wal::invalidate_region(self.pager.file_mut(), old_wal_start) {
301 left.push(format!("clearing the old WAL region's first frame: {e}"));
302 }
303 if let Err(e) = wal::scrub_region(self.pager.file_mut(), old_wal_start, new_pages) {
304 left.push(format!("zeroing the old WAL region: {e}"));
305 }
306 if let Err(e) = scrub_bytes(self.pager.file_mut(), &old_wrap) {
307 left.push(format!("overwriting other copies of the old key wrap: {e}"));
308 }
309 self.rekey_cleanup = (!left.is_empty()).then(|| left.join("; "));
310 // FMT-9 (a): the old region is freed by the next commit (see
311 // `ensure_wal_capacity`).
312 self.release_pages(old_wal_start, new_pages);
313 Ok(())
314 }
315
316 /// REKEY-1: a rekey failed before its new page 0 was on disk. Put the
317 /// header and the KDF back, so the handle (and every later write) uses
318 /// the old secret. Then, best effort: zero the new WAL region, whose
319 /// commit wraps the data key under the new secret, so a later
320 /// torn-header scan can't find it; and, if page 0 may have been
321 /// written, write the old one back.
322 fn undo_rekey(
323 &mut self,
324 before: crate::format::Header,
325 before_kdf: KdfParams,
326 new_region: Option<(u64, u64)>,
327 page0_written: bool,
328 err: MnemoError,
329 ) -> MnemoError {
330 self.header = before;
331 self.kdf = before_kdf;
332 // RB-005.2: a failed zeroing is reported, not dropped. The old
333 // secret is still in force either way; what's left is a committed
334 // copy of the new key wrap in the region past the file's end,
335 // which a torn-header scan could use with the new secret until a
336 // compaction clears it (a later write over those pages also does).
337 let scrub_failed = new_region.and_then(|(start, pages)| {
338 wal::scrub_region(self.pager.file_mut(), start, pages).err()
339 });
340 let with_scrub_note = |err: MnemoError| match &scrub_failed {
341 None => err,
342 Some(e) => MnemoError::Io(std::io::Error::other(format!(
343 "{err}; the old secret is still in force, but zeroing the new key wrap's \
344 copy failed ({e}), so a copy may be left in the file until `mnemo compact` \
345 clears it (a later write over those pages also does)"
346 ))),
347 };
348 if !page0_written {
349 return with_scrub_note(err);
350 }
351 self.header.write_counter = self.pager.write_counter;
352 let mut page = self.header.to_page();
353 let put_back = self
354 .header
355 .apply_seal(&mut page, self.pager.dek())
356 .and_then(|_| self.pager.write_raw(0, &page))
357 .and_then(|_| self.pager.sync());
358 match put_back {
359 Ok(()) => with_scrub_note(err),
360 // `mnemo rekey` looks for "may open with either secret" to leave
361 // out its "the passphrase was not changed": keep the phrase.
362 Err(again) => MnemoError::Io(std::io::Error::other(format!(
363 "rekey failed writing the new header ({err}), and the old header \
364 couldn't be written back ({again}): the file {EITHER_SECRET}; close it \
365 without writing and try both"
366 ))),
367 }
368 }
369
370 /// 12.3: whether `e` is REKEY-1's one exception, the error that says the
371 /// file may open with either secret. Kept beside the message it reads.
372 pub(crate) fn rekey_left_either_secret(e: &MnemoError) -> bool {
373 e.to_string().contains(EITHER_SECRET)
374 }
375
376 /// REKEY-1 (RB-004.2): after a successful [`Mnemo::rekey`] or
377 /// [`Mnemo::rekey_with_key`], what couldn't be scrubbed of the old key
378 /// wrap, or `None` if it all was. The rekey took effect either way; what
379 /// is left is plaintext key-wrap bytes the old secret could still use, so
380 /// to be sure, rotate (`compact_file`) as [`Mnemo::rekey`] describes.
381 /// Each rekey resets it.
382 pub fn rekey_cleanup_error(&self) -> Option<&str> {
383 self.rekey_cleanup.as_deref()
384 }
385
386 /// SEC-2 (RB-001.30): write a copy of this database at `dest` under a
387 /// **fresh data key**, protected by `passphrase` through `kdf`. It goes
388 /// through the compaction path (live memories, the result cache and
389 /// the index, no history), so the copy shares no key material with
390 /// this file: neither this file's passphrase nor its data key opens
391 /// it, and its passphrase opens nothing here. This file is flushed
392 /// first (unless read-only) and is otherwise unchanged; `dest` must not
393 /// exist. The copy is v9.
394 pub fn export_rekeyed(
395 &mut self,
396 dest: impl AsRef<Path>,
397 passphrase: &str,
398 kdf: KdfParams,
399 ) -> Result<CompactReport> {
400 self.export_rekeyed_secret(
401 dest.as_ref(),
402 passphrase.as_bytes(),
403 SecretKind::Passphrase,
404 kdf,
405 )
406 }
407
408 /// [`Mnemo::export_rekeyed`] protected by a raw 256-bit key (no KDF).
409 pub fn export_rekeyed_with_key(
410 &mut self,
411 dest: impl AsRef<Path>,
412 key: &[u8; crypto::KEY_LEN],
413 ) -> Result<CompactReport> {
414 self.export_rekeyed_secret(dest.as_ref(), key, SecretKind::Key, KdfParams::raw_key())
415 }
416
417 pub(super) fn export_rekeyed_secret(
418 &mut self,
419 dest: &Path,
420 secret: &[u8],
421 kind: SecretKind,
422 kdf: KdfParams,
423 ) -> Result<CompactReport> {
424 crypto::check_kdf_for(kind, kdf)?;
425 if paths_refer_to_same_file(&self.path, dest).unwrap_or(false) {
426 return Err(MnemoError::Invalid(format!(
427 "export_rekeyed refuses to overwrite the open database at {}",
428 dest.display()
429 )));
430 }
431 if dest.exists() {
432 return Err(MnemoError::Invalid(format!(
433 "{} already exists",
434 dest.display()
435 )));
436 }
437 if !self.read_only {
438 self.flush()?;
439 }
440 let config = MnemoConfig {
441 dimensions: self.dimensions,
442 kdf,
443 store_float_vectors: self.float_vectors(),
444 ..Default::default()
445 };
446 let (tmp, mut new) = create_temp(dest, "export", secret, kind, config, None)?;
447 let result = (|| {
448 let report = self.copy_live_into(&mut new)?;
449 new.flush()?;
450 drop(new);
451 std::fs::rename(&tmp, dest)?;
452 Ok(report)
453 })();
454 if result.is_err() {
455 let _ = std::fs::remove_file(&tmp);
456 }
457 result
458 }
459
460 /// The compaction copy: every live, unexpired memory and cache entry of
461 /// `self` into `new` (a freshly created file), and the index if `self`
462 /// has one. Counts as [`CompactReport`].
463 pub(super) fn copy_live_into(&mut self, new: &mut Mnemo) -> Result<CompactReport> {
464 // FMT-9e: compaction rewrites everything, so it compresses every
465 // thread turn, recent or not.
466 new.turn_compress_after = 0;
467 // ANN-1.1: compaction is "re-tune for the current size" by
468 // default. Pass IndexConfig::default() so partitions,
469 // subspaces, n_probe and n_rerank are all re-derived from the
470 // compacted vector count. Previously we froze the pre-compact
471 // (n_probe, n_rerank), which left the new index on stale
472 // numbers for the smaller post-compact corpus.
473 let want_index = self.has_index();
474 let now = memory::now_secs();
475 let all = self.memories()?;
476 let before = all.len();
477 let mut after = 0;
478 let mut zero_vector_manifests = 0;
479 let mut zero_vector_memories = 0;
480 for mut m in all {
481 if m.is_expired(now) {
482 continue;
483 }
484 // A file from before the zero-vector rule (Phase 3 PR 10a) can
485 // hold all-zero vectors. A legacy onboarding or manifest memory
486 // gets the sentinel unit vector a current manifest has, so it
487 // behaves like a new one; any other is carried unchanged.
488 if embed::is_zero_vector(&m.vector) {
489 if crud::is_onboarding(&m) || is_manifest(&m) {
490 m.vector = Memory::scaffold_manifest(self.dimensions).vector;
491 zero_vector_manifests += 1;
492 } else {
493 zero_vector_memories += 1;
494 }
495 }
496 // The engine's own copy: `_mnemo.*` keys come through as they
497 // are, and the write-time zero-vector check doesn't apply.
498 new.put_existing(m)?;
499 after += 1;
500 }
501 if want_index && after > 0 {
502 new.build_index_with(IndexConfig::default())?;
503 }
504
505 // Count + copy cache entries. We walk `self.cache_dir` by index
506 // so each hop reads the directory's live `accessed_at` /
507 // `access_count` directly rather than going through
508 // `cache_get` (which would also treat read-only semantics,
509 // tombstones, etc. — we want the raw, authoritative values).
510 let mut cache_before = 0usize;
511 let mut cache_after = 0usize;
512 let positions: Vec<usize> = (0..self.cache_dir.len()).collect();
513 for pos in positions {
514 let (keep, reserved) = {
515 let e = &self.cache_dir[pos];
516 (
517 !e.deleted && !e.is_expired(now),
518 embed::is_reserved_namespace(&e.namespace),
519 )
520 };
521 if keep {
522 // EMBED-ID-1: the engine's own entries (the embedder
523 // identity) are copied but not counted.
524 new.copy_cache_entry_from(self, pos)?;
525 if !reserved {
526 cache_before += 1;
527 cache_after += 1;
528 }
529 }
530 }
531 Ok(CompactReport {
532 before,
533 after,
534 cache_before,
535 cache_after,
536 zero_vector_manifests,
537 zero_vector_memories,
538 })
539 }
540
541 /// Decrypt and validate every live record. Returns the count verified
542 /// across memories **and** cache entries (FIX-1 R-001.1: now that the
543 /// cache survives compaction, `verify()` has to walk it too — the
544 /// pre-FIX-1 implementation only checked `self.catalog`, so a
545 /// corrupted cache record went unnoticed).
546 pub fn verify(&mut self) -> Result<usize> {
547 Ok(self.verify_report()?.records)
548 }
549
550 /// [`Mnemo::verify`], also counting the memories whose vector is all
551 /// zeros. A file written before the zero-vector rule (Phase 3 PR 10a)
552 /// can hold them; they decode fine but score 0.0 on every vector query.
553 /// `mnemo verify` warns about them, and compaction carries them
554 /// (giving a legacy manifest the sentinel vector).
555 pub fn verify_report(&mut self) -> Result<VerifyReport> {
556 let entries: Vec<CatalogEntry> = self
557 .catalog
558 .iter()
559 .filter(|e| !e.deleted)
560 .cloned()
561 .collect();
562 let mut n = entries.len();
563 let mut zero_vector_memories = 0;
564 for e in &entries {
565 let bytes = self.read_record(e)?;
566 let m: Memory = self.decode_memory(&bytes)?;
567 // FMT-9b: and the row's vector column entry.
568 let zero = if e.v9.is_some() {
569 let (h, _) = self.column_entry(e)?;
570 if h.len() != self.dimensions {
571 return Err(MnemoError::Invalid(
572 "vector entry has the wrong width".into(),
573 ));
574 }
575 // fp16 +0.0 and -0.0.
576 !h.is_empty() && h.iter().all(|b| b & 0x7fff == 0)
577 } else {
578 embed::is_zero_vector(&m.vector)
579 };
580 if zero {
581 zero_vector_memories += 1;
582 }
583 }
584
585 // Also decode every live cache entry. Tombstoned entries are
586 // skipped — their pages are orphan ciphertext awaiting
587 // `compact_file`, same as deleted memories. Expired entries
588 // are *still* on disk until compaction, so we verify them too.
589 let cache_positions: Vec<(u64, u32, u32, u64, bool)> = self
590 .cache_dir
591 .iter()
592 .filter(|e| !e.deleted)
593 .map(|e| {
594 let reserved = embed::is_reserved_namespace(&e.namespace);
595 (e.start_page, e.page_count, e.len, e.gen, reserved)
596 })
597 .collect();
598 for (start_page, page_count, len, gen, reserved) in cache_positions {
599 let buf = self.read_record_run(start_page, page_count, len, gen)?;
600 let _c: CacheEntry = rmp_serde::from_slice(&buf)
601 .map_err(|err| MnemoError::Serialize(err.to_string()))?;
602 // EMBED-ID-1: the engine's own entries are checked, not counted.
603 if !reserved {
604 n += 1;
605 }
606 }
607 // FMT-9 (a): no free run may overlap a page the committed state
608 // references (records, cache entries, control runs, the WAL).
609 if self.is_v9() {
610 self.check_free_list_disjoint()?;
611 }
612 Ok(VerifyReport {
613 records: n,
614 zero_vector_memories,
615 keyword_tokenizer: self.keyword_tokenizer()?,
616 })
617 }
618
619 /// FMT-9 (a): fail if the free list (or a pending free) overlaps any
620 /// page the current state references.
621 pub(super) fn check_free_list_disjoint(&self) -> Result<()> {
622 let h = &self.header;
623 let mut live: Vec<(u64, u64, &str)> = vec![
624 (h.wal_start, h.wal_pages, "WAL region"),
625 (h.catalog_start, h.catalog_pages, "catalog run"),
626 (h.index_start, h.index_pages, "index run"),
627 (h.manifest_start, h.manifest_pages, "manifest run"),
628 (h.cache_start, h.cache_pages, "cache directory run"),
629 (h.free.start, h.free.pages, "free-list run"),
630 (h.keys.start, h.keys.pages, "key-slot run"),
631 ];
632 live.extend(
633 self.catalog
634 .iter()
635 .filter(|e| !e.deleted)
636 .map(|e| (e.start_page, e.page_count as u64, "record")),
637 );
638 live.extend(
639 self.cache_dir
640 .iter()
641 .filter(|e| !e.deleted)
642 .map(|e| (e.start_page, e.page_count as u64, "cache entry")),
643 );
644 live.extend(self.col.page_rows.keys().map(|&p| (p, 1, "vector page")));
645 live.extend(
646 self.delta_chain
647 .iter()
648 .map(|r| (r.start, r.pages, "catalog delta run")),
649 );
650 live.extend(
651 self.index_chain
652 .iter()
653 .map(|r| (r.start, r.pages, "index delta run")),
654 );
655 live.push((
656 self.header.bm25.start,
657 self.header.bm25.pages,
658 "BM25 manifest",
659 ));
660 live.extend(
661 self.bm25
662 .manifest
663 .segments
664 .iter()
665 .map(|t| (t.0, t.1, "BM25 segment")),
666 );
667 for (p, c, what) in live {
668 if c == 0 {
669 continue;
670 }
671 if self.free.overlaps(p, c) {
672 return Err(MnemoError::Invalid(format!(
673 "free list overlaps a live {what} at page {p} (+{c})"
674 )));
675 }
676 if self
677 .pending_free
678 .iter()
679 .any(|&(q, n)| q < p + c && p < q + n)
680 {
681 return Err(MnemoError::Invalid(format!(
682 "a pending free overlaps a live {what} at page {p} (+{c})"
683 )));
684 }
685 }
686 Ok(())
687 }
688
689 /// The statistics that need no record decrypts and no index load
690 /// (v0.12.2, RB-002.3): counts, sizes, the format, whether an index
691 /// exists, the recall mode and the bytes the vector column needs. The
692 /// first [`Mnemo::stats`] on a handle decrypts every record (for its
693 /// agent list) and loads a persisted index; this is what a phone app
694 /// polling the recall mode should call.
695 pub fn stats_summary(&self) -> StatsSummary {
696 let deleted = self.catalog.iter().filter(|e| e.deleted).count();
697 let v9 = self.is_v9();
698 let column = if v9 {
699 (self.scored_rows() * crate::veccol::entry_len(self.dimensions)) as u64
700 } else {
701 0
702 };
703 let recall_mode = if self.has_index() {
704 RecallMode::Indexed
705 } else if v9 && column <= self.vector_cache_budget as u64 {
706 RecallMode::ExactResident
707 } else {
708 RecallMode::ExactPaged
709 };
710 let rp = self.restore_points();
711 StatsSummary {
712 memories: self.len(),
713 deleted,
714 dimensions: self.dimensions,
715 file_bytes: self.header.next_page * PAGE_SIZE as u64,
716 format_version: self.header.version,
717 wal_pages: self.header.wal_pages,
718 has_index: self.has_index(),
719 recall_mode,
720 vector_column_bytes: column,
721 snapshots_retained: rp.retained,
722 oldest_restorable_at: rp.oldest_at,
723 snapshot_pinned_bytes: rp.pinned_bytes,
724 }
725 }
726
727 /// Summary statistics for the open database. The first call on a
728 /// handle decrypts every record (to list the agents) and loads a
729 /// persisted index; [`Mnemo::stats_summary`] does neither.
730 pub fn stats(&mut self) -> Result<Stats> {
731 let deleted = self.catalog.iter().filter(|e| e.deleted).count();
732 // FIX-1 R-001.8 part 2: build the agent set lazily on first
733 // call per handle, then maintain in `put` / invalidate in
734 // `delete`. Pre-FIX-1 every `stats()` call decrypted every
735 // live memory (O(N) AES-GCM decrypts just to list a usually-
736 // tiny set of distinct agent IDs). On a 1M-memory database
737 // this was in the multi-second range on hardware AES.
738 if self.agent_set.is_none() {
739 let built: std::collections::BTreeSet<String> =
740 self.memories()?.into_iter().map(|m| m.agent_id).collect();
741 self.agent_set = Some(built);
742 }
743 let agents: Vec<String> = self
744 .agent_set
745 .as_ref()
746 .expect("agent_set just filled above")
747 .iter()
748 .cloned()
749 .collect();
750 let file_bytes = self.header.next_page * PAGE_SIZE as u64;
751 let recall_mode = self.recall_mode()?;
752 let rp = self.restore_points();
753 Ok(Stats {
754 memories: self.len(),
755 deleted,
756 dimensions: self.dimensions,
757 file_bytes,
758 agents,
759 encrypted: self.header.flags & FLAG_ENCRYPTED != 0,
760 created_at: self.header.created_at,
761 index: {
762 self.ensure_ann()?;
763 self.ann.as_ref().map(|a| a.info())
764 },
765 wal_pages: self.header.wal_pages,
766 fsyncs_last_flush: self.fsyncs_last_flush,
767 format_version: self.header.version,
768 recall_mode,
769 snapshots_retained: rp.retained,
770 oldest_restorable_at: rp.oldest_at,
771 snapshot_pinned_bytes: rp.pinned_bytes,
772 keyword_tokenizer: self.keyword_tokenizer()?,
773 })
774 }
775
776 /// Rewrite the file, dropping tombstoned and expired memories and
777 /// reclaiming stale pages left by updates. Done out-of-place via a temp
778 /// file and an atomic rename.
779 ///
780 /// FIX-1 R-001.1 + R-002.2 part 2: the result cache now survives
781 /// compaction. Every live, non-expired directory entry is copied
782 /// into the new file verbatim — `created_at`, `ttl_secs`,
783 /// `cost_hint_ms`, `key_preview`, `size_bytes`, `content_type`,
784 /// `vector` and `model` come from the record body; `accessed_at`
785 /// and `access_count` come from the *directory* (the record body
786 /// only holds the insert-time snapshot — the directory is the
787 /// source of truth for the live counts, as of v5's recall trick).
788 /// Tombstoned and TTL-expired entries are dropped. Pre-FIX-1
789 /// compaction kept only the memory catalog and silently emptied
790 /// the cache; the Planner's interim README caveat (c417d2e) called
791 /// that out — this PR removes the surprise.
792 ///
793 /// The output is always v9, so this is also how a v4–v8 file is
794 /// converted: the only read-write open that accepts one (the v8
795 /// sunset, v0.13). It keeps every live memory.
796 pub fn compact_file(path: &str, passphrase: &str) -> Result<CompactReport> {
797 Self::compact_file_secret(
798 path,
799 passphrase.as_bytes(),
800 SecretKind::Passphrase,
801 0,
802 &crate::SharedOptions::default(),
803 )
804 }
805
806 /// PERF-1 step 7: [`Mnemo::compact_file`] for a raw-key database.
807 pub fn compact_file_with_key(path: &str, key: &[u8; crypto::KEY_LEN]) -> Result<CompactReport> {
808 Self::compact_file_secret(
809 path,
810 key,
811 SecretKind::Key,
812 0,
813 &crate::SharedOptions::default(),
814 )
815 }
816
817 /// [`Mnemo::compact_file`] with the lock layer's options: how long to
818 /// wait for the file's lock (`opts.deadline`; `compact_file` waits 10 s),
819 /// a cancel, and `allow_network_fs`. `mnemo compact --wait` uses it.
820 pub fn compact_file_waiting(
821 path: &str,
822 passphrase: &str,
823 opts: crate::SharedOptions,
824 ) -> Result<CompactReport> {
825 Self::compact_file_secret(
826 path,
827 passphrase.as_bytes(),
828 SecretKind::Passphrase,
829 0,
830 &opts,
831 )
832 }
833
834 /// [`Mnemo::compact_file_waiting`] for a raw-key database.
835 pub fn compact_file_waiting_with_key(
836 path: &str,
837 key: &[u8; crypto::KEY_LEN],
838 opts: crate::SharedOptions,
839 ) -> Result<CompactReport> {
840 Self::compact_file_secret(path, key, SecretKind::Key, 0, &opts)
841 }
842
843 pub(super) fn compact_file_secret(
844 path: &str,
845 secret: &[u8],
846 kind: SecretKind,
847 format_version: u16,
848 opts: &crate::SharedOptions,
849 ) -> Result<CompactReport> {
850 // RB-007.3: compact the file the path names, through any symlink,
851 // and rename over that file, so a link stays a link and every path
852 // to the brain names the new file.
853 let real = std::fs::canonicalize(path)?;
854 // The one read-write open that takes a v4–v8 file (the v8 sunset).
855 // RB-007.4: through the lock layer, so shared handles' busy reads
856 // can't keep it out, and a shared caller that times out reads
857 // "compact" in the lock-info note.
858 let old = Mnemo::open_exclusive_secret(&real, secret, "compact", opts, true)?;
859 // RB-007.8 item 8: with the exclusive lock held no compaction of
860 // this file is running, so temp files left by dead ones can go.
861 remove_dead_compaction_temps(&real);
862 let dims = old.dimensions;
863 // 12.3 (the keys note, section 1, rule 6): never lower the
864 // parameters, and raise a passphrase file that's below the floor.
865 let kdf = if kind == SecretKind::Passphrase && old.kdf.below_passphrase_floor() {
866 old.kdf.for_passphrase()
867 } else {
868 old.kdf
869 };
870 // 12.3 (the salt rule): the new file keeps the salt, so whatever
871 // found the secret for the old file (a keychain entry) finds it.
872 let salt = old.header.salt;
873 let config = MnemoConfig {
874 dimensions: dims,
875 kdf,
876 // FMT-9f: compaction writes v9 (upgrading a v8 file),
877 // unless `compact_file_to` asked for v8. A v9 file that
878 // keeps float vectors keeps them.
879 format_version,
880 store_float_vectors: old.float_vectors(),
881 ..Default::default()
882 };
883 // v0.14.0 step 1: a new file under a name no other compaction shares.
884 let (tmp, new) = create_temp(&real, "compact", secret, kind, config, Some(salt))?;
885 // Created owner-only; it keeps the old file's mode.
886 if let Err(e) = copy_mode(old.pager.file(), new.pager.file()) {
887 drop(new);
888 let _ = std::fs::remove_file(&tmp);
889 return Err(e);
890 }
891 // `compact_into` releases the old file's lock only after the rename.
892 let result = Self::compact_into(old, new, &real, &tmp, |old, new| old.copy_live_into(new));
893 if result.is_err() {
894 let _ = std::fs::remove_file(&tmp);
895 }
896 result
897 }
898
899 /// Write the compacted copy of `old` to `tmp`, then rename it over
900 /// `path`, all while `old` holds the old file's exclusive lock.
901 ///
902 /// v0.14.0 step 1 (12.4's design note, "Gaps in today's code"): the lock
903 /// used to be released before the rename. A process that opened the
904 /// path in that window locked the old file and wrote to it, and the
905 /// rename then replaced it, losing those writes. Holding the lock
906 /// through the rename and the directory sync means a process either
907 /// waits on the old file's lock (and then finds, by `open_with_lock`'s
908 /// identity check, that the path names the new file) or opens the new
909 /// file.
910 ///
911 /// **Windows and the toolchain.** Renaming over a file another handle
912 /// holds open and locked works on Linux and macOS with every toolchain,
913 /// and on Windows when the engine is built with Rust 1.85 or later,
914 /// whose `std::fs::rename` uses POSIX semantics. Built with 1.75 to 1.84
915 /// (the MSRV is 1.75), Windows refuses it with "Access is denied" (os
916 /// error 5) while the old file is open, so the rename is retried once
917 /// after the old handle is closed, as before v0.14.0. That leaves the
918 /// old window open for those builds; each commit's identity check
919 /// (`ensure_not_replaced`) then turns nearly every write that would have
920 /// been lost into `Replaced`. (Probed on CI, 2026-11-13: 1.75 to 1.84
921 /// refuse, 1.85 to 1.100 succeed; the released binaries are built with
922 /// stable.)
923 fn compact_into<R>(
924 mut old: Mnemo,
925 mut new: Mnemo,
926 path: &Path,
927 tmp: &Path,
928 copy: impl FnOnce(&mut Mnemo, &mut Mnemo) -> Result<R>,
929 ) -> Result<R> {
930 let report = copy(&mut old, &mut new)?;
931
932 new.flush()?;
933 // The new file is closed before the rename: Windows won't rename a
934 // file this process still has open.
935 drop(new);
936
937 match std::fs::rename(tmp, path) {
938 Ok(()) => {}
939 #[cfg(windows)]
940 Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
941 // A toolchain before 1.85: see above.
942 drop(old);
943 std::fs::rename(tmp, path)?;
944 return Ok(report);
945 }
946 Err(e) => return Err(MnemoError::Io(e)),
947 }
948 // Make the rename durable before the old file's lock goes.
949 #[cfg(unix)]
950 if let Some(parent) = path.parent() {
951 let parent = if parent.as_os_str().is_empty() {
952 Path::new(".")
953 } else {
954 parent
955 };
956 if let Ok(dir) = File::open(parent) {
957 let _ = dir.sync_all();
958 crate::bump_fsync();
959 }
960 }
961 // Only now does the old file's lock go.
962 drop(old);
963 Ok(report)
964 }
965
966 /// 12.3 step 4 (v0.15): **embed every live memory again with
967 /// `embedder`** and record its identity, so a file moves to a new model
968 /// (or a new query convention, or a new width) in one step.
969 ///
970 /// It's a compaction with new vectors: it runs under the file's
971 /// exclusive lock (waiting 10 s for it, like [`Mnemo::compact_file`]),
972 /// writes a temp file beside the brain with the same salt and KDF
973 /// parameters, and renames it over the brain while the lock is held. An
974 /// interrupted run leaves the old file whole (and a temp file the next
975 /// compaction or reembed removes), so the file never opens with two
976 /// identities or mixed vectors.
977 ///
978 /// - Every live memory is embedded with [`Embedder::embed`] (the
979 /// document side), in batches of 64: facts, superseded versions (so
980 /// history reads stay consistent), essence items and thread turns.
981 /// A manifest and a thread link (`_mnemo.kind = "thread_link"`) keep
982 /// their sentinel vector, at the new width, and aren't embedded.
983 /// - The new identity is recorded in the `_mnemo.embedder` entry and in
984 /// the manifest's `metadata.embedder`.
985 /// - The result cache is copied as compaction copies it; a semantic
986 /// entry whose vector has the old width is dropped.
987 /// - The ANN index is rebuilt if there was one, and the keyword index
988 /// with the current tokenizer (TOK-1). Snapshot history is dropped,
989 /// as by compaction.
990 pub fn reembed_file(
991 path: &str,
992 passphrase: &str,
993 embedder: &dyn Embedder,
994 ) -> Result<ReembedReport> {
995 Self::reembed_file_secret(
996 path,
997 passphrase.as_bytes(),
998 SecretKind::Passphrase,
999 embedder,
1000 &crate::SharedOptions::default(),
1001 )
1002 }
1003
1004 /// [`Mnemo::reembed_file`] for a raw-key database.
1005 pub fn reembed_file_with_key(
1006 path: &str,
1007 key: &[u8; crypto::KEY_LEN],
1008 embedder: &dyn Embedder,
1009 ) -> Result<ReembedReport> {
1010 Self::reembed_file_secret(
1011 path,
1012 key,
1013 SecretKind::Key,
1014 embedder,
1015 &crate::SharedOptions::default(),
1016 )
1017 }
1018
1019 /// [`Mnemo::reembed_file`] with the lock layer's options (how long to
1020 /// wait for the lock, a cancel), as [`Mnemo::compact_file_waiting`].
1021 pub fn reembed_file_waiting(
1022 path: &str,
1023 passphrase: &str,
1024 embedder: &dyn Embedder,
1025 opts: crate::SharedOptions,
1026 ) -> Result<ReembedReport> {
1027 Self::reembed_file_secret(
1028 path,
1029 passphrase.as_bytes(),
1030 SecretKind::Passphrase,
1031 embedder,
1032 &opts,
1033 )
1034 }
1035
1036 /// [`Mnemo::reembed_file_waiting`] for a raw-key database.
1037 pub fn reembed_file_waiting_with_key(
1038 path: &str,
1039 key: &[u8; crypto::KEY_LEN],
1040 embedder: &dyn Embedder,
1041 opts: crate::SharedOptions,
1042 ) -> Result<ReembedReport> {
1043 Self::reembed_file_secret(path, key, SecretKind::Key, embedder, &opts)
1044 }
1045
1046 fn reembed_file_secret(
1047 path: &str,
1048 secret: &[u8],
1049 kind: SecretKind,
1050 embedder: &dyn Embedder,
1051 opts: &crate::SharedOptions,
1052 ) -> Result<ReembedReport> {
1053 let to = embedder.identity();
1054 if to.dimensions == 0 {
1055 return Err(MnemoError::Invalid(
1056 "reembed: the embedder's identity has 0 dimensions".into(),
1057 ));
1058 }
1059 let real = std::fs::canonicalize(path)?;
1060 let mut old = Mnemo::open_exclusive_secret(&real, secret, "reembed", opts, true)?;
1061 remove_dead_temps(&real, "reembed");
1062 let from = old.recorded_identity()?;
1063 let kdf = if kind == SecretKind::Passphrase && old.kdf.below_passphrase_floor() {
1064 old.kdf.for_passphrase()
1065 } else {
1066 old.kdf
1067 };
1068 let salt = old.header.salt;
1069 let config = MnemoConfig {
1070 dimensions: to.dimensions,
1071 kdf,
1072 format_version: 0,
1073 store_float_vectors: old.float_vectors(),
1074 ..Default::default()
1075 };
1076 let (tmp, new) = create_temp(&real, "reembed", secret, kind, config, Some(salt))?;
1077 if let Err(e) = copy_mode(old.pager.file(), new.pager.file()) {
1078 drop(new);
1079 let _ = std::fs::remove_file(&tmp);
1080 return Err(e);
1081 }
1082 let result = Self::compact_into(old, new, &real, &tmp, |old, new| {
1083 old.copy_reembedded_into(new, embedder, from.clone(), to.clone())
1084 });
1085 if result.is_err() {
1086 let _ = std::fs::remove_file(&tmp);
1087 }
1088 result
1089 }
1090
1091 /// [`Mnemo::reembed_file`]'s copy: every live memory with a new vector,
1092 /// the new identity, and the cache.
1093 fn copy_reembedded_into(
1094 &mut self,
1095 new: &mut Mnemo,
1096 embedder: &dyn Embedder,
1097 from: Option<embed::EmbedderIdentity>,
1098 to: embed::EmbedderIdentity,
1099 ) -> Result<ReembedReport> {
1100 const BATCH: usize = 64;
1101 new.turn_compress_after = 0;
1102 let want_index = self.has_index();
1103 let now = memory::now_secs();
1104 let dims = to.dimensions;
1105 let mut live: Vec<Memory> = self
1106 .memories()?
1107 .into_iter()
1108 .filter(|m| !m.is_expired(now))
1109 .collect();
1110 let mut manifests = 0;
1111 let mut thread_links = 0;
1112 for m in live.iter_mut() {
1113 if embed::read_identity_from_metadata(&m.metadata).is_some() {
1114 embed::write_identity_into_metadata(&mut m.metadata, &to);
1115 }
1116 }
1117 // R-008.3: a manifest and a thread link carry a sentinel vector, not
1118 // an embedding of their text.
1119 let is_link = |m: &Memory| {
1120 m.metadata.get(MNEMO_META_KIND).and_then(|v| v.as_str())
1121 == Some(MNEMO_META_KIND_THREAD_LINK)
1122 };
1123 let to_embed: Vec<usize> = (0..live.len())
1124 .filter(|&i| !is_manifest(&live[i]) && !is_link(&live[i]))
1125 .collect();
1126 for chunk in to_embed.chunks(BATCH) {
1127 let texts: Vec<&str> = chunk.iter().map(|&i| live[i].content.as_str()).collect();
1128 let vectors = embedder.embed(&texts)?;
1129 if vectors.len() != texts.len() {
1130 return Err(MnemoError::Invalid(format!(
1131 "reembed: the embedder returned {} vectors for {} texts",
1132 vectors.len(),
1133 texts.len()
1134 )));
1135 }
1136 for (&i, v) in chunk.iter().zip(vectors) {
1137 if v.len() != dims {
1138 return Err(MnemoError::DimensionMismatch {
1139 expected: dims,
1140 got: v.len(),
1141 });
1142 }
1143 if embed::is_zero_vector(&v) {
1144 return Err(MnemoError::Invalid(format!(
1145 "reembed: the embedder returned an all-zero vector for memory {}",
1146 live[i].id
1147 )));
1148 }
1149 live[i].vector = v;
1150 }
1151 }
1152 let memories = live.len();
1153 for mut m in live {
1154 if is_manifest(&m) {
1155 m.vector = Memory::scaffold_manifest(dims).vector;
1156 manifests += 1;
1157 } else if is_link(&m) {
1158 m.vector = new.sentinel_vector();
1159 thread_links += 1;
1160 }
1161 new.put_existing(m)?;
1162 }
1163 if want_index && memories > 0 {
1164 new.build_index_with(IndexConfig::default())?;
1165 }
1166 let mut cache_entries = 0;
1167 let mut cache_dropped = 0;
1168 for pos in 0..self.cache_dir.len() {
1169 let (keep, reserved, wrong_width) = {
1170 let e = &self.cache_dir[pos];
1171 (
1172 !e.deleted && !e.is_expired(now),
1173 embed::is_reserved_namespace(&e.namespace),
1174 e.vector.as_ref().is_some_and(|v| v.len() != dims),
1175 )
1176 };
1177 if !keep || (reserved && self.cache_dir[pos].namespace == embed::IDENTITY_NAMESPACE) {
1178 continue;
1179 }
1180 if wrong_width {
1181 cache_dropped += 1;
1182 continue;
1183 }
1184 new.copy_cache_entry_from(self, pos)?;
1185 if !reserved {
1186 cache_entries += 1;
1187 }
1188 }
1189 new.record_identity(&to)?;
1190 Ok(ReembedReport {
1191 memories: memories - manifests - thread_links,
1192 manifests,
1193 thread_links,
1194 cache_entries,
1195 cache_dropped,
1196 from,
1197 to,
1198 })
1199 }
1200
1201 /// Copy one live cache entry from `old` at directory position
1202 /// `pos` into `self` (a freshly-created compaction target).
1203 /// Decrypts the old record body, substitutes the old *directory*'s
1204 /// `accessed_at` + `access_count` (the record body's copies are
1205 /// stale as of v5's directory-only hit path), re-encodes, writes
1206 /// a fresh record run, and pushes a matching directory entry.
1207 ///
1208 /// Caller is expected to have already filtered out tombstoned /
1209 /// expired entries and to call this on a read-write handle.
1210 pub(crate) fn copy_cache_entry_from(&mut self, old: &mut Mnemo, pos: usize) -> Result<()> {
1211 if self.read_only {
1212 return Err(MnemoError::ReadOnly);
1213 }
1214 // Snapshot the directory fields we need, so the borrow on
1215 // `old.cache_dir` ends before we touch `old.pager`.
1216 let (start_page, page_count, len, dir_accessed_at, dir_access_count, old_gen) = {
1217 let e = &old.cache_dir[pos];
1218 (
1219 e.start_page,
1220 e.page_count,
1221 e.len,
1222 e.accessed_at,
1223 e.access_count,
1224 e.gen,
1225 )
1226 };
1227
1228 // Read + decrypt the old record body.
1229 let buf = old.read_record_run(start_page, page_count, len, old_gen)?;
1230 let mut entry: CacheEntry =
1231 rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))?;
1232
1233 // Overwrite the stale body copies with the directory's live
1234 // values before persisting. Everything else — `created_at`,
1235 // `ttl_secs`, `cost_hint_ms`, `key_preview`, `size_bytes`,
1236 // `content_type`, `value`, `vector`, `model` — stays as the
1237 // body already recorded it.
1238 entry.accessed_at = dir_accessed_at;
1239 entry.access_count = dir_access_count;
1240
1241 let bytes =
1242 rmp_serde::to_vec(&entry).map_err(|err| MnemoError::Serialize(err.to_string()))?;
1243 let (new_start_page, new_page_count, gen) = self.write_record(&bytes)?;
1244
1245 let dir_entry = CacheDirectoryEntry {
1246 namespace: entry.namespace.clone(),
1247 key_hash: entry.key_hash,
1248 start_page: new_start_page,
1249 page_count: new_page_count,
1250 len: bytes.len() as u32,
1251 deleted: false,
1252 accessed_at: dir_accessed_at,
1253 access_count: dir_access_count,
1254 size_bytes: entry.size_bytes,
1255 ttl_secs: entry.ttl_secs,
1256 created_at: entry.created_at,
1257 vector: entry.vector.clone(),
1258 model: entry.model.clone(),
1259 gen,
1260 };
1261 let new_pos = self.cache_dir.len();
1262 self.cache_idx
1263 .insert(&entry.namespace, entry.key_hash, new_pos);
1264 self.cache_dir.push(dir_entry);
1265 self.dirty_cache = true;
1266 Ok(())
1267 }
1268}
1269
1270/// SEC-2 (RB-001.30): overwrite every occurrence of `needle` in the file
1271/// with zeros, then sync. Rekey uses it for stale copies of the old header's
1272/// key wrap: they're plaintext (page 0 is sealed, not encrypted) and can sit
1273/// in WAL regions that were grown, relocated or freed. Every other page is
1274/// AES-GCM ciphertext, where a 76-byte random match doesn't happen.
1275pub(super) fn scrub_bytes(file: &mut std::fs::File, needle: &[u8]) -> Result<usize> {
1276 if needle.is_empty() {
1277 return Ok(0);
1278 }
1279 let len = file.seek(SeekFrom::End(0))?;
1280 let chunk = 1 << 20;
1281 let overlap = needle.len() - 1;
1282 let mut hits: Vec<u64> = Vec::new();
1283 let mut buf = vec![0u8; chunk + overlap];
1284 let mut pos: u64 = 0;
1285 while pos < len {
1286 let want = (chunk as u64 + overlap as u64).min(len - pos) as usize;
1287 file.seek(SeekFrom::Start(pos))?;
1288 file.read_exact(&mut buf[..want])?;
1289 let mut i = 0;
1290 while i + needle.len() <= want {
1291 if buf[i..i + needle.len()] == *needle {
1292 hits.push(pos + i as u64);
1293 i += needle.len();
1294 } else {
1295 i += 1;
1296 }
1297 }
1298 pos += chunk as u64;
1299 }
1300 hits.dedup();
1301 let zeros = vec![0u8; needle.len()];
1302 for off in &hits {
1303 file.seek(SeekFrom::Start(*off))?;
1304 file.write_all(&zeros)?;
1305 }
1306 if !hits.is_empty() {
1307 file.sync_all()?;
1308 crate::bump_fsync();
1309 }
1310 Ok(hits.len())
1311}
1312
1313/// RB-007.8 item 8: remove the temp files that compactions of `brain` left
1314/// when their process died: in `brain`'s directory, regular files named
1315/// exactly `<brain's name>.compact-<pid>-<n>-<8 hex digits>.tmp` (the
1316/// pattern [`temp_sibling`] makes) whose pid isn't this process and no
1317/// longer runs, and, on Unix, that this user owns: in a shared directory
1318/// another user's file of the same name is left alone. Nothing else is
1319/// touched. Best effort; returns how many went.
1320///
1321/// Call it only with `brain`'s exclusive lock held: a live compaction holds
1322/// that lock for as long as its temp file exists. Off Unix no process
1323/// check is available, so nothing is removed.
1324pub(crate) fn remove_dead_compaction_temps(brain: &Path) -> usize {
1325 remove_dead_temps(brain, "compact")
1326}
1327
1328/// [`remove_dead_compaction_temps`] for the temps of another operation
1329/// (`what`, as [`temp_sibling`] names them): 12.3's `init` uses "init".
1330pub(crate) fn remove_dead_temps(brain: &Path, what: &str) -> usize {
1331 let (Some(dir), Some(name)) = (brain.parent(), brain.file_name()) else {
1332 return 0;
1333 };
1334 let prefix = format!("{}.{what}-", name.to_string_lossy());
1335 let Ok(entries) = std::fs::read_dir(dir) else {
1336 return 0;
1337 };
1338 let mut removed = 0;
1339 for entry in entries.flatten() {
1340 let file_name = entry.file_name();
1341 let Some(pid) = file_name.to_str().and_then(|n| dead_temp_pid(n, &prefix)) else {
1342 continue;
1343 };
1344 if pid == std::process::id() || crate::shared::pid_alive(pid) {
1345 continue;
1346 }
1347 let path = entry.path();
1348 let Ok(meta) = std::fs::symlink_metadata(&path) else {
1349 continue;
1350 };
1351 if !meta.file_type().is_file() || !owned_by_us(&meta) {
1352 continue;
1353 }
1354 if std::fs::remove_file(&path).is_ok() {
1355 removed += 1;
1356 }
1357 }
1358 removed
1359}
1360
1361/// Whether this process's user owns the file (Unix). Elsewhere, true: the
1362/// caller removes nothing off Unix anyway.
1363#[cfg(unix)]
1364fn owned_by_us(meta: &std::fs::Metadata) -> bool {
1365 use std::os::unix::fs::MetadataExt;
1366 #[cfg(any(test, feature = "failpoints"))]
1367 if let Some(uid) = crate::__failpoints::euid_override() {
1368 return meta.uid() == uid;
1369 }
1370 meta.uid() == rustix::process::geteuid().as_raw()
1371}
1372
1373#[cfg(not(unix))]
1374fn owned_by_us(_meta: &std::fs::Metadata) -> bool {
1375 true
1376}
1377
1378/// The pid in a compaction temp name `<prefix><pid>-<n>-<8 hex>.tmp`, if the
1379/// name is exactly that.
1380fn dead_temp_pid(name: &str, prefix: &str) -> Option<u32> {
1381 let rest = name.strip_prefix(prefix)?.strip_suffix(".tmp")?;
1382 let mut parts = rest.split('-');
1383 let (pid, n, nanos) = (parts.next()?, parts.next()?, parts.next()?);
1384 let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
1385 let hex8 = nanos.len() == 8 && nanos.bytes().all(|b| b.is_ascii_hexdigit());
1386 if parts.next().is_some() || !digits(pid) || !digits(n) || !hex8 {
1387 return None;
1388 }
1389 pid.parse().ok()
1390}
1391
1392/// The phrase REKEY-1's one exception carries; `mnemo rekey` and
1393/// [`crate::keys::rekey_stored`] look for it.
1394const EITHER_SECRET: &str = "may open with either secret";
1395
1396/// A new, locked temp file next to `dest` (`Create::New`, so nothing already
1397/// at the name, a symlink included, is ever written through), under a fresh
1398/// name for each attempt while names are taken. RB-006.10.
1399pub(crate) fn create_temp(
1400 dest: &Path,
1401 what: &str,
1402 secret: &[u8],
1403 kind: SecretKind,
1404 config: MnemoConfig,
1405 salt: Option<[u8; crypto::SALT_LEN]>,
1406) -> Result<(PathBuf, Mnemo)> {
1407 let mut attempt = 0;
1408 loop {
1409 let tmp = temp_sibling(dest, what);
1410 match Mnemo::create_secret_new(&tmp, secret, kind, config, salt) {
1411 Ok(new) => return Ok((tmp, new)),
1412 Err(e) if is_name_taken(&e) && attempt + 1 < TEMP_NAME_ATTEMPTS => attempt += 1,
1413 Err(e) => return Err(e),
1414 }
1415 }
1416}