mnemo-engine 0.19.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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
//! The pager: encrypted, page-granular I/O over the database file.
//!
//! The pager owns the file handle and the data-encryption-key (DEK). Callers
//! deal in *plaintext payloads*; the pager transparently encrypts on write and
//! decrypts on read. Decrypted pages are kept in a **bounded LRU cache**
//! ([`crate::cache::PageCache`]) so repeated reads skip a decrypt and writes
//! are batched until [`Pager::flush`]. The cache caps retained *clean* pages;
//! dirty (un-flushed) pages are pinned until a flush makes them clean.

use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};

/// Test-only crash injection hooks (Phase 1.3). Compiled in under
/// `cfg(test)` and the `failpoints` feature; otherwise absent — the
/// production build carries no runtime cost. The counter is
/// thread-local so parallel tests do not stomp on each other.
#[cfg(any(test, feature = "failpoints"))]
pub(crate) mod failpoints {
    use std::cell::Cell;

    thread_local! {
        // -1  => disabled (default).
        // N>0 => Nth subsequent `check()` returns Ok, then check
        //        `N+1` fails and disarms.
        // 0   => the *next* `check()` fails, then disarms.
        //
        // `const { ... }` in `thread_local!` was stabilized in Rust
        // 1.59, safely under our 1.75 MSRV floor. Const-init avoids
        // the first-touch branch and satisfies clippy's
        // `missing_const_for_thread_local` on stable.
        static WRITES_UNTIL_FAIL: Cell<i64> = const { Cell::new(-1) };
        // How many writes in a row fail once the counter fires (12.4's
        // MaybeStored test fails the checkpoint and then the recovery).
        static FAILS_LEFT: Cell<u32> = const { Cell::new(1) };
        // REKEY-2 (RB-005.4 item 5): writes counted from the last
        // `set_writes_failing` (or from the thread's start), and the
        // write numbers in that count that fail.
        static WRITES_SEEN: Cell<u64> = const { Cell::new(0) };
        static FAILING: std::cell::RefCell<Vec<u64>> = const { std::cell::RefCell::new(Vec::new()) };
    }

    /// Fail exactly the writes numbered in `ns`, counting from 0 at this
    /// call (each write the pager or the WAL makes is one number). Unlike
    /// [`set_writes_until_fail_n`], the failing writes needn't be
    /// consecutive. An empty set disarms it. Independent of
    /// [`set_writes_until_fail`].
    pub fn set_writes_failing(ns: &[u64]) {
        WRITES_SEEN.with(|c| c.set(0));
        FAILING.with(|f| *f.borrow_mut() = ns.to_vec());
    }

    /// How many writes this thread has made since the last
    /// [`set_writes_failing`].
    pub fn writes_seen() -> u64 {
        WRITES_SEEN.with(|c| c.get())
    }

    /// Arm the pager (and the WAL commit writer) to fail its Nth
    /// subsequent write with a synthetic `io::Error`. `n = 0` fails
    /// on the very next write; `n = -1` disables. One-shot: the
    /// counter disarms itself the moment it fires.
    pub fn set_writes_until_fail(n: i64) {
        WRITES_UNTIL_FAIL.with(|c| c.set(n));
        FAILS_LEFT.with(|c| c.set(1));
    }

    /// Like [`set_writes_until_fail`], but `count` writes in a row fail
    /// once the counter fires, then it disarms.
    pub fn set_writes_until_fail_n(n: i64, count: u32) {
        WRITES_UNTIL_FAIL.with(|c| c.set(n));
        FAILS_LEFT.with(|c| c.set(count.max(1)));
    }

    /// Called by every file-writing code path in the pager and the
    /// WAL commit. Returns `Err` when the counter reaches zero,
    /// simulating a torn write mid-flush.
    pub(crate) fn check() -> std::io::Result<()> {
        let n = WRITES_SEEN.with(|c| {
            let n = c.get();
            c.set(n + 1);
            n
        });
        if FAILING.with(|f| f.borrow().contains(&n)) {
            return Err(std::io::Error::other(
                "injected crash (REKEY-2 failpoint set)",
            ));
        }
        WRITES_UNTIL_FAIL.with(|c| {
            let v = c.get();
            if v == 0 {
                let left = FAILS_LEFT.with(|f| f.get());
                if left > 1 {
                    FAILS_LEFT.with(|f| f.set(left - 1));
                } else {
                    c.set(-1);
                }
                Err(std::io::Error::other(
                    "injected crash (Phase 1.3 failpoint)",
                ))
            } else if v > 0 {
                c.set(v - 1);
                Ok(())
            } else {
                Ok(())
            }
        })
    }
}

/// Zero-cost stub used everywhere the failpoint is compiled out.
/// Kept as an `#[inline(always)] fn` so the call site reads the
/// same in both configurations; the branch is optimized away.
///
/// Also re-exported to sibling modules (`wal`) that need the same
/// hook on their own `write_all` sites — the double-underscore
/// makes it obvious this is not a stable API.
#[cfg(not(any(test, feature = "failpoints")))]
#[inline(always)]
pub(crate) fn __failpoint_check() -> std::io::Result<()> {
    Ok(())
}

#[cfg(any(test, feature = "failpoints"))]
#[inline(always)]
pub(crate) fn __failpoint_check() -> std::io::Result<()> {
    failpoints::check()
}

use zeroize::Zeroizing;

use crate::cache::PageCache;
use crate::crypto::{self, KEY_LEN, NONCE_LEN};
use crate::error::{MnemoError, Result};
use crate::format::{PAGE_SIZE, PAYLOAD};

/// PERF-2 (v0.19.0): below this many pages, [`Pager::read_pages_uncached`]
/// and [`Pager::for_each_page`] decrypt on the calling thread; at or above
/// it, on scoped threads.
pub const PARALLEL_DECRYPT_MIN_PAGES: usize = 64;

/// PERF-2 (v0.19.0): the pages one [`Pager::for_each_page`] thread reads and
/// decrypts per buffer: 15 pages is 120 KiB, under the size at which the
/// macOS allocator starts keeping freed blocks for reuse, so a handle's
/// memory doesn't grow with a large fill.
const STREAM_PAGES: usize = 15;

/// PERF-2 (v0.19.0): the plaintext of a batch of pages
/// ([`Pager::read_pages_uncached`]): the pages read from disk, decrypted in
/// place in one buffer, and the cached ones as they were.
pub(crate) struct PageBatch {
    disk: Vec<u8>,
    slots: Vec<Slot>,
}

enum Slot {
    /// The page's index in the decrypted disk buffer.
    Disk(usize),
    /// A cached (possibly dirty) copy.
    Cached(Vec<u8>),
}

impl PageBatch {
    /// The `i`th requested page's plaintext ([`PAYLOAD`] bytes).
    pub(crate) fn payload(&self, i: usize) -> &[u8] {
        match &self.slots[i] {
            Slot::Disk(j) => {
                let at = j * PAGE_SIZE + NONCE_LEN;
                &self.disk[at..at + PAYLOAD]
            }
            Slot::Cached(v) => v,
        }
    }

    /// How many pages the batch holds.
    pub(crate) fn len(&self) -> usize {
        self.slots.len()
    }

    /// PERF-2: the batch as one buffer of page images, page `i` at `i *
    /// PAGE_SIZE` with its plaintext at `NONCE_LEN..NONCE_LEN + PAYLOAD`:
    /// the decrypted read buffer itself when every page came from disk in
    /// the order asked, a copy laid out the same way otherwise (cached
    /// pages, or pages asked out of order).
    pub(crate) fn into_images(self) -> Vec<u8> {
        let in_place = self
            .slots
            .iter()
            .enumerate()
            .all(|(i, s)| matches!(s, Slot::Disk(j) if *j == i));
        if in_place {
            return self.disk;
        }
        let mut out = vec![0u8; self.slots.len() * PAGE_SIZE];
        for i in 0..self.slots.len() {
            let at = i * PAGE_SIZE + NONCE_LEN;
            out[at..at + PAYLOAD].copy_from_slice(self.payload(i));
        }
        out
    }
}

/// A positioned read of exactly `buf.len()` bytes at `offset`. It doesn't
/// use the file's cursor, which every other read and write here sets
/// itself first.
fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::FileExt;
        file.read_exact_at(buf, offset)
    }
    #[cfg(windows)]
    {
        use std::os::windows::fs::FileExt;
        let mut done = 0;
        while done < buf.len() {
            match file.seek_read(&mut buf[done..], offset + done as u64) {
                Ok(0) => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::UnexpectedEof,
                        "failed to fill whole buffer",
                    ))
                }
                Ok(n) => done += n,
                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }
}

/// The database file with the advisory lock its opener took, released
/// explicitly when this is dropped.
///
/// `flock` locks belong to the open file description, not to one file
/// descriptor. While another thread of the process spawns a child, the
/// child holds a copy of the parent's file table until it `exec`s (the
/// descriptor is close-on-exec, but that only takes effect at the exec).
/// Without the explicit unlock, a handle dropped inside that window left
/// the lock held by the child's copy, and the next open of the file failed
/// with `Locked` (FLAKE-1). Unlocking releases it whatever copies exist.
/// On Windows the unlock is equally harmless: handles aren't inherited.
pub(crate) struct LockedFile(File);

impl LockedFile {
    /// Wraps a file whose lock the caller has just taken.
    pub(crate) fn new(file: File) -> Self {
        Self(file)
    }
}

impl std::ops::Deref for LockedFile {
    type Target = File;
    fn deref(&self) -> &File {
        &self.0
    }
}

impl std::ops::DerefMut for LockedFile {
    fn deref_mut(&mut self) -> &mut File {
        &mut self.0
    }
}

impl Drop for LockedFile {
    fn drop(&mut self) {
        // Nothing to do on failure: closing the file releases the lock once
        // the last copy of the description goes.
        let _ = fs4::fs_std::FileExt::unlock(&self.0);
    }
}

/// Default page-cache capacity, in pages (~8 MiB of decrypted payloads).
/// PERF-1 step 4 lowered it from 8192 (~64 MiB): at 10K and 100K memories
/// that cache was most of an open handle's RSS, for little hit rate on
/// recall's scattered record reads. `Mnemo::set_cache_capacity` raises it.
pub const DEFAULT_CACHE_PAGES: usize = 1024;

/// FMT-9b: the default page cache for a v9 file, 256 pages (~2 MiB). v9
/// recall scores from the catalog rows and the resident vector column and
/// decrypts only the `top_k` hits, so a large cache of record pages buys
/// little; `Mnemo::set_cache_capacity` still raises it.
pub const V9_DEFAULT_CACHE_PAGES: usize = 256;

/// What a shared-mode handle's pager reports if anything reaches the file
/// between calls (it holds none then).
const DETACHED: &str = "the brain's file isn't open outside a shared-mode call";

/// Encrypted page reader/writer with a bounded write-back cache.
pub struct Pager {
    /// The brain's file. A shared-mode handle (12.4) holds it only inside a
    /// call: [`Pager::attach_file`] at the start, [`Pager::detach_file`] at
    /// the end, so no descriptor stays open between calls.
    file: Option<LockedFile>,
    dek: Zeroizing<[u8; KEY_LEN]>,
    /// Monotonic write counter persisted in the header (lease / replay
    /// machinery; see `Mnemo::prepare_for_flush`). **No longer used in
    /// the page nonce** — SEC-1 (v0.5.2) moved page nonces to a
    /// per-session random prefix + per-session counter so copies of a
    /// file can't collide on `(page_no, write_counter)` under the same
    /// DEK. Still bumped per write for the existing lease machinery.
    pub write_counter: u64,
    /// Random 64-bit "fixed field" (NIST SP 800-38D §8.2.1) stamped
    /// into bytes 0..8 of every page nonce this pager produces. Drawn
    /// fresh on every writable open and regenerated on counter wrap —
    /// so cross-session nonce collisions require two independent
    /// sessions to draw the same 64-bit random value (birthday bound
    /// ~2^32). Unused on read-only handles.
    session_random: u64,
    /// Per-session monotonic counter stamped into bytes 8..12 of every
    /// page nonce. Starts at 0, increments once per encrypted page
    /// write via [`Pager::next_nonce`]. If about to overflow `u32::MAX`,
    /// [`Pager::next_nonce`] regenerates `session_random` and resets to 0
    /// so the (random, counter) pair stays unique within the session.
    session_counter: u32,
    /// Format version this pager is currently encrypting *for*. `Pager` is
    /// version-aware because the format-bump in v6 changed page encryption
    /// to bind each page's home `page_no` as AAD on AES-GCM, making
    /// page-swap attacks tamper-evident. The pager picks the right AAD
    /// scheme per version on every encrypt/decrypt. During a v5→v6
    /// migration the pager flips from 5 to 6 mid-flight via
    /// [`Pager::set_version`].
    version: u16,
    /// Bounded LRU cache of decrypted page payloads.
    cache: PageCache,
    /// FMT-9: the generation each dirty page is to be sealed under (v9
    /// binds it into the page AAD). Drained by [`Pager::flush`].
    dirty_gens: std::collections::HashMap<u64, u64>,
}

impl Pager {
    /// Wrap an open file with a pager. `write_counter` comes from the header.
    pub(crate) fn new(
        file: LockedFile,
        dek: Zeroizing<[u8; KEY_LEN]>,
        write_counter: u64,
        version: u16,
    ) -> Self {
        Self {
            file: Some(file),
            dek,
            write_counter,
            // Fresh 64-bit random per Pager construction = per writable
            // open. See SEC-1 doc on `crypto::session_page_nonce`.
            session_random: crypto::random_u64(),
            session_counter: 0,
            version,
            cache: PageCache::new(if version >= crate::format::VERSION_V9 {
                V9_DEFAULT_CACHE_PAGES
            } else {
                DEFAULT_CACHE_PAGES
            }),
            dirty_gens: std::collections::HashMap::new(),
        }
    }

    /// Mint the next page nonce for this session.
    ///
    /// Increments `session_counter` and returns
    /// `session_random || session_counter`. If the counter would overflow
    /// `u32::MAX`, regenerates `session_random` and resets the counter
    /// before incrementing — so no `(session_random, session_counter)`
    /// pair ever repeats within this session.
    fn next_nonce(&mut self) -> [u8; NONCE_LEN] {
        if self.session_counter == u32::MAX {
            // Wrap guard: pick a new 64-bit prefix and reset the counter
            // so the next write uses `(fresh_random, 1)` instead of
            // reusing `(old_random, 0)`.
            self.session_random = crypto::random_u64();
            self.session_counter = 0;
        }
        self.session_counter += 1;
        crypto::session_page_nonce(self.session_random, self.session_counter)
    }

    /// Switch the pager to a new format version. Used by [`crate::Mnemo::open`]
    /// during a migration that needs to read with the old version's AAD
    /// scheme and write with the new one.
    pub(crate) fn set_version(&mut self, version: u16) {
        self.version = version;
    }

    /// AAD bound to an encrypted page under this pager's version. Returns a
    /// fresh `Vec` each call to keep the `Aead::Payload` lifetime simple at
    /// every call site. Empty for v4/v5 (matching the historical scheme
    /// without page binding); `page_no.to_le_bytes()` from v6 onwards.
    ///
    /// **v9 (FMT-9 (a)):** `page_no || generation`, where the generation is
    /// the transaction id that wrote the page. Pages are reused in v9, so a
    /// page number alone no longer pins a ciphertext: an attacker holding
    /// an older copy of the file could put back the page's previous
    /// ciphertext, whose tag is valid for the same `page_no`. Every pointer
    /// to a page (header run pointers, catalog rows, cache-directory
    /// entries, snapshots) records the generation it expects, and a read
    /// under any other generation fails authentication.
    #[inline]
    fn page_aad(&self, page_no: u64, gen: u64) -> Vec<u8> {
        if self.version >= crate::format::VERSION_V9 {
            let mut aad = Vec::with_capacity(16);
            aad.extend_from_slice(&page_no.to_le_bytes());
            aad.extend_from_slice(&gen.to_le_bytes());
            aad
        } else if self.version >= 6 {
            page_no.to_le_bytes().to_vec()
        } else {
            Vec::new()
        }
    }

    /// The format version the pager encrypts for.
    pub(crate) fn version(&self) -> u16 {
        self.version
    }

    /// Borrow the data-encryption-key (used by `rekey`, which re-wraps it).
    pub fn dek(&self) -> &[u8; KEY_LEN] {
        &self.dek
    }

    /// The underlying file (its identity is checked before each commit).
    ///
    /// Panics outside a shared-mode call, where the pager holds no file:
    /// nothing reaches the file there.
    pub fn file(&self) -> &File {
        self.file.as_deref().expect(DETACHED)
    }

    /// Mutable access to the underlying file. Used by the WAL, which writes
    /// its log frames directly rather than through the page cache. Panics
    /// like [`Pager::file`].
    pub fn file_mut(&mut self) -> &mut File {
        self.file.as_deref_mut().expect(DETACHED)
    }

    /// The file for this pager's own I/O; an error, not a panic, if a
    /// shared-mode handle reaches it between calls.
    fn f(&mut self) -> std::io::Result<&mut File> {
        self.file
            .as_deref_mut()
            .ok_or_else(|| std::io::Error::other(DETACHED))
    }

    /// 12.4: give a shared-mode handle's pager the call's locked file.
    pub(crate) fn attach_file(&mut self, file: LockedFile) {
        self.file = Some(file);
    }

    /// 12.4: take the call's locked file back at the end of the call. The
    /// caller drops it, which unlocks and closes it.
    pub(crate) fn detach_file(&mut self) -> Option<LockedFile> {
        self.file.take()
    }

    /// Resize the page cache, evicting clean pages if it shrank.
    pub fn set_cache_capacity(&mut self, pages: usize) {
        self.cache.set_capacity(pages);
    }

    /// Current page-cache occupancy and configured cap.
    pub fn cache_stats(&self) -> (usize, usize) {
        (self.cache.len(), self.cache.capacity())
    }

    /// Write a raw, *unencrypted* page-sized buffer at `page_no`.
    /// Used only for the header (page 0).
    pub fn write_raw(&mut self, page_no: u64, data: &[u8; PAGE_SIZE]) -> Result<()> {
        __failpoint_check()?;
        self.f()?
            .seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
        self.f()?.write_all(data)?;
        Ok(())
    }

    /// Read a raw, *unencrypted* page-sized buffer from `page_no`.
    ///
    /// Retained as the symmetric counterpart to [`Pager::write_raw`]; the
    /// header page is currently read directly in `Mnemo::open`.
    #[allow(dead_code)]
    pub fn read_raw(&mut self, page_no: u64) -> Result<[u8; PAGE_SIZE]> {
        let mut buf = [0u8; PAGE_SIZE];
        self.f()?
            .seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
        self.f()?.read_exact(&mut buf)?;
        Ok(buf)
    }

    /// Encrypt `payload` into a finished on-disk page image **without writing
    /// it**. Advances the nonce counter and refreshes the page cache (as a
    /// clean entry) so later reads see the new content. Used by the WAL path:
    /// the returned bytes are logged to the WAL and only later copied to
    /// `page_no` by a checkpoint.
    ///
    /// `gen` is the page's generation (v9; ignored before).
    pub fn seal_page(&mut self, page_no: u64, gen: u64, payload: &[u8]) -> Result<[u8; PAGE_SIZE]> {
        if payload.len() > PAYLOAD {
            return Err(MnemoError::Invalid(format!(
                "payload {} exceeds page capacity {}",
                payload.len(),
                PAYLOAD
            )));
        }
        let mut padded = vec![0u8; PAYLOAD];
        padded[..payload.len()].copy_from_slice(payload);

        // Bump the header's lease counter (unchanged — still consumed by
        // `prepare_for_flush`); mint the actual nonce from the per-session
        // random + counter pair (SEC-1).
        self.write_counter += 1;
        let nonce = self.next_nonce();
        let aad = self.page_aad(page_no, gen);
        let ciphertext = crypto::aead_encrypt(&self.dek, &nonce, &padded, &aad)?;

        let mut disk = [0u8; PAGE_SIZE];
        disk[..NONCE_LEN].copy_from_slice(&nonce);
        disk[NONCE_LEN..].copy_from_slice(&ciphertext);

        // The plaintext is now the live content of this page; it is clean
        // because the WAL/checkpoint — not Pager::flush — will write it.
        self.cache.insert(page_no, padded, false);
        Ok(disk)
    }

    /// Write an already-finished page image straight to `page_no`. The bytes
    /// are written verbatim — used to checkpoint WAL frames (encrypted pages,
    /// or the plaintext header) to their home locations.
    pub fn write_sealed(&mut self, page_no: u64, bytes: &[u8; PAGE_SIZE]) -> Result<()> {
        __failpoint_check()?;
        self.f()?
            .seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
        self.f()?.write_all(bytes)?;
        Ok(())
    }

    /// Flush OS buffers to stable storage.
    pub fn sync(&mut self) -> Result<()> {
        self.f()?.sync_all()?;
        crate::bump_fsync();
        Ok(())
    }

    /// Read and decrypt the plaintext payload of an encrypted page. `gen` is
    /// the generation the referencing pointer expects (v9; ignored before).
    pub fn read_page(&mut self, page_no: u64, gen: u64) -> Result<Vec<u8>> {
        if let Some(p) = self.cache.get(page_no) {
            return Ok(p);
        }
        let mut disk = [0u8; PAGE_SIZE];
        self.f()?
            .seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
        self.f()?.read_exact(&mut disk)?;

        let mut nonce = [0u8; NONCE_LEN];
        nonce.copy_from_slice(&disk[0..NONCE_LEN]);
        let ciphertext = &disk[NONCE_LEN..];

        let aad = self.page_aad(page_no, gen);
        let payload = crypto::aead_decrypt(&self.dek, &nonce, ciphertext, &aad)
            .map_err(|_| MnemoError::PageAuthFailed(page_no))?;

        self.cache.insert(page_no, payload.clone(), false);
        Ok(payload)
    }

    /// FMT-9b: [`Pager::read_page`] without caching the result: for bulk
    /// reads (loading the vector column) that would otherwise push every
    /// cached record page out. A cached copy (possibly dirty) still wins.
    pub fn read_page_uncached(&mut self, page_no: u64, gen: u64) -> Result<Vec<u8>> {
        if let Some(p) = self.cache.peek(page_no) {
            return Ok(p.to_vec());
        }
        let mut disk = [0u8; PAGE_SIZE];
        self.f()?
            .seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
        self.f()?.read_exact(&mut disk)?;
        let mut nonce = [0u8; NONCE_LEN];
        nonce.copy_from_slice(&disk[0..NONCE_LEN]);
        let aad = self.page_aad(page_no, gen);
        crypto::aead_decrypt(&self.dek, &nonce, &disk[NONCE_LEN..], &aad)
            .map_err(|_| MnemoError::PageAuthFailed(page_no))
    }

    /// PERF-2 (v0.19.0): [`Pager::read_page_uncached`] for many pages at
    /// once. `pages` is a list of `(page_no, gen)`; [`PageBatch::payload`]
    /// gives each one's plaintext, in the same order. A cached copy
    /// (possibly dirty) still wins. The rest are read with one positioned
    /// read per run of adjacent pages and decrypted in place in that one
    /// buffer: on up to `available_parallelism()` scoped threads when there
    /// are at least [`PARALLEL_DECRYPT_MIN_PAGES`] of them, on this thread
    /// otherwise. The first page (by page number) that fails authentication
    /// is the error, as it would be one page at a time.
    pub(crate) fn read_pages_uncached(&mut self, pages: &[(u64, u64)]) -> Result<PageBatch> {
        let threads = if pages.len() >= PARALLEL_DECRYPT_MIN_PAGES {
            std::thread::available_parallelism().map_or(1, |n| n.get())
        } else {
            1
        };
        // `MNEMO_DEV_DECRYPT_THREADS` caps the threads, so a benchmark can
        // record the single-thread number (a phone without spare cores).
        // Unsupported and compiled only with `dev-hooks` (HOOKS-1).
        #[cfg(feature = "dev-hooks")]
        let threads = std::env::var("MNEMO_DEV_DECRYPT_THREADS")
            .ok()
            .and_then(|v| v.parse::<usize>().ok())
            .map_or(threads, |cap| threads.min(cap.max(1)));
        self.read_pages_with(pages, threads)
    }

    /// PERF-2 (v0.19.0): read and decrypt `pages` (`(page_no, gen)`), calling
    /// `sink(i, plaintext)` once for each, in no particular order (`i` is
    /// the page's position in `pages`). A cached copy (possibly dirty) still
    /// wins. The rest are split among up to `available_parallelism()`
    /// scoped threads, started once for the call when there are at least
    /// [`PARALLEL_DECRYPT_MIN_PAGES`] pages; each reads its share of the
    /// pages (sorted, adjacent ones in one positioned read) [`STREAM_PAGES`]
    /// at a time into a small buffer, decrypts them in place and hands the
    /// buffer to `sink` on this thread through a bounded channel, so memory
    /// stays a few small buffers whatever the number of pages. A page that
    /// fails authentication, or a failing `sink`, stops the call with that
    /// error.
    pub(crate) fn for_each_page(
        &mut self,
        pages: &[(u64, u64)],
        sink: impl FnMut(usize, &[u8]) -> Result<()>,
    ) -> Result<()> {
        self.for_each_page_with(pages, None, sink)
    }

    /// [`Pager::for_each_page`], with `threads` fixing the thread count
    /// (tests; `None` chooses as `for_each_page` does).
    pub(crate) fn for_each_page_with(
        &mut self,
        pages: &[(u64, u64)],
        threads: Option<usize>,
        mut sink: impl FnMut(usize, &[u8]) -> Result<()>,
    ) -> Result<()> {
        let mut todo: Vec<usize> = Vec::with_capacity(pages.len());
        for (i, &(p, _)) in pages.iter().enumerate() {
            match self.cache.peek(p) {
                Some(c) => {
                    let c = c.to_vec();
                    sink(i, &c)?;
                }
                None => todo.push(i),
            }
        }
        if todo.is_empty() {
            return Ok(());
        }
        todo.sort_by_key(|&i| pages[i].0);
        let auto = if todo.len() >= PARALLEL_DECRYPT_MIN_PAGES {
            std::thread::available_parallelism().map_or(1, |n| n.get())
        } else {
            1
        };
        // `MNEMO_DEV_DECRYPT_THREADS`, as for `read_pages_uncached`.
        #[cfg(feature = "dev-hooks")]
        let auto = std::env::var("MNEMO_DEV_DECRYPT_THREADS")
            .ok()
            .and_then(|v| v.parse::<usize>().ok())
            .map_or(auto, |cap| auto.min(cap.max(1)));
        let threads = threads
            .unwrap_or(auto)
            .clamp(1, todo.len().div_ceil(STREAM_PAGES));
        let aads: Vec<Vec<u8>> = todo
            .iter()
            .map(|&i| self.page_aad(pages[i].0, pages[i].1))
            .collect();
        let cipher = crypto::page_cipher(&self.dek);
        let file: &File = self.f()?;
        // Read and decrypt `todo[lo..hi]` (at most STREAM_PAGES) into a new
        // buffer, page after page.
        let read = |lo: usize, hi: usize| -> Result<Vec<u8>> {
            let mut buf = vec![0u8; (hi - lo) * PAGE_SIZE];
            let mut k = lo;
            while k < hi {
                let first = pages[todo[k]].0;
                let mut run = 1;
                while k + run < hi && pages[todo[k + run]].0 == first + run as u64 {
                    run += 1;
                }
                let at = (k - lo) * PAGE_SIZE;
                read_exact_at(
                    file,
                    &mut buf[at..at + run * PAGE_SIZE],
                    first * PAGE_SIZE as u64,
                )?;
                k += run;
            }
            for (n, img) in buf.chunks_exact_mut(PAGE_SIZE).enumerate() {
                let j = lo + n;
                let mut nonce = [0u8; NONCE_LEN];
                nonce.copy_from_slice(&img[..NONCE_LEN]);
                let (body, tag) = img[NONCE_LEN..].split_at_mut(PAYLOAD);
                crypto::aead_decrypt_in_place(&cipher, &nonce, &aads[j], body, tag)
                    .map_err(|_| MnemoError::PageAuthFailed(pages[todo[j]].0))?;
            }
            Ok(buf)
        };
        let mut deliver = |lo: usize, buf: &[u8]| -> Result<()> {
            for (n, img) in buf.chunks_exact(PAGE_SIZE).enumerate() {
                sink(todo[lo + n], &img[NONCE_LEN..NONCE_LEN + PAYLOAD])?;
            }
            Ok(())
        };
        if threads <= 1 {
            let mut lo = 0;
            while lo < todo.len() {
                let hi = (lo + STREAM_PAGES).min(todo.len());
                deliver(lo, &read(lo, hi)?)?;
                lo = hi;
            }
            return Ok(());
        }
        let per = todo.len().div_ceil(threads);
        std::thread::scope(|s| {
            let (tx, rx) = std::sync::mpsc::sync_channel::<Result<(usize, Vec<u8>)>>(2 * threads);
            let read = &read;
            for t in 0..threads {
                let tx = tx.clone();
                let (start, end) = (t * per, ((t + 1) * per).min(todo.len()));
                s.spawn(move || {
                    let mut lo = start;
                    while lo < end {
                        let hi = (lo + STREAM_PAGES).min(end);
                        let msg = read(lo, hi).map(|b| (lo, b));
                        let stop = msg.is_err();
                        if tx.send(msg).is_err() || stop {
                            return;
                        }
                        lo = hi;
                    }
                });
            }
            drop(tx);
            // Dropping `rx` on an error makes every thread's next send fail,
            // so they stop.
            for msg in rx {
                let (lo, buf) = msg?;
                deliver(lo, &buf)?;
            }
            Ok(())
        })
    }

    /// [`Pager::read_pages_uncached`] on at most `threads` threads (1: this
    /// thread only).
    pub(crate) fn read_pages_with(
        &mut self,
        pages: &[(u64, u64)],
        threads: usize,
    ) -> Result<PageBatch> {
        let mut slots: Vec<Slot> = pages
            .iter()
            .map(|&(p, _)| match self.cache.peek(p) {
                Some(c) => Slot::Cached(c.to_vec()),
                None => Slot::Disk(usize::MAX),
            })
            .collect();
        // The pages to read, by position in `pages`, sorted by page number so
        // adjacent pages share one read.
        let mut todo: Vec<usize> = (0..pages.len())
            .filter(|&i| matches!(slots[i], Slot::Disk(_)))
            .collect();
        todo.sort_by_key(|&i| pages[i].0);
        for (j, &i) in todo.iter().enumerate() {
            slots[i] = Slot::Disk(j);
        }
        let mut disk = vec![0u8; todo.len() * PAGE_SIZE];
        let mut k = 0;
        while k < todo.len() {
            let first = pages[todo[k]].0;
            let mut run = 1;
            while k + run < todo.len() && pages[todo[k + run]].0 == first + run as u64 {
                run += 1;
            }
            let buf = &mut disk[k * PAGE_SIZE..(k + run) * PAGE_SIZE];
            read_exact_at(self.f()?, buf, first * PAGE_SIZE as u64)?;
            k += run;
        }
        let cipher = crypto::page_cipher(&self.dek);
        let aads: Vec<Vec<u8>> = todo
            .iter()
            .map(|&i| self.page_aad(pages[i].0, pages[i].1))
            .collect();
        // Decrypt pages `first..` of `chunk` in place; the first failure is
        // that page's index in `todo`.
        let open = |first: usize, chunk: &mut [u8]| -> std::result::Result<(), usize> {
            for (n, img) in chunk.chunks_exact_mut(PAGE_SIZE).enumerate() {
                let j = first + n;
                let mut nonce = [0u8; NONCE_LEN];
                nonce.copy_from_slice(&img[..NONCE_LEN]);
                let (body, tag) = img[NONCE_LEN..].split_at_mut(PAYLOAD);
                crypto::aead_decrypt_in_place(&cipher, &nonce, &aads[j], body, tag)
                    .map_err(|_| j)?;
            }
            Ok(())
        };
        let threads = threads.clamp(1, todo.len().max(1));
        let failed: Option<usize> = if threads <= 1 {
            open(0, &mut disk).err()
        } else {
            let per = todo.len().div_ceil(threads);
            std::thread::scope(|s| {
                let open = &open;
                let parts: Vec<_> = disk
                    .chunks_mut(per * PAGE_SIZE)
                    .enumerate()
                    .map(|(t, chunk)| s.spawn(move || open(t * per, chunk).err()))
                    .collect();
                parts
                    .into_iter()
                    .filter_map(|h| h.join().expect("a decrypt thread panicked"))
                    .min()
            })
        };
        if let Some(j) = failed {
            return Err(MnemoError::PageAuthFailed(pages[todo[j]].0));
        }
        Ok(PageBatch { disk, slots })
    }

    /// Stage a plaintext payload for an encrypted page. The payload is padded
    /// (or rejected if too large) to exactly [`PAYLOAD`] bytes. The page is
    /// cached dirty — pinned against eviction — until [`Pager::flush`].
    ///
    /// [`Pager::flush`] seals it under generation `gen` (v9; ignored before).
    pub fn write_page(&mut self, page_no: u64, gen: u64, payload: &[u8]) -> Result<()> {
        if payload.len() > PAYLOAD {
            return Err(MnemoError::Invalid(format!(
                "payload {} exceeds page capacity {}",
                payload.len(),
                PAYLOAD
            )));
        }
        let mut padded = vec![0u8; PAYLOAD];
        padded[..payload.len()].copy_from_slice(payload);
        self.cache.insert(page_no, padded, true);
        self.dirty_gens.insert(page_no, gen);
        Ok(())
    }

    /// Encrypt and write every dirty page, then fsync.
    ///
    /// Each page gets a fresh nonce from the per-session random prefix +
    /// per-session counter (`Pager::next_nonce` → `crypto::session_page_nonce`
    /// since v0.5.2 / SEC-1). The counter advances per write; the random
    /// prefix is drawn once per writable open and regenerated on counter
    /// wrap, so no nonce ever repeats across writes in this session or
    /// across copies of the file. Once written, pages become clean and
    /// the cache is trimmed back to its cap.
    pub fn flush(&mut self) -> Result<()> {
        let pages = self.cache.dirty_pages();
        if pages.is_empty() {
            return Ok(());
        }
        for page_no in pages {
            let payload = self
                .cache
                .peek(page_no)
                .expect("dirty page must be cached")
                .to_vec();
            self.write_counter += 1;
            let nonce = self.next_nonce();
            let gen = self.dirty_gens.get(&page_no).copied().unwrap_or(0);
            let aad = self.page_aad(page_no, gen);
            let ciphertext = crypto::aead_encrypt(&self.dek, &nonce, &payload, &aad)?;

            let mut disk = Vec::with_capacity(PAGE_SIZE);
            disk.extend_from_slice(&nonce);
            disk.extend_from_slice(&ciphertext);
            debug_assert_eq!(disk.len(), PAGE_SIZE);

            __failpoint_check()?;
            self.f()?
                .seek(SeekFrom::Start(page_no * PAGE_SIZE as u64))?;
            self.f()?.write_all(&disk)?;
        }
        self.f()?.sync_all()?;
        crate::bump_fsync();
        // The pages just written are now clean and so evictable; settle the
        // cache back within its bound.
        self.cache.mark_all_clean();
        self.dirty_gens.clear();
        self.cache.trim();
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const GEN: u64 = 7;

    fn pager(path: &std::path::Path) -> Pager {
        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(path)
            .unwrap();
        Pager::new(
            LockedFile::new(file),
            Zeroizing::new([7u8; KEY_LEN]),
            0,
            crate::format::VERSION_V9,
        )
    }

    /// Pages 1..=n, each holding its own number, sealed under `GEN`.
    fn write_pages(path: &std::path::Path, n: u64) {
        let mut p = pager(path);
        for page in 1..=n {
            let body = page.to_le_bytes();
            let img = p.seal_page(page, GEN, &body).unwrap();
            p.write_sealed(page, &img).unwrap();
        }
        p.sync().unwrap();
    }

    /// PERF-2: a batch read gives what page-at-a-time reads give, in the
    /// order asked, with gaps and on one thread or several; the first page
    /// that fails authentication is the error on both paths; a read past
    /// the end fails; a cached (dirty) copy wins.
    #[test]
    fn batched_reads_match_single_reads() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("p.bin");
        let n = (PARALLEL_DECRYPT_MIN_PAGES as u64) * 2;
        write_pages(&path, n);
        let mut want: Vec<(u64, u64)> = (1..=n).filter(|p| p % 5 != 0).map(|p| (p, GEN)).collect();
        want.reverse();
        want.swap(3, 40);
        let mut single = pager(&path);
        let one: Vec<Vec<u8>> = want
            .iter()
            .map(|&(p, g)| single.read_page_uncached(p, g).unwrap())
            .collect();
        let all = |b: PageBatch| {
            (0..b.len())
                .map(|i| b.payload(i).to_vec())
                .collect::<Vec<_>>()
        };
        for threads in [1, 4] {
            let mut p = pager(&path);
            assert_eq!(
                all(p.read_pages_with(&want, threads).unwrap()),
                one,
                "{threads} threads"
            );
        }
        assert_eq!(all(pager(&path).read_pages_uncached(&want).unwrap()), one);
        for (got, &(page, _)) in one.iter().zip(&want) {
            assert_eq!(&got[..8], &page.to_le_bytes());
        }

        // A damaged page (one the batch asks for): its own number in the
        // error, both paths.
        let bad = 51u64;
        assert!(want.iter().any(|&(p, _)| p == bad));
        {
            use std::io::{Seek, SeekFrom, Write};
            let mut f = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
            f.seek(SeekFrom::Start(bad * PAGE_SIZE as u64 + 100))
                .unwrap();
            f.write_all(&[0xA5]).unwrap();
        }
        for threads in [1, 4] {
            let res = pager(&path).read_pages_with(&want, threads);
            assert!(
                matches!(res, Err(MnemoError::PageAuthFailed(p)) if p == bad),
                "{threads} threads: {:?}",
                res.map(|b| b.len())
            );
        }
        // The wrong generation fails too.
        let res = pager(&path).read_pages_with(&[(1, GEN + 1)], 1);
        assert!(
            matches!(res, Err(MnemoError::PageAuthFailed(1))),
            "{:?}",
            res.map(|b| b.len())
        );
        // Past the end of the file.
        assert!(pager(&path).read_pages_with(&[(n + 5, GEN)], 1).is_err());
        // A dirty cached copy wins over the disk.
        let mut p = pager(&path);
        p.write_page(2, GEN, b"in the cache").unwrap();
        let got = p.read_pages_with(&[(2, GEN), (3, GEN)], 1).unwrap();
        assert_eq!(&got.payload(0)[..12], b"in the cache");
        assert_eq!(&got.payload(1)[..8], &3u64.to_le_bytes());
    }

    /// PERF-2: `for_each_page` hands every page to the sink once, with its
    /// own plaintext, on one thread or several; a damaged page or a failing
    /// sink stops it with that error; a cached (dirty) copy wins.
    #[test]
    fn streamed_reads_reach_the_sink_once_each() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("p.bin");
        let n = (PARALLEL_DECRYPT_MIN_PAGES as u64) * 3;
        write_pages(&path, n);
        let want: Vec<(u64, u64)> = (1..=n)
            .rev()
            .filter(|p| p % 7 != 0)
            .map(|p| (p, GEN))
            .collect();
        for threads in [Some(1), Some(4), None] {
            let mut seen = vec![0u32; want.len()];
            pager(&path)
                .for_each_page_with(&want, threads, |i, bytes| {
                    seen[i] += 1;
                    assert_eq!(&bytes[..8], &want[i].0.to_le_bytes());
                    assert_eq!(bytes.len(), PAYLOAD);
                    Ok(())
                })
                .unwrap();
            assert!(seen.iter().all(|&c| c == 1), "{threads:?}: {seen:?}");
        }
        // A failing sink stops the call with its error.
        for threads in [Some(1), Some(4)] {
            let mut calls = 0;
            let res = pager(&path).for_each_page_with(&want, threads, |_, _| {
                calls += 1;
                if calls == 10 {
                    Err(MnemoError::Invalid("stop".into()))
                } else {
                    Ok(())
                }
            });
            assert!(matches!(res, Err(MnemoError::Invalid(_))), "{threads:?}");
            assert_eq!(calls, 10);
        }
        // A cached dirty copy wins.
        let mut p = pager(&path);
        p.write_page(2, GEN, b"cached").unwrap();
        let mut got = Vec::new();
        p.for_each_page_with(&[(2, GEN), (3, GEN)], Some(1), |i, b| {
            got.push((i, b[..6].to_vec()));
            Ok(())
        })
        .unwrap();
        got.sort();
        assert_eq!(got[0], (0, b"cached".to_vec()));
        assert_eq!(&got[1].1[..6], &3u64.to_le_bytes()[..6]);
        // A damaged page: its own number in the error.
        {
            use std::io::{Seek, SeekFrom, Write};
            let mut f = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
            f.seek(SeekFrom::Start(100 * PAGE_SIZE as u64 + 64))
                .unwrap();
            f.write_all(&[0x5A]).unwrap();
        }
        for threads in [Some(1), Some(4)] {
            let res = pager(&path).for_each_page_with(&want, threads, |_, _| Ok(()));
            assert!(
                matches!(res, Err(MnemoError::PageAuthFailed(100))),
                "{threads:?}: {:?}",
                res.err()
            );
        }
    }
}