mnemo-engine 0.15.0

Encrypted, single-file, portable agent memory engine with multi-signal recall, sessions, snapshots, and an IVF+PQ index
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
//! Loading the control plane: file locking, sealed-run readers, the catalog and index delta chains, the snapshot manifest, cache directory, ANN index, free list and key slots, and the v4 catalog migration.

use super::*;

/// Open a file and take an OS advisory lock, returning `Locked { path }`
/// if the requested lock cannot be acquired. On drop of the returned
/// [`File`], the OS releases the lock. `flock`/`LockFileEx` semantics
/// (per file-descriptor on Unix, per-open-file-handle on Windows) mean
/// the lock is scoped to this handle: cloning the file (or the returned
/// `File`) shares the lock, but a fresh `open()` from any process gets a
/// distinct handle and will collide.
///
/// The file comes back as a [`LockedFile`], which unlocks explicitly on
/// drop, so a failed open (a wrong key, say) releases the lock as promptly
/// as a closed handle does.
///
/// v0.14.0 step 1 (12.4's design note, "Gaps in today's code"):
/// - **Truncation waits for the lock.** `create` used to open with
///   `O_TRUNC`, which empties the file before the lock is even tried, so a
///   refused `create` over a file another handle had open destroyed it. Now
///   the file is truncated only once the exclusive lock is held.
/// - **The lock must be on the file the path names.** Between the open and
///   the lock, another process can rename a new file over the path (a
///   compaction does, holding the old file's lock until it has). The lock
///   then lands on the replaced file, and every write to it is lost. So
///   after locking, the open file is compared with the one at the path,
///   and on a mismatch the open is retried on the new file.
///
/// `Create::New` refuses any existing name, a symlink included (`O_EXCL`;
/// `CREATE_NEW` on Windows), with `ErrorKind::AlreadyExists`. Temp files use
/// it, so nothing already at a temp name is ever written through.
pub(super) fn open_with_lock(path: &Path, write: bool, create: Create) -> Result<LockedFile> {
    const ATTEMPTS: usize = 8;
    for _ in 0..ATTEMPTS {
        let file = open_and_lock_once(path, write, create)?;
        if is_file_at(&file, path)? {
            if create == Create::Truncate {
                file.set_len(0)?;
            }
            return Ok(file);
        }
        if create == Create::New {
            // We made this name ourselves, so it can't have been replaced by
            // a compaction; something else is moving files here.
            return Err(MnemoError::Replaced {
                path: path.to_path_buf(),
                shared: false,
                missing: false,
            });
        }
        // Replaced between our open and our lock: unlock (on drop) and open
        // whatever the path names now.
    }
    Err(MnemoError::Replaced {
        path: path.to_path_buf(),
        shared: false,
        missing: false,
    })
}

/// 12.4: take `path`'s exclusive lock through the lock layer for a long
/// operation `op` (the intent lock, `opts.deadline`, a `lock-info` note).
/// The sidecar directory is used only if a shared handle has made it, so a
/// brain nobody opens in shared mode gains no sibling; without it the wait
/// still has the deadline and the backoff, but no intent lock or note.
/// The returned [`crate::shared::Held`] removes the note when dropped; drop
/// it before the file. Where shared mode isn't available (`Unsupported`:
/// a network or synced filesystem, an old Windows build), one plain try,
/// as before, and no note.
pub(super) fn lock_exclusive(
    path: &Path,
    op: &str,
    opts: &crate::SharedOptions,
) -> Result<(LockedFile, Option<crate::shared::Held>)> {
    use crate::shared::{BrainLocks, Call, LockKind};
    let mut locks = match BrainLocks::for_plain(path, opts) {
        Ok(l) => l,
        Err(MnemoError::Unsupported(_)) => {
            return Ok((open_with_lock(path, true, Create::No)?, None));
        }
        Err(e) => return Err(e),
    };
    let mut call = Call::new(opts.deadline, opts.cancel.as_ref());
    let mut held = locks.acquire(LockKind::Exclusive, &mut call)?;
    held.announce(op);
    let file = held.take_file();
    Ok((file, Some(held)))
}

/// 12.4: take `path`'s shared lock through the lock layer for a read-only
/// open: it waits up to `opts.deadline` for a writer to finish, and runs
/// alongside other readers (a reader holds the intent lock for one try
/// only). As [`lock_exclusive`], the sidecar is used only if a shared
/// handle has made it, and where shared mode isn't available, one plain
/// try.
pub(super) fn lock_shared(path: &Path, opts: &crate::SharedOptions) -> Result<LockedFile> {
    use crate::shared::{BrainLocks, Call, LockKind};
    let mut locks = match BrainLocks::for_plain(path, opts) {
        Ok(l) => l,
        Err(MnemoError::Unsupported(_)) => return open_with_lock(path, false, Create::No),
        Err(e) => return Err(e),
    };
    let mut call = Call::new(opts.deadline, opts.cancel.as_ref());
    let mut held = locks.acquire(LockKind::Shared, &mut call)?;
    Ok(held.take_file())
}

/// `path` made absolute against the current directory, without resolving
/// symlinks (a later check re-resolves them, so it follows the path as it
/// is then). If the current directory can't be read, the path is kept as
/// given. (`std::path::absolute` needs Rust 1.79; the MSRV is 1.75.)
pub(super) fn absolute(path: PathBuf) -> PathBuf {
    if path.is_absolute() {
        return path;
    }
    match std::env::current_dir() {
        Ok(dir) => dir.join(path),
        Err(_) => path,
    }
}

impl Mnemo {
    /// v0.14.0 step 1: refuse to write when the file at this handle's path
    /// is no longer the one it has open (something renamed another file
    /// over it, or the file was moved or removed), since every write would
    /// go to a file nobody finds at the path. Called before each commit
    /// (`flush`, `rekey`); costs an `fstat` of the open file and a `stat`
    /// of the path.
    ///
    /// RB-008.2: when the check itself fails (permission to the path lost,
    /// the descriptor limit on Windows), a plain handle commits as v0.13.2
    /// did. It holds the lock for its whole life, so nothing it can't see
    /// can compact over it. A shared handle returns the error.
    pub(super) fn ensure_not_replaced(&self) -> Result<()> {
        let at = match file_at(self.pager.file(), &self.path) {
            Ok(at) => at,
            Err(_) if !self.shared => return Ok(()),
            Err(e) => return Err(e),
        };
        match at {
            AtPath::Same => Ok(()),
            AtPath::Other | AtPath::Nothing => Err(MnemoError::Replaced {
                path: self.path.clone(),
                shared: false,
                missing: at == AtPath::Nothing,
            }),
        }
    }
}

/// What a path names, against a file a handle has open.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum AtPath {
    /// The open file.
    Same,
    /// Another file (one was renamed over the path).
    Other,
    /// Nothing: the file was moved or removed.
    Nothing,
}

/// Does `path` still name the file `file` has open? `false` when the path
/// names another file, or none (it was removed or renamed away).
pub(crate) fn is_file_at(file: &File, path: &Path) -> Result<bool> {
    Ok(file_at(file, path)? == AtPath::Same)
}

/// What `path` names, against the file `file` has open. On Unix, the
/// device and inode of an `fstat` of the open descriptor against a `stat`
/// of the path (RB-008.2: no new descriptor). Elsewhere, `same_file`.
pub(crate) fn file_at(file: &File, path: &Path) -> Result<AtPath> {
    #[cfg(any(test, feature = "failpoints"))]
    if crate::__failpoints::take_path_check_failure() {
        return Err(MnemoError::Io(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "path check failed (failpoint)",
        )));
    }
    let at_path = match path_identity(path) {
        Ok(id) => id,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(AtPath::Nothing),
        Err(e) => return Err(MnemoError::Io(e)),
    };
    if file_identity(file)? == at_path {
        Ok(AtPath::Same)
    } else {
        Ok(AtPath::Other)
    }
}

#[cfg(unix)]
fn file_identity(file: &File) -> std::io::Result<(u64, u64)> {
    use std::os::unix::fs::MetadataExt;
    let m = file.metadata()?;
    Ok((m.dev(), m.ino()))
}

#[cfg(unix)]
fn path_identity(path: &Path) -> std::io::Result<(u64, u64)> {
    use std::os::unix::fs::MetadataExt;
    let m = std::fs::metadata(path)?;
    Ok((m.dev(), m.ino()))
}

#[cfg(not(unix))]
fn file_identity(file: &File) -> std::io::Result<same_file::Handle> {
    same_file::Handle::from_file(file.try_clone()?)
}

#[cfg(not(unix))]
fn path_identity(path: &Path) -> std::io::Result<same_file::Handle> {
    same_file::Handle::from_path(path)
}

/// How [`open_with_lock`] treats a missing or existing file.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Create {
    /// Open an existing file only.
    No,
    /// Create it, or empty an existing one once the lock is held.
    Truncate,
    /// Create a new file; any existing name, a symlink included, is
    /// `AlreadyExists`.
    New,
}

fn open_and_lock_once(path: &Path, write: bool, create: Create) -> Result<LockedFile> {
    let mut opts = OpenOptions::new();
    opts.read(true);
    if write {
        opts.write(true);
    }
    match create {
        Create::No => {}
        // No `truncate(true)`: see `open_with_lock`.
        Create::Truncate => {
            opts.create(true);
        }
        Create::New => {
            opts.create_new(true);
        }
    }
    owner_only(&mut opts);
    let file = opts.open(path)?;
    // On success the returned `Result<()>` is `Ok(())`. On conflict:
    //   * Unix `flock(2)` → `ErrorKind::WouldBlock` (EWOULDBLOCK / EAGAIN)
    //   * Windows `LockFileEx` → raw OS code 33 (ERROR_LOCK_VIOLATION)
    //     or 32 (ERROR_SHARING_VIOLATION), both surfaced by Rust as
    //     `ErrorKind::Uncategorized` because `std::io::ErrorKind`
    //     doesn't carry a portable "locked" variant.
    // Anything else is a real I/O failure (permissions, invalid handle,
    // ...) and gets bubbled up as `MnemoError::Io`.
    let result = if write {
        FileExt::try_lock_exclusive(&file)
    } else {
        FileExt::try_lock_shared(&file)
    };
    match result {
        Ok(()) => Ok(LockedFile::new(file)),
        Err(e) if is_lock_conflict(&e) => Err(MnemoError::Locked {
            path: path.to_path_buf(),
            holder: None,
        }),
        Err(e) => Err(MnemoError::Io(e)),
    }
}

/// A file this opens and creates gets mode 0600 on Unix (owner read and
/// write, whatever the umask allows of that): a brain, a compaction's or an
/// export's new file. The mode applies only when the file is created, so an
/// existing file's mode is never changed. Elsewhere, a no-op.
pub(super) fn owner_only(opts: &mut OpenOptions) -> &mut OpenOptions {
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    opts
}

/// Give `to` the permissions `from` has (Unix): a compaction's new file
/// keeps the brain's mode, so one made group-readable on purpose stays so.
/// Elsewhere, a no-op.
pub(super) fn copy_mode(from: &File, to: &File) -> Result<()> {
    #[cfg(unix)]
    to.set_permissions(from.metadata()?.permissions())?;
    #[cfg(not(unix))]
    let _ = (from, to);
    Ok(())
}

/// Do two paths resolve to the same on-disk file? Used by
/// [`Mnemo::export_encrypted`] to refuse overwriting the live
/// database. On Unix we compare `(dev, ino)` via `MetadataExt`, which
/// catches hard links and symlinks. On Windows we compare canonicalized
/// paths, since there is no stable device+inode equivalent in `std`.
/// Returns `None` if either side can't be stat'd / canonicalized —
/// the caller treats that as "not the same file" so a missing `dest`
/// (the normal export case) proceeds.
pub(super) fn paths_refer_to_same_file(a: &Path, b: &Path) -> Option<bool> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        let ma = std::fs::metadata(a).ok()?;
        let mb = std::fs::metadata(b).ok()?;
        Some(ma.dev() == mb.dev() && ma.ino() == mb.ino())
    }
    #[cfg(not(unix))]
    {
        let ca = std::fs::canonicalize(a).ok()?;
        let cb = std::fs::canonicalize(b).ok()?;
        Some(ca == cb)
    }
}

/// A sibling temp-file path next to `dest`, suffixed with
/// `.export-tmp`. Lives in `dest`'s own parent directory so the final
/// [`std::fs::rename`] is same-filesystem (and therefore atomic on
/// every platform mnemo supports).
/// A temp file name next to `dest`, unique to this call: `<dest>.<what>-<pid>-<n>.tmp`.
/// Two exports or compactions of one file, in one process or two, never
/// share a temp file (v0.14.0 step 1; the fixed `.compact-tmp` name let a
/// second compaction truncate the first one's copy mid-write). A crash can
/// leave one behind; it's safe to delete when no compaction is running.
pub(super) fn temp_sibling(dest: &Path, what: &str) -> PathBuf {
    #[cfg(any(test, feature = "failpoints"))]
    if let Some(planted) = crate::__failpoints::take_next_temp_name() {
        return planted;
    }
    use std::sync::atomic::{AtomicU64, Ordering};
    static NEXT: AtomicU64 = AtomicU64::new(0);
    let n = NEXT.fetch_add(1, Ordering::Relaxed);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos())
        .unwrap_or(0);
    let mut buf = dest.as_os_str().to_os_string();
    buf.push(format!(
        ".{what}-{}-{n}-{nanos:08x}.tmp",
        std::process::id()
    ));
    PathBuf::from(buf)
}

/// How many fresh names a temp file gets before a run of collisions
/// (`AlreadyExists`) is reported as the error.
pub(super) const TEMP_NAME_ATTEMPTS: usize = 16;

/// Was `e` the `AlreadyExists` a `Create::New` open returns for a taken name?
pub(super) fn is_name_taken(e: &MnemoError) -> bool {
    matches!(e, MnemoError::Io(io) if io.kind() == std::io::ErrorKind::AlreadyExists)
}

/// Was this I/O error the OS reporting a conflicting file lock, or a
/// genuine I/O failure? Platform-conditional because
/// [`std::io::ErrorKind`] carries no portable "resource-locked" variant
/// as of Rust 1.75 — Windows surfaces `ERROR_LOCK_VIOLATION` /
/// `ERROR_SHARING_VIOLATION` as `Uncategorized`.
pub(crate) fn is_lock_conflict(e: &std::io::Error) -> bool {
    if e.kind() == std::io::ErrorKind::WouldBlock {
        return true;
    }
    #[cfg(windows)]
    if let Some(code) = e.raw_os_error() {
        // 33 = ERROR_LOCK_VIOLATION, 32 = ERROR_SHARING_VIOLATION —
        // both mean "someone else holds an incompatible lock on this
        // region of the file". See
        // https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
        if code == 33 || code == 32 {
            return true;
        }
    }
    false
}

/// Read a run of consecutive encrypted pages and concatenate their plaintext.
/// `gen` is the generation the run's pointer expects (v9; `0` before).
pub(super) fn read_run_bytes(
    pager: &mut Pager,
    start: u64,
    pages: u64,
    len: u64,
    gen: u64,
) -> Result<Vec<u8>> {
    let mut buf = Vec::with_capacity(len as usize);
    for i in 0..pages {
        buf.extend_from_slice(&pager.read_page(start + i, gen)?);
    }
    buf.truncate(len as usize);
    Ok(buf)
}

/// FMT-9b: a page run read as a byte stream, one page at a time and
/// without caching it, so loading a large run (a 100K catalog is several
/// MB, its index about 17 MB) never holds the whole serialized run in
/// memory next to the structure being decoded from it.
pub(super) struct RunReader<'a> {
    pub(super) pager: &'a mut Pager,
    /// The first page error, kept so the caller reports it as itself
    /// (e.g. `PageAuthFailed`) rather than as a decode error.
    pub(super) err: &'a std::cell::RefCell<Option<MnemoError>>,
    pub(super) next_page: u64,
    pub(super) end_page: u64,
    pub(super) gen: u64,
    pub(super) remaining: u64,
    pub(super) buf: Vec<u8>,
    pub(super) pos: usize,
}

impl<'a> RunReader<'a> {
    pub(super) fn new(
        pager: &'a mut Pager,
        err: &'a std::cell::RefCell<Option<MnemoError>>,
        start: u64,
        pages: u64,
        len: u64,
        gen: u64,
    ) -> Self {
        RunReader {
            pager,
            err,
            next_page: start,
            end_page: start + pages,
            gen,
            remaining: len,
            buf: Vec::new(),
            pos: 0,
        }
    }
}

impl Read for RunReader<'_> {
    /// The decoder reads a byte or a few at a time; serve those straight
    /// from the current page.
    #[inline]
    fn read_exact(&mut self, out: &mut [u8]) -> std::io::Result<()> {
        if self.buf.len() - self.pos >= out.len() {
            out.copy_from_slice(&self.buf[self.pos..self.pos + out.len()]);
            self.pos += out.len();
            return Ok(());
        }
        let mut done = 0;
        while done < out.len() {
            match self.read(&mut out[done..])? {
                0 => return Err(std::io::ErrorKind::UnexpectedEof.into()),
                n => done += n,
            }
        }
        Ok(())
    }

    #[inline]
    fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
        if self.pos == self.buf.len() {
            if self.remaining == 0 || self.next_page >= self.end_page {
                return Ok(0);
            }
            let mut page = match self.pager.read_page_uncached(self.next_page, self.gen) {
                Ok(p) => p,
                Err(e) => {
                    let msg = e.to_string();
                    *self.err.borrow_mut() = Some(e);
                    return Err(std::io::Error::other(msg));
                }
            };
            self.next_page += 1;
            page.truncate((self.remaining as usize).min(page.len()));
            self.remaining -= page.len() as u64;
            self.buf = page;
            self.pos = 0;
        }
        let n = out.len().min(self.buf.len() - self.pos);
        out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
        self.pos += n;
        Ok(n)
    }
}

/// FMT-9b: deserialize a sequence into a `Vec` sized from the encoded
/// length up front (bounded by `cap`, so a hostile length can't force a
/// huge allocation). serde's own `Vec` impl pre-sizes only up to 1 MiB and
/// then doubles, which for a 100K catalog leaves a quarter of the capacity
/// unused and a freed half-size copy behind in the allocator.
pub(super) struct ExactVec<T> {
    pub(super) cap: usize,
    pub(super) _t: std::marker::PhantomData<T>,
}

impl<'de, T: Deserialize<'de>> serde::de::DeserializeSeed<'de> for ExactVec<T> {
    type Value = Vec<T>;
    fn deserialize<D: serde::Deserializer<'de>>(
        self,
        d: D,
    ) -> std::result::Result<Vec<T>, D::Error> {
        d.deserialize_seq(self)
    }
}

impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for ExactVec<T> {
    type Value = Vec<T>;
    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str("a sequence")
    }
    fn visit_seq<A: serde::de::SeqAccess<'de>>(
        self,
        mut seq: A,
    ) -> std::result::Result<Vec<T>, A::Error> {
        let mut v = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(self.cap));
        while let Some(x) = seq.next_element()? {
            v.push(x);
        }
        Ok(v)
    }
}

/// Load a v5+ catalog run (an empty `pages` yields an empty catalog).
pub(super) fn load_catalog(
    pager: &mut Pager,
    start: u64,
    pages: u64,
    len: u64,
    gen: u64,
) -> Result<Vec<CatalogEntry>> {
    if pages == 0 {
        return Ok(Vec::new());
    }
    // Sized exactly (every row encodes to at least 8 bytes, which bounds
    // the up-front allocation by the run's length). v8 decodes from one
    // buffer, as before; v9 streams the run (it's larger, and it's paired
    // with a resident vector column, so the transient buffer costs RSS).
    let cap = (len / 8) as usize;
    if pager.version() < VERSION_V9 {
        let buf = read_run_bytes(pager, start, pages, len, gen)?;
        let mut de = rmp_serde::Deserializer::from_read_ref(&buf);
        return serde::de::DeserializeSeed::deserialize(
            ExactVec::<CatalogEntry> {
                cap,
                _t: std::marker::PhantomData,
            },
            &mut de,
        )
        .map_err(|e| MnemoError::Serialize(e.to_string()));
    }
    let err = std::cell::RefCell::new(None);
    let mut de = rmp_serde::Deserializer::new(RunReader::new(pager, &err, start, pages, len, gen));
    let res = serde::de::DeserializeSeed::deserialize(
        ExactVec::<CatalogEntry> {
            cap,
            _t: std::marker::PhantomData,
        },
        &mut de,
    );
    drop(de);
    match (res, err.into_inner()) {
        (Ok(v), _) => Ok(v),
        (Err(_), Some(page_err)) => Err(page_err),
        (Err(e), None) => Err(MnemoError::Serialize(e.to_string())),
    }
}

/// FMT-9c.2: one delta run of a v9 catalog: the rows a commit changed or
/// added, by position, and the previous delta in the chain.
#[derive(Serialize, Deserialize)]
pub(super) struct CatalogDelta {
    pub(super) prev: (u64, u64, u64, u64),
    pub(super) rows: Vec<(u32, CatalogEntry)>,
}

pub(super) fn ptr_tuple(p: RunPtr) -> (u64, u64, u64, u64) {
    (p.start, p.pages, p.len, p.gen)
}

pub(super) fn tuple_ptr(t: (u64, u64, u64, u64)) -> RunPtr {
    RunPtr {
        start: t.0,
        pages: t.1,
        len: t.2,
        gen: t.3,
    }
}

/// FMT-9c.2: walk the delta chain from `head` back to the base and replay
/// it onto `catalog`, oldest first. Returns the catalog, the chain (oldest
/// first) and its total row count. An empty `head` is a no-op (and v8).
pub(super) fn apply_delta_chain(
    pager: &mut Pager,
    mut catalog: Vec<CatalogEntry>,
    head: RunPtr,
) -> Result<(Vec<CatalogEntry>, Vec<RunPtr>, usize)> {
    let mut deltas: Vec<(RunPtr, Vec<(u32, CatalogEntry)>)> = Vec::new();
    let mut at = head;
    while !at.is_empty() {
        if deltas.len() > 4096 {
            return Err(MnemoError::Invalid("catalog delta chain too long".into()));
        }
        let buf = read_run_bytes(pager, at.start, at.pages, at.len, at.gen)?;
        let d: CatalogDelta =
            rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))?;
        deltas.push((at, d.rows));
        at = tuple_ptr(d.prev);
    }
    deltas.reverse();
    let mut rows = 0usize;
    let mut chain = Vec::with_capacity(deltas.len());
    for (ptr, d) in deltas {
        rows += d.len();
        chain.push(ptr);
        for (i, row) in d {
            let i = i as usize;
            match i.cmp(&catalog.len()) {
                std::cmp::Ordering::Less => catalog[i] = row,
                std::cmp::Ordering::Equal => catalog.push(row),
                std::cmp::Ordering::Greater => {
                    return Err(MnemoError::Invalid("catalog delta skips a row".into()))
                }
            }
        }
    }
    Ok((catalog, chain, rows))
}

/// FMT-9c.3: one delta run of a v9 ANN index: the changes a commit made,
/// and the previous delta in the chain.
#[derive(Serialize)]
pub(super) struct IndexDeltaRef<'a> {
    pub(super) prev: (u64, u64, u64, u64),
    pub(super) ops: &'a [IndexOp],
}

#[derive(Deserialize)]
pub(super) struct IndexDeltaOwned {
    pub(super) prev: (u64, u64, u64, u64),
    pub(super) ops: Vec<IndexOp>,
}

/// FMT-9c.3: walk the index delta chain from `head` and replay it onto a
/// just-loaded base index, oldest first. Returns the chain and its change
/// count.
pub(super) fn apply_index_chain(
    pager: &mut Pager,
    ann: &mut IvfPqIndex,
    head: RunPtr,
) -> Result<(Vec<RunPtr>, usize)> {
    let mut deltas: Vec<(RunPtr, Vec<IndexOp>)> = Vec::new();
    let mut at = head;
    while !at.is_empty() {
        if deltas.len() > 4096 {
            return Err(MnemoError::Invalid("index delta chain too long".into()));
        }
        let buf = read_run_bytes(pager, at.start, at.pages, at.len, at.gen)?;
        let d: IndexDeltaOwned =
            rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))?;
        deltas.push((at, d.ops));
        at = tuple_ptr(d.prev);
    }
    deltas.reverse();
    let mut chain = Vec::with_capacity(deltas.len());
    let mut n = 0usize;
    for (ptr, ops) in deltas {
        n += ops.len();
        chain.push(ptr);
        ann.apply_ops(ops)?;
    }
    Ok((chain, n))
}

/// FMT-9f: the runs of an index delta chain whose base didn't load (a
/// layout this build doesn't know), oldest first, without replaying them,
/// so the next `build_index` or `drop_index` frees them with the base.
/// Best effort: a delta this build can't decode ends the walk, and the
/// runs before it stay unreferenced until the next compaction.
pub(super) fn index_chain_runs(pager: &mut Pager, head: RunPtr) -> Vec<RunPtr> {
    let mut runs = Vec::new();
    let mut at = head;
    while !at.is_empty() && runs.len() <= 4096 {
        let Ok(buf) = read_run_bytes(pager, at.start, at.pages, at.len, at.gen) else {
            break;
        };
        let Ok(d) = rmp_serde::from_slice::<IndexDeltaOwned>(&buf) else {
            break;
        };
        runs.push(at);
        at = tuple_ptr(d.prev);
    }
    runs.reverse();
    runs
}

/// Load a **v4** catalog run using the frozen [`CatalogEntryV4`] shape.
/// Used only by the v4→v5 migration path in [`Mnemo::open`].
pub(super) fn load_catalog_v4(
    pager: &mut Pager,
    start: u64,
    pages: u64,
    len: u64,
) -> Result<Vec<CatalogEntryV4>> {
    if pages == 0 {
        return Ok(Vec::new());
    }
    let buf = read_run_bytes(pager, start, pages, len, 0)?;
    rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))
}

/// Walk a v4 catalog and synthesize the v5 shape. For each live entry,
/// reads the memory's serialized body and copies its `accessed_at` and
/// `access_count` into the catalog row (the v4 record body still carries
/// them — they're moving *from* the body *to* the catalog). Deleted
/// entries skip the read and zero the fields.
pub(super) fn migrate_v4_catalog(
    pager: &mut Pager,
    v4: Vec<CatalogEntryV4>,
) -> Result<Vec<CatalogEntry>> {
    let mut out = Vec::with_capacity(v4.len());
    for e in &v4 {
        let (accessed_at, access_count) = if e.deleted {
            (0i64, 0u32)
        } else {
            let mut buf = Vec::with_capacity(e.len as usize);
            for i in 0..e.page_count as u64 {
                buf.extend_from_slice(&pager.read_page(e.start_page + i, 0)?);
            }
            buf.truncate(e.len as usize);
            let mem: Memory = rmp_serde::from_slice(&buf)
                .map_err(|err| MnemoError::Serialize(err.to_string()))?;
            (mem.accessed_at, mem.access_count)
        };
        out.push(CatalogEntry {
            id: e.id,
            start_page: e.start_page,
            page_count: e.page_count,
            len: e.len,
            deleted: e.deleted,
            accessed_at,
            access_count,
            gen: 0,
            v9: None,
        });
    }
    Ok(out)
}

/// Load the snapshot manifest (an empty `pages` yields an empty manifest).
pub(super) fn load_manifest(
    pager: &mut Pager,
    start: u64,
    pages: u64,
    len: u64,
    gen: u64,
) -> Result<Vec<Snapshot>> {
    if pages == 0 {
        return Ok(Vec::new());
    }
    let buf = read_run_bytes(pager, start, pages, len, gen)?;
    rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))
}

/// Load the result-cache directory (v8+). An empty `pages` yields an
/// empty directory, which is the natural state for v7 files migrated
/// to v8 (no cache entries yet) and for freshly created v8 files.
pub(super) fn load_cache_directory(
    pager: &mut Pager,
    start: u64,
    pages: u64,
    len: u64,
    gen: u64,
) -> Result<Vec<CacheDirectoryEntry>> {
    if pages == 0 {
        return Ok(Vec::new());
    }
    let buf = read_run_bytes(pager, start, pages, len, gen)?;
    rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))
}

/// Load an ANN index run, validating its dimensionality.
pub(super) fn load_index(
    pager: &mut Pager,
    start: u64,
    pages: u64,
    len: u64,
    gen: u64,
    dims: usize,
) -> Result<Option<IvfPqIndex>> {
    if pages == 0 {
        return Ok(None);
    }
    // v8 decodes from one buffer, as before. v9 streams the run (a 100K
    // index is ~17 MB), trading decode speed for not holding it twice.
    if pager.version() < VERSION_V9 {
        let buf = read_run_bytes(pager, start, pages, len, gen)?;
        let mut idx: IvfPqIndex =
            rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))?;
        if idx.dims() != dims {
            return Err(MnemoError::Invalid(
                "ANN index dimensionality does not match the database".into(),
            ));
        }
        idx.rebuild_assignment();
        return Ok(Some(idx));
    }
    // v9 index runs start with a layout byte. An index is derived data, so
    // a layout this build doesn't know means "no index" (recall scans
    // exactly; `rebuild_index` writes a current one), never an error.
    let err = std::cell::RefCell::new(None);
    let mut rd = RunReader::new(pager, &err, start, pages, len, gen);
    let mut layout = [0u8; 1];
    if rd.read_exact(&mut layout).is_err() {
        drop(rd);
        return match err.into_inner() {
            Some(page_err) => Err(page_err),
            None => Ok(None),
        };
    }
    if layout[0] != V9_INDEX_LAYOUT {
        return Ok(None);
    }
    let res: std::result::Result<IvfPqIndex, _> = rmp_serde::from_read(rd);
    let mut idx = match (res, err.into_inner()) {
        (Ok(i), _) => i,
        (Err(_), Some(page_err)) => return Err(page_err),
        (Err(e), None) => return Err(MnemoError::Serialize(e.to_string())),
    };
    if idx.dims() != dims {
        return Err(MnemoError::Invalid(
            "ANN index dimensionality does not match the database".into(),
        ));
    }
    idx.rebuild_assignment();
    Ok(Some(idx))
}

/// FMT-9 (a): load the v9 free list (an empty pointer yields an empty list).
pub(super) fn load_free_list(pager: &mut Pager, ptr: RunPtr) -> Result<FreeList> {
    if ptr.is_empty() {
        return Ok(FreeList::default());
    }
    let buf = read_run_bytes(pager, ptr.start, ptr.pages, ptr.len, ptr.gen)?;
    let runs: Vec<crate::freelist::FreeRun> =
        rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))?;
    FreeList::from_runs(runs)
}

/// FMT-9 (b): load the v9 key-slot run (an empty pointer yields no slots).
pub(super) fn load_key_slots(pager: &mut Pager, ptr: RunPtr) -> Result<KeySlotRun> {
    if ptr.is_empty() {
        return Ok(KeySlotRun::default());
    }
    let buf = read_run_bytes(pager, ptr.start, ptr.pages, ptr.len, ptr.gen)?;
    let run: KeySlotRun =
        rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))?;
    run.validate()?;
    Ok(run)
}