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 who can open the file from now on, as long as nobody
117 /// kept the old secret.** The data key stays the same, so anyone who had
118 /// the file (or any copy or backup of it) and the old passphrase can
119 /// still read it, and everything written to it later. The old wrap is
120 /// scrubbed from this file (the previous WAL region is zeroed, and any
121 /// stale copy of the old header's key wrap is overwritten), but an
122 /// earlier copy keeps it. To revoke an old secret, rotate: rekey, then
123 /// [`Mnemo::compact_file`] (`mnemo rekey --rotate`), which rewrites the
124 /// file under a fresh data key.
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 for m in all {
289 if m.is_expired(now) {
290 continue;
291 }
292 new.remember(m)?;
293 after += 1;
294 }
295 if want_index && after > 0 {
296 new.build_index_with(IndexConfig::default())?;
297 }
298
299 // Count + copy cache entries. We walk `self.cache_dir` by index
300 // so each hop reads the directory's live `accessed_at` /
301 // `access_count` directly rather than going through
302 // `cache_get` (which would also treat read-only semantics,
303 // tombstones, etc. — we want the raw, authoritative values).
304 let mut cache_before = 0usize;
305 let mut cache_after = 0usize;
306 let positions: Vec<usize> = (0..self.cache_dir.len()).collect();
307 for pos in positions {
308 let keep = {
309 let e = &self.cache_dir[pos];
310 !e.deleted && !e.is_expired(now)
311 };
312 if keep {
313 cache_before += 1;
314 new.copy_cache_entry_from(self, pos)?;
315 cache_after += 1;
316 }
317 }
318 Ok(CompactReport {
319 before,
320 after,
321 cache_before,
322 cache_after,
323 })
324 }
325
326 /// Decrypt and validate every live record. Returns the count verified
327 /// across memories **and** cache entries (FIX-1 R-001.1: now that the
328 /// cache survives compaction, `verify()` has to walk it too — the
329 /// pre-FIX-1 implementation only checked `self.catalog`, so a
330 /// corrupted cache record went unnoticed).
331 pub fn verify(&mut self) -> Result<usize> {
332 let entries: Vec<CatalogEntry> = self
333 .catalog
334 .iter()
335 .filter(|e| !e.deleted)
336 .cloned()
337 .collect();
338 let mut n = entries.len();
339 for e in &entries {
340 let bytes = self.read_record(e)?;
341 let _m: Memory = self.decode_memory(&bytes)?;
342 // FMT-9b: and the row's vector column entry.
343 if e.v9.is_some() {
344 let (h, _) = self.column_entry(e)?;
345 if h.len() != self.dimensions {
346 return Err(MnemoError::Invalid(
347 "vector entry has the wrong width".into(),
348 ));
349 }
350 }
351 }
352
353 // Also decode every live cache entry. Tombstoned entries are
354 // skipped — their pages are orphan ciphertext awaiting
355 // `compact_file`, same as deleted memories. Expired entries
356 // are *still* on disk until compaction, so we verify them too.
357 let cache_positions: Vec<(u64, u32, u32, u64)> = self
358 .cache_dir
359 .iter()
360 .filter(|e| !e.deleted)
361 .map(|e| (e.start_page, e.page_count, e.len, e.gen))
362 .collect();
363 for (start_page, page_count, len, gen) in cache_positions {
364 let buf = self.read_record_run(start_page, page_count, len, gen)?;
365 let _c: CacheEntry = rmp_serde::from_slice(&buf)
366 .map_err(|err| MnemoError::Serialize(err.to_string()))?;
367 n += 1;
368 }
369 // FMT-9 (a): no free run may overlap a page the committed state
370 // references (records, cache entries, control runs, the WAL).
371 if self.is_v9() {
372 self.check_free_list_disjoint()?;
373 }
374 Ok(n)
375 }
376
377 /// FMT-9 (a): fail if the free list (or a pending free) overlaps any
378 /// page the current state references.
379 pub(super) fn check_free_list_disjoint(&self) -> Result<()> {
380 let h = &self.header;
381 let mut live: Vec<(u64, u64, &str)> = vec![
382 (h.wal_start, h.wal_pages, "WAL region"),
383 (h.catalog_start, h.catalog_pages, "catalog run"),
384 (h.index_start, h.index_pages, "index run"),
385 (h.manifest_start, h.manifest_pages, "manifest run"),
386 (h.cache_start, h.cache_pages, "cache directory run"),
387 (h.free.start, h.free.pages, "free-list run"),
388 (h.keys.start, h.keys.pages, "key-slot run"),
389 ];
390 live.extend(
391 self.catalog
392 .iter()
393 .filter(|e| !e.deleted)
394 .map(|e| (e.start_page, e.page_count as u64, "record")),
395 );
396 live.extend(
397 self.cache_dir
398 .iter()
399 .filter(|e| !e.deleted)
400 .map(|e| (e.start_page, e.page_count as u64, "cache entry")),
401 );
402 live.extend(self.col.page_rows.keys().map(|&p| (p, 1, "vector page")));
403 live.extend(
404 self.delta_chain
405 .iter()
406 .map(|r| (r.start, r.pages, "catalog delta run")),
407 );
408 live.extend(
409 self.index_chain
410 .iter()
411 .map(|r| (r.start, r.pages, "index delta run")),
412 );
413 live.push((
414 self.header.bm25.start,
415 self.header.bm25.pages,
416 "BM25 manifest",
417 ));
418 live.extend(
419 self.bm25
420 .manifest
421 .segments
422 .iter()
423 .map(|t| (t.0, t.1, "BM25 segment")),
424 );
425 for (p, c, what) in live {
426 if c == 0 {
427 continue;
428 }
429 if self.free.overlaps(p, c) {
430 return Err(MnemoError::Invalid(format!(
431 "free list overlaps a live {what} at page {p} (+{c})"
432 )));
433 }
434 if self
435 .pending_free
436 .iter()
437 .any(|&(q, n)| q < p + c && p < q + n)
438 {
439 return Err(MnemoError::Invalid(format!(
440 "a pending free overlaps a live {what} at page {p} (+{c})"
441 )));
442 }
443 }
444 Ok(())
445 }
446
447 /// Summary statistics for the open database.
448 pub fn stats(&mut self) -> Result<Stats> {
449 let deleted = self.catalog.iter().filter(|e| e.deleted).count();
450 // FIX-1 R-001.8 part 2: build the agent set lazily on first
451 // call per handle, then maintain in `put` / invalidate in
452 // `delete`. Pre-FIX-1 every `stats()` call decrypted every
453 // live memory (O(N) AES-GCM decrypts just to list a usually-
454 // tiny set of distinct agent IDs). On a 1M-memory database
455 // this was in the multi-second range on hardware AES.
456 if self.agent_set.is_none() {
457 let built: std::collections::BTreeSet<String> =
458 self.memories()?.into_iter().map(|m| m.agent_id).collect();
459 self.agent_set = Some(built);
460 }
461 let agents: Vec<String> = self
462 .agent_set
463 .as_ref()
464 .expect("agent_set just filled above")
465 .iter()
466 .cloned()
467 .collect();
468 let file_bytes = self.header.next_page * PAGE_SIZE as u64;
469 let recall_mode = self.recall_mode()?;
470 Ok(Stats {
471 memories: self.len(),
472 deleted,
473 dimensions: self.dimensions,
474 file_bytes,
475 agents,
476 encrypted: self.header.flags & FLAG_ENCRYPTED != 0,
477 created_at: self.header.created_at,
478 index: {
479 self.ensure_ann()?;
480 self.ann.as_ref().map(|a| a.info())
481 },
482 wal_pages: self.header.wal_pages,
483 fsyncs_last_flush: self.fsyncs_last_flush,
484 format_version: self.header.version,
485 recall_mode,
486 })
487 }
488
489 /// Rewrite the file, dropping tombstoned and expired memories and
490 /// reclaiming stale pages left by updates. Done out-of-place via a temp
491 /// file and an atomic rename.
492 ///
493 /// FIX-1 R-001.1 + R-002.2 part 2: the result cache now survives
494 /// compaction. Every live, non-expired directory entry is copied
495 /// into the new file verbatim — `created_at`, `ttl_secs`,
496 /// `cost_hint_ms`, `key_preview`, `size_bytes`, `content_type`,
497 /// `vector` and `model` come from the record body; `accessed_at`
498 /// and `access_count` come from the *directory* (the record body
499 /// only holds the insert-time snapshot — the directory is the
500 /// source of truth for the live counts, as of v5's recall trick).
501 /// Tombstoned and TTL-expired entries are dropped. Pre-FIX-1
502 /// compaction kept only the memory catalog and silently emptied
503 /// the cache; the Planner's interim README caveat (c417d2e) called
504 /// that out — this PR removes the surprise.
505 pub fn compact_file(path: &str, passphrase: &str) -> Result<CompactReport> {
506 Self::compact_file_secret(path, passphrase.as_bytes(), 0)
507 }
508
509 /// PERF-1 step 7: [`Mnemo::compact_file`] for a raw-key database.
510 pub fn compact_file_with_key(path: &str, key: &[u8; crypto::KEY_LEN]) -> Result<CompactReport> {
511 Self::compact_file_secret(path, key, 0)
512 }
513
514 /// FMT-9f: [`Mnemo::compact_file`] into an explicit format: `9` (what
515 /// `compact_file` does) or `8`, which keeps a v8 file readable by
516 /// v0.10 and earlier. The v8 target is kept for one release.
517 pub fn compact_file_to(
518 path: &str,
519 passphrase: &str,
520 format_version: u16,
521 ) -> Result<CompactReport> {
522 if format_version != VERSION && format_version != VERSION_V9 {
523 return Err(MnemoError::Invalid(format!(
524 "compact target format {format_version} isn't supported (use 8 or 9)"
525 )));
526 }
527 Self::compact_file_secret(path, passphrase.as_bytes(), format_version)
528 }
529
530 pub(super) fn compact_file_secret(
531 path: &str,
532 secret: &[u8],
533 format_version: u16,
534 ) -> Result<CompactReport> {
535 let mut old = Mnemo::open_secret(path, secret)?;
536 let dims = old.dimensions;
537 let kdf = old.kdf;
538 let tmp = format!("{path}.compact-tmp");
539
540 let mut new = Mnemo::create_secret(
541 &tmp,
542 secret,
543 MnemoConfig {
544 dimensions: dims,
545 kdf,
546 // FMT-9f: compaction writes v9 (upgrading a v8 file),
547 // unless `compact_file_to` asked for v8. A v9 file that
548 // keeps float vectors keeps them.
549 format_version,
550 store_float_vectors: old.float_vectors(),
551 ..Default::default()
552 },
553 )?;
554 let report = old.copy_live_into(&mut new)?;
555
556 new.flush()?;
557 drop(new);
558 drop(old);
559
560 std::fs::rename(&tmp, path)?;
561 Ok(report)
562 }
563
564 /// Copy one live cache entry from `old` at directory position
565 /// `pos` into `self` (a freshly-created compaction target).
566 /// Decrypts the old record body, substitutes the old *directory*'s
567 /// `accessed_at` + `access_count` (the record body's copies are
568 /// stale as of v5's directory-only hit path), re-encodes, writes
569 /// a fresh record run, and pushes a matching directory entry.
570 ///
571 /// Caller is expected to have already filtered out tombstoned /
572 /// expired entries and to call this on a read-write handle.
573 pub(crate) fn copy_cache_entry_from(&mut self, old: &mut Mnemo, pos: usize) -> Result<()> {
574 if self.read_only {
575 return Err(MnemoError::ReadOnly);
576 }
577 // Snapshot the directory fields we need, so the borrow on
578 // `old.cache_dir` ends before we touch `old.pager`.
579 let (start_page, page_count, len, dir_accessed_at, dir_access_count, old_gen) = {
580 let e = &old.cache_dir[pos];
581 (
582 e.start_page,
583 e.page_count,
584 e.len,
585 e.accessed_at,
586 e.access_count,
587 e.gen,
588 )
589 };
590
591 // Read + decrypt the old record body.
592 let buf = old.read_record_run(start_page, page_count, len, old_gen)?;
593 let mut entry: CacheEntry =
594 rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))?;
595
596 // Overwrite the stale body copies with the directory's live
597 // values before persisting. Everything else — `created_at`,
598 // `ttl_secs`, `cost_hint_ms`, `key_preview`, `size_bytes`,
599 // `content_type`, `value`, `vector`, `model` — stays as the
600 // body already recorded it.
601 entry.accessed_at = dir_accessed_at;
602 entry.access_count = dir_access_count;
603
604 let bytes =
605 rmp_serde::to_vec(&entry).map_err(|err| MnemoError::Serialize(err.to_string()))?;
606 let (new_start_page, new_page_count, gen) = self.write_record(&bytes)?;
607
608 let dir_entry = CacheDirectoryEntry {
609 namespace: entry.namespace.clone(),
610 key_hash: entry.key_hash,
611 start_page: new_start_page,
612 page_count: new_page_count,
613 len: bytes.len() as u32,
614 deleted: false,
615 accessed_at: dir_accessed_at,
616 access_count: dir_access_count,
617 size_bytes: entry.size_bytes,
618 ttl_secs: entry.ttl_secs,
619 created_at: entry.created_at,
620 vector: entry.vector.clone(),
621 model: entry.model.clone(),
622 gen,
623 };
624 let new_pos = self.cache_dir.len();
625 self.cache_idx
626 .insert(&entry.namespace, entry.key_hash, new_pos);
627 self.cache_dir.push(dir_entry);
628 self.dirty_cache = true;
629 Ok(())
630 }
631}
632
633/// SEC-2 (RB-001.30): overwrite every occurrence of `needle` in the file
634/// with zeros, then sync. Rekey uses it for stale copies of the old header's
635/// key wrap: they're plaintext (page 0 is sealed, not encrypted) and can sit
636/// in WAL regions that were grown, relocated or freed. Every other page is
637/// AES-GCM ciphertext, where a 76-byte random match doesn't happen.
638pub(super) fn scrub_bytes(file: &mut std::fs::File, needle: &[u8]) -> Result<usize> {
639 if needle.is_empty() {
640 return Ok(0);
641 }
642 let len = file.seek(SeekFrom::End(0))?;
643 let chunk = 1 << 20;
644 let overlap = needle.len() - 1;
645 let mut hits: Vec<u64> = Vec::new();
646 let mut buf = vec![0u8; chunk + overlap];
647 let mut pos: u64 = 0;
648 while pos < len {
649 let want = (chunk as u64 + overlap as u64).min(len - pos) as usize;
650 file.seek(SeekFrom::Start(pos))?;
651 file.read_exact(&mut buf[..want])?;
652 let mut i = 0;
653 while i + needle.len() <= want {
654 if buf[i..i + needle.len()] == *needle {
655 hits.push(pos + i as u64);
656 i += needle.len();
657 } else {
658 i += 1;
659 }
660 }
661 pos += chunk as u64;
662 }
663 hits.dedup();
664 let zeros = vec![0u8; needle.len()];
665 for off in &hits {
666 file.seek(SeekFrom::Start(*off))?;
667 file.write_all(&zeros)?;
668 }
669 if !hits.is_empty() {
670 file.sync_all()?;
671 crate::bump_fsync();
672 }
673 Ok(hits.len())
674}