Skip to main content

mnemo_engine/store/
flush.rs

1//! Commits and durability: sealed runs, the WAL and checkpoint, flush, close, and the page-cache and vector-budget settings.
2
3use super::*;
4
5impl Mnemo {
6    /// Seal a serialized buffer into a fresh run of encrypted home pages and
7    /// append a WAL frame for each. Returns the run's `(start_page, pages)`.
8    /// The pages are *not* written to their home locations here — they go to
9    /// the WAL and are folded in later by [`Mnemo::checkpoint`].
10    ///
11    /// `gen` is the run's generation (v9; `0` on v8). On v9 the pages come
12    /// from the free list when an eligible run fits.
13    pub(super) fn seal_run(
14        &mut self,
15        bytes: &[u8],
16        gen: u64,
17        frames: &mut Vec<wal::Frame>,
18    ) -> Result<(u64, u32)> {
19        let pc = bytes.len().div_ceil(PAYLOAD).max(1);
20        let start = self.alloc_pages(pc as u64);
21        self.seal_run_at(start, pc as u64, bytes, gen, frames)?;
22        Ok((start, pc as u32))
23    }
24
25    /// Seal `bytes` into the `pages` already-allocated pages at `start`
26    /// (pages past the data are sealed empty) and append their WAL frames.
27    pub(super) fn seal_run_at(
28        &mut self,
29        start: u64,
30        pages: u64,
31        bytes: &[u8],
32        gen: u64,
33        frames: &mut Vec<wal::Frame>,
34    ) -> Result<()> {
35        let direct = self.is_v9() && pages > V9_WAL_RUN_MAX_PAGES;
36        for i in 0..pages as usize {
37            let lo = (i * PAYLOAD).min(bytes.len());
38            let hi = ((i + 1) * PAYLOAD).min(bytes.len());
39            let page_no = start + i as u64;
40            let sealed = self.pager.seal_page(page_no, gen, &bytes[lo..hi])?;
41            if direct {
42                self.pager.write_sealed(page_no, &sealed)?;
43            } else {
44                frames.push((page_no, sealed.to_vec()));
45            }
46        }
47        if direct {
48            self.direct_writes = true;
49        }
50        Ok(())
51    }
52
53    /// Grow the WAL region if `frame_pages` worth of frames would not fit.
54    /// Called at the top of `flush`, where the WAL is always spent (every
55    /// flush ends with a checkpoint), so relocating it cannot strand a
56    /// committed transaction.
57    pub(super) fn ensure_wal_capacity(&mut self, frame_pages: usize) -> Result<()> {
58        let need = wal::txn_byte_len(frame_pages, PAGE_SIZE);
59        if need <= self.header.wal_pages * PAGE_SIZE as u64 {
60            return Ok(());
61        }
62        // Allocate a new, larger region at the file tail (~1.5x headroom).
63        let req = need.div_ceil(PAGE_SIZE as u64);
64        let new_pages = (req + req / 2 + 4).max(DEFAULT_WAL_PAGES);
65        let old_wal_start = self.header.wal_start;
66        let old_wal_pages = self.header.wal_pages;
67        // FMT-9 (a): the new region always comes from the file's tail: the
68        // relocation commits a header-only transaction, so a region taken
69        // from the free list would still be listed as free in the
70        // committed free-list run.
71        let new_start = self.header.next_page;
72        self.header.next_page += new_pages;
73        self.header.wal_start = new_start;
74        self.header.wal_pages = new_pages;
75        self.header.wal_seq += 1;
76        // DUR-1 (R-002.1): WAL-log the header change into the *new* region
77        // first, checkpoint page 0, then invalidate the old region. A crash
78        // anywhere here either keeps the old state (if page 0 wasn't yet
79        // overwritten) or recovers to the new state via the torn-header
80        // scan in `Mnemo::open`, which prefers the highest-txn-id valid
81        // committed header frame.
82        self.relocate_header_through_wal(old_wal_start)?;
83        // FMT-9 (a): once the relocation has committed, the old region is
84        // unreferenced; the next commit frees it.
85        self.release_pages(old_wal_start, old_wal_pages);
86        Ok(())
87    }
88
89    /// Shared helper for every post-`create` page-0 commit: WAL-log the
90    /// new header into the current WAL region, checkpoint page 0, and
91    /// invalidate `old_wal_start` (the previous region, or the current
92    /// region when it hasn't moved). The caller is expected to have
93    /// mutated `self.header` to its target values *including a bumped
94    /// `wal_seq`* (one more than the last on-disk `wal_seq`); this
95    /// routine applies the seal, writes the frame + commit, folds page 0,
96    /// then zeroes the old region's first frame header.
97    ///
98    /// If `old_wal_start == self.header.wal_start`, the invalidation is
99    /// skipped — the region didn't move, so overwriting its first frame
100    /// would destroy the just-committed one.
101    pub(super) fn relocate_header_through_wal(&mut self, old_wal_start: u64) -> Result<()> {
102        self.header.write_counter = self.pager.write_counter;
103        let mut page = self.header.to_page();
104        self.header.apply_seal(&mut page, self.pager.dek())?;
105        let txn_id = self.header.wal_seq;
106        let frames = vec![(0u64, page.to_vec())];
107        wal::commit(
108            self.pager.file_mut(),
109            self.header.wal_start,
110            self.header.wal_pages,
111            txn_id,
112            &frames,
113        )?;
114        self.pager.write_raw(0, &page)?;
115        self.pager.sync()?;
116        if old_wal_start != self.header.wal_start {
117            wal::invalidate_region(self.pager.file_mut(), old_wal_start)?;
118        }
119        Ok(())
120    }
121
122    /// Fold a committed transaction's WAL frames into their home pages.
123    pub(super) fn checkpoint(&mut self, frames: &[wal::Frame]) -> Result<()> {
124        for (page_no, bytes) in frames {
125            let mut img = [0u8; PAGE_SIZE];
126            img.copy_from_slice(bytes);
127            self.pager.write_sealed(*page_no, &img)?;
128        }
129        self.pager.sync()?;
130        Ok(())
131    }
132
133    /// Persist all pending changes as one **write-ahead-logged transaction**.
134    ///
135    /// Sequence:
136    ///
137    /// 1. **Prepare.** Serialize the control plane (catalog, ANN index),
138    ///    grow the WAL if needed, and **lease** counter and page slots —
139    ///    bump `header.write_counter` and `header.next_page` by upper
140    ///    bounds on this transaction's consumption and persist that
141    ///    *leased* header to disk before any encrypted page is written.
142    /// 2. **Data pages.** [`Pager::flush`] writes dirty record pages
143    ///    copy-on-write under fresh nonces and fsyncs them. The orphan-page
144    ///    nonce-reuse window (see [Phase 1.1 of the improvement plan])
145    ///    is closed because the leased header on disk already records a
146    ///    `write_counter` past anything this step can produce.
147    /// 3. **Control plane.** Seal the new catalog / ANN index / snapshot
148    ///    manifest into fresh home page runs.
149    /// 4. **Commit.** Log all of step 3's frames plus the final header
150    ///    frame into the WAL and fsync — the durability point.
151    /// 5. **Checkpoint.** Fold the WAL into the home pages.
152    ///
153    /// A crash before step 4 leaves the previous state intact. A crash
154    /// after step 4 is repaired by [`Mnemo::open`] replaying the WAL.
155    /// Safe to call repeatedly.
156    pub fn flush(&mut self) -> Result<()> {
157        if self.read_only {
158            return Err(MnemoError::ReadOnly);
159        }
160        // Snapshot the thread-local fsync counter. Every `sync_all` the
161        // pager / wal / checkpoint path makes between here and the end
162        // of this function bumps the same counter; `delta` lands on
163        // `self.fsyncs_last_flush` so `Stats::fsyncs_last_flush` can
164        // report it. The planner wants this to decide whether cutting
165        // fsync count is a viable write-latency win before we touch
166        // the write path's durability model.
167        let fsync_before = crate::fsync_count();
168        // PERF-1 step 3: while the index is unloaded, records written since
169        // its run pile up for the next load to re-assign. Once there are
170        // INDEX_PERSIST_EVERY_CHANGES of them, load it now so this flush
171        // persists a current index and keeps that work bounded.
172        if self.ann_unloaded && self.dirty_catalog {
173            let (index_start, index_gen) = (self.header.index_start, self.index_gen_now());
174            let v9 = self.is_v9();
175            let pending = self
176                .catalog
177                .iter()
178                .filter(|e| !e.deleted && written_after_index(e, v9, index_start, index_gen))
179                .count();
180            if pending >= INDEX_PERSIST_EVERY_CHANGES {
181                self.ensure_ann()?;
182            }
183        }
184        // PERF-1: persist the (derived) ANN index only when forced or due.
185        // Otherwise the header keeps pointing at the previous index run, and
186        // records written since then are re-assigned when it's next loaded
187        // (`reconcile_ann_with_catalog`). `ann == None` with `dirty_index` set is a
188        // dropped index, which is persisted at once.
189        let persist_index = if self.is_v9() {
190            self.plan_index_v9()
191        } else {
192            self.dirty_index
193                && (self.index_persist.forced
194                    || self.ann.is_none()
195                    || self.index_persist.commits + 1 >= INDEX_PERSIST_EVERY_COMMITS
196                    || self.index_persist.changes >= INDEX_PERSIST_EVERY_CHANGES)
197        };
198        let free_work =
199            self.is_v9() && (self.free_dirty || !self.pending_free.is_empty() || self.dirty_keys);
200        if !self.dirty_catalog && !persist_index && !self.dirty_cache && !free_work {
201            // No control-plane changes pending. Because every `put` that
202            // dirties a data page also dirties the catalog, and every
203            // `cache_put` that dirties a data page also dirties
204            // `dirty_cache`, there can't be dirty data pages either —
205            // nothing to do.
206            self.fsyncs_last_flush = 0;
207            return Ok(());
208        }
209
210        // FIX-1 R-001.8 part 3: snapshot the memory/index-dirty flags
211        // before step 3b decides whether to push a restore point.
212        // Only flushes that change the memory catalog or ANN index
213        // need a snapshot — a cache-only flush (`dirty_cache` set,
214        // `dirty_catalog` + `dirty_index` both false) must not push,
215        // because snapshots don't capture cache state and every push
216        // counts against `max_snapshots` (default 256), so a cache-
217        // heavy workload would otherwise evict every real memory
218        // restore point within ~256 cache writes.
219        let is_memory_or_index_flush = self.dirty_catalog || persist_index;
220
221        // FMT-9: a v9 session's first sealed page needs the generation
222        // lease (normally taken by its first record write already).
223        self.ensure_gen_lease()?;
224        // FMT-9e: turns that aged past the cutoff are rewritten compressed
225        // (bounded per commit), then packed with the other waiting records.
226        self.settle_cold_turns()?;
227        // FMT-9b: column entries first; they move rows' vector locations,
228        // so they must land before the catalog is serialized.
229        self.pack_records()?;
230        self.pack_vectors()?;
231
232        // 1. Serialize control plane, ensure WAL capacity, lease counter +
233        //    page slots, and persist the leased header *before* any data
234        //    page hits the disk.
235        let ctx = self.prepare_for_flush(persist_index)?;
236
237        // 2. Record (vector) data pages: copy-on-write to fresh pages, fsynced.
238        //    Safe: the lease guarantees that even if we crash here, reopen
239        //    will see a `write_counter` past every nonce this step uses.
240        self.pager.flush()?;
241
242        // 3. Seal the catalog / index control pages into fresh home runs.
243        //    FMT-9: `txn_id` is this transaction's id and the generation
244        //    of every run it seals. A v9 run replaced here is freed by this
245        //    same commit (`superseded`); v8 never reuses pages.
246        let txn_id = self.header.wal_seq + 1;
247        let gen = if self.is_v9() { txn_id } else { 0 };
248        let v9 = self.is_v9();
249        let mut superseded: Vec<(u64, u64)> = Vec::new();
250        let mut frames: Vec<wal::Frame> = Vec::new();
251        // FMT-9c.2: a delta run goes on the chain; a new base replaces the
252        // old base and the whole chain (all freed by this commit). The
253        // chain is adopted once the commit succeeds.
254        let mut new_chain: Option<(Vec<RunPtr>, usize)> = None;
255        if let Some(bytes) = &ctx.cat_bytes {
256            if ctx.cat_delta {
257                let (start, pages) = self.seal_run(bytes, gen, &mut frames)?;
258                let ptr = RunPtr {
259                    start,
260                    pages: pages as u64,
261                    len: bytes.len() as u64,
262                    gen,
263                };
264                self.header.catalog_delta = ptr;
265                let mut chain = self.delta_chain.clone();
266                chain.push(ptr);
267                new_chain = Some((chain, self.delta_rows + self.dirty_rows.len()));
268            } else {
269                if v9 && self.header.catalog_pages > 0 {
270                    superseded.push((self.header.catalog_start, self.header.catalog_pages));
271                }
272                if v9 {
273                    for r in &self.delta_chain {
274                        superseded.push((r.start, r.pages));
275                    }
276                    self.header.catalog_delta = RunPtr::default();
277                    new_chain = Some((Vec::new(), 0));
278                }
279                let (start, pages) = self.seal_run(bytes, gen, &mut frames)?;
280                self.header.catalog_start = start;
281                self.header.catalog_pages = pages as u64;
282                self.header.catalog_len = bytes.len() as u64;
283                self.header.catalog_gen = gen;
284            }
285        }
286        // FMT-9d: the BM25 segment, then the manifest that lists it.
287        let mut new_bm25: Option<Bm25Segments> = None;
288        if let Some((bytes, replace_from)) = &ctx.bm25_seg {
289            let (start, pages) = self.seal_run(bytes, gen, &mut frames)?;
290            let mut segs = self.bm25.manifest.segments.clone();
291            let mut seg_docs = self.bm25.manifest.seg_docs.clone();
292            seg_docs.resize(segs.len(), 0);
293            let docs = if let Some(from) = *replace_from {
294                for t in segs.drain(from..) {
295                    superseded.push((t.0, t.1));
296                }
297                seg_docs.truncate(from);
298                self.bm25.merged_docs
299            } else {
300                self.bm25.pending.len() as u32
301            };
302            segs.push((start, pages as u64, bytes.len() as u64, gen));
303            seg_docs.push(docs);
304            let man = Bm25Manifest {
305                tokenizer: text::TOKENIZER_V1,
306                next_doc: self.bm25.manifest.next_doc,
307                segments: segs.clone(),
308                seg_docs: seg_docs.clone(),
309            };
310            let mbytes =
311                rmp_serde::to_vec(&man).map_err(|e| MnemoError::Serialize(e.to_string()))?;
312            if !self.header.bm25.is_empty() {
313                superseded.push((self.header.bm25.start, self.header.bm25.pages));
314            }
315            let (ms, mp) = self.seal_run(&mbytes, gen, &mut frames)?;
316            self.header.bm25 = RunPtr {
317                start: ms,
318                pages: mp as u64,
319                len: mbytes.len() as u64,
320                gen,
321            };
322            new_bm25 = Some((segs, seg_docs));
323        }
324        let mut new_ichain: Option<(Vec<RunPtr>, usize)> = None;
325        if persist_index && ctx.idx_delta {
326            if let Some(bytes) = &ctx.idx_bytes {
327                let (start, pages) = self.seal_run(bytes, gen, &mut frames)?;
328                let ptr = RunPtr {
329                    start,
330                    pages: pages as u64,
331                    len: bytes.len() as u64,
332                    gen,
333                };
334                self.header.index_delta = ptr;
335                let mut chain = self.index_chain.clone();
336                chain.push(ptr);
337                let n = self.index_delta_ops.as_ref().map_or(0, |o| o.len());
338                new_ichain = Some((chain, self.index_chain_ops + n));
339            }
340        } else if persist_index {
341            if v9 && self.header.index_pages > 0 {
342                superseded.push((self.header.index_start, self.header.index_pages));
343            }
344            if v9 {
345                for r in &self.index_chain {
346                    superseded.push((r.start, r.pages));
347                }
348                self.header.index_delta = RunPtr::default();
349                new_ichain = Some((Vec::new(), 0));
350            }
351            match &ctx.idx_bytes {
352                Some(bytes) => {
353                    let (start, pages) = self.seal_run(bytes, gen, &mut frames)?;
354                    self.header.index_start = start;
355                    self.header.index_pages = pages as u64;
356                    self.header.index_len = bytes.len() as u64;
357                    self.header.index_gen = gen;
358                }
359                None => {
360                    self.header.index_start = 0;
361                    self.header.index_pages = 0;
362                    self.header.index_len = 0;
363                    self.header.index_gen = 0;
364                }
365            }
366        }
367        // v8+ result-cache directory (Phase 10.1). Seal the serialized
368        // directory into a fresh page run and update the pointer in the
369        // header. The seal AAD already covers cache_start/pages/len for
370        // v8+ (see `header_seal_aad`), so tampering with the pointer
371        // trips the header seal on the next open.
372        if self.dirty_cache {
373            if v9 && self.header.cache_pages > 0 {
374                superseded.push((self.header.cache_start, self.header.cache_pages));
375            }
376            match &ctx.cache_bytes {
377                Some(bytes) if !self.cache_dir.is_empty() => {
378                    let (start, pages) = self.seal_run(bytes, gen, &mut frames)?;
379                    self.header.cache_start = start;
380                    self.header.cache_pages = pages as u64;
381                    self.header.cache_len = bytes.len() as u64;
382                    self.header.cache_gen = gen;
383                }
384                _ => {
385                    // Either the directory serialized to nothing (all
386                    // entries deleted after tombstone-only migration) or
387                    // it's empty — collapse the pointer to zero.
388                    self.header.cache_start = 0;
389                    self.header.cache_pages = 0;
390                    self.header.cache_len = 0;
391                    self.header.cache_gen = 0;
392                }
393            }
394        }
395
396        // 3b. Record this transaction as a restorable snapshot. The manifest
397        //     update is staged in a local and adopted only once the commit
398        //     below succeeds, so a failed flush leaves no phantom entry.
399        //
400        //     The cap (`self.max_snapshots`) is applied to the staged local
401        //     before the new entry lands, so after appending the manifest
402        //     holds at most `max_snapshots` entries — the most-recent N.
403        //     `max_snapshots == 0` disables the cap. On v8, pages
404        //     referenced only by pruned snapshots stay on disk until
405        //     `compact_file`; on v9 they become reusable once no retained
406        //     snapshot is older than the transaction that freed them.
407        //
408        //     FIX-1 R-001.8 part 3: skip the snapshot push on a
409        //     cache-only flush. Snapshots don't capture the cache
410        //     anyway, and every push counts against `max_snapshots`
411        //     (default 256) + rewrites the manifest run — so a
412        //     cache-heavy workload would otherwise evict every real
413        //     memory restore point within ~256 cache writes. On a
414        //     cache-only flush we reuse the current manifest
415        //     verbatim; the manifest run already lives at
416        //     `self.header.manifest_{start,pages,len}` (set by the
417        //     last memory-touching flush, or at `create` time).
418        let live = self.len() as u64;
419        let mut manifest = self.manifest.clone();
420        if is_memory_or_index_flush {
421            if self.max_snapshots > 0 && !v9 {
422                // Drop the oldest entries so there's room for the new one.
423                while manifest.len() >= self.max_snapshots {
424                    manifest.remove(0);
425                }
426            }
427            manifest.push(Snapshot {
428                txn_id,
429                created_at: memory::now_secs(),
430                catalog_start: self.header.catalog_start,
431                catalog_pages: self.header.catalog_pages,
432                catalog_len: self.header.catalog_len,
433                index_start: self.header.index_start,
434                index_pages: self.header.index_pages,
435                index_len: self.header.index_len,
436                memory_count: live,
437                gens: v9.then_some(SnapshotGens {
438                    catalog: self.header.catalog_gen,
439                    index: self.header.index_gen,
440                    delta: ptr_tuple(self.header.catalog_delta),
441                    index_delta: ptr_tuple(self.header.index_delta),
442                    bm25: ptr_tuple(self.header.bm25),
443                }),
444            });
445            if v9 {
446                let extra = self.pending_free.iter().map(|r| r.1).sum::<u64>()
447                    + superseded.iter().map(|r| r.1).sum::<u64>()
448                    + self.header.manifest_pages;
449                self.apply_retention(&mut manifest, extra);
450            }
451            let man_bytes =
452                rmp_serde::to_vec(&manifest).map_err(|e| MnemoError::Serialize(e.to_string()))?;
453            if v9 && self.header.manifest_pages > 0 {
454                superseded.push((self.header.manifest_start, self.header.manifest_pages));
455            }
456            let (m_start, m_pages) = self.seal_run(&man_bytes, gen, &mut frames)?;
457            self.header.manifest_start = m_start;
458            self.header.manifest_pages = m_pages as u64;
459            self.header.manifest_len = man_bytes.len() as u64;
460            self.header.manifest_gen = gen;
461        }
462
463        // 3c. FMT-9 (b): the key-slot run, rewritten copy-on-write when a
464        //     slot changed. The header seal covers its pointer.
465        if v9 && self.dirty_keys {
466            if !self.header.keys.is_empty() {
467                superseded.push((self.header.keys.start, self.header.keys.pages));
468            }
469            if self.key_slots.slots.is_empty() {
470                self.header.keys = RunPtr::default();
471            } else {
472                let bytes = rmp_serde::to_vec(&self.key_slots)
473                    .map_err(|e| MnemoError::Serialize(e.to_string()))?;
474                let (start, pages) = self.seal_run(&bytes, gen, &mut frames)?;
475                self.header.keys = RunPtr {
476                    start,
477                    pages: pages as u64,
478                    len: bytes.len() as u64,
479                    gen,
480                };
481            }
482        }
483
484        // 3d. FMT-9 (a): the free list. Everything this transaction
485        //     stopped referencing (`pending_free`, the runs replaced above,
486        //     and the previous free-list run itself) is freed *at this
487        //     transaction's id*, in this transaction's own commit, so it
488        //     can't be reused until this commit is durable and no retained
489        //     snapshot predates it. The list is staged in a local and
490        //     adopted only once the commit succeeds (a failed flush that
491        //     is retried must not free the same runs twice).
492        let mut shrink = false;
493        let staged_free =
494            if v9 && (self.free_dirty || !self.pending_free.is_empty() || !superseded.is_empty()) {
495                let mut staged = self.free.clone();
496                for &(p, c) in self.pending_free.iter().chain(superseded.iter()) {
497                    staged.free(txn_id, p, c)?;
498                }
499                if !self.header.free.is_empty() {
500                    staged.free(txn_id, self.header.free.start, self.header.free.pages)?;
501                }
502                // FMT-9c: give eligible free runs at the file's tail back
503                // to the filesystem: the header's `next_page` moves down in
504                // this commit, and the file is cut after it.
505                let min_snap = self.min_snapshot_txn();
506                while let Some(p) =
507                    staged.take_tail(self.header.next_page, self.header.wal_seq, min_snap)
508                {
509                    self.header.next_page = p;
510                    shrink = true;
511                }
512                // Size the run with room for the one extra entry that
513                // allocating it out of the list can create (a split), then
514                // allocate it from the list (eligible runs only) or the tail.
515                let est = rmp_serde::to_vec(&staged.to_runs())
516                    .map_err(|e| MnemoError::Serialize(e.to_string()))?
517                    .len()
518                    + 64;
519                let pc = est.div_ceil(PAYLOAD).max(1) as u64;
520                let start = match staged.alloc(pc, self.header.wal_seq, self.min_snapshot_txn()) {
521                    Some(p) => p,
522                    None => {
523                        let p = self.header.next_page;
524                        self.header.next_page += pc;
525                        p
526                    }
527                };
528                let bytes = rmp_serde::to_vec(&staged.to_runs())
529                    .map_err(|e| MnemoError::Serialize(e.to_string()))?;
530                if bytes.len() as u64 > pc * PAYLOAD as u64 {
531                    return Err(MnemoError::Invalid(
532                        "free list outgrew its reserved run".into(),
533                    ));
534                }
535                self.seal_run_at(start, pc, &bytes, gen, &mut frames)?;
536                self.header.free = RunPtr {
537                    start,
538                    pages: pc,
539                    len: bytes.len() as u64,
540                    gen,
541                };
542                Some(staged)
543            } else {
544                None
545            };
546
547        // 3e. The header is the transaction's final frame; stamp the new id
548        //     and the *actual* (post-flush) write counter, which is <= the
549        //     leased value persisted in `prepare_for_flush`. This is the
550        //     value that ultimately replaces the leased header on checkpoint.
551        self.header.vector_count = live;
552        self.header.write_counter = self.pager.write_counter;
553        self.header.wal_seq = txn_id;
554        let mut hpage = self.header.to_page();
555        self.header.apply_seal(&mut hpage, self.pager.dek())?;
556        frames.push((0, hpage.to_vec()));
557
558        // 4. COMMIT — log the transaction and fsync. Nothing at a home page
559        //    other than the leased header has changed yet; this single
560        //    fsync is what makes the rest durable.
561        // FMT-9c: big runs went straight to their home pages; make them
562        // durable before the header that references them can be.
563        if self.direct_writes {
564            self.pager.sync()?;
565            self.direct_writes = false;
566        }
567        let (wal_start, wal_pages) = (self.header.wal_start, self.header.wal_pages);
568        wal::commit(self.pager.file_mut(), wal_start, wal_pages, txn_id, &frames)?;
569
570        // 5. Checkpoint — fold the WAL into the home pages.
571        self.checkpoint(&frames)?;
572        // FMT-9c: the committed header no longer covers the tail; cut it.
573        // A crash before this leaves a longer file, which is harmless.
574        if shrink {
575            let len = self.header.next_page * PAGE_SIZE as u64;
576            self.pager.file_mut().set_len(len)?;
577        }
578
579        self.manifest = manifest;
580        if let Some(staged) = staged_free {
581            self.free = staged;
582        }
583        self.pending_free.clear();
584        self.free_dirty = false;
585        self.dirty_keys = false;
586        if let Some((chain, rows)) = new_chain {
587            self.delta_chain = chain;
588            self.delta_rows = rows;
589        }
590        if let Some((chain, n)) = new_ichain {
591            self.index_chain = chain;
592            self.index_chain_ops = n;
593        }
594        if let Some((segs, seg_docs)) = new_bm25 {
595            // FMT-9f: keep the loaded dicts and read only the new segment's
596            // (a merge replaced the segments from `kept` on), instead of
597            // dropping them all and reloading every dict on next use.
598            let kept = self
599                .bm25
600                .manifest
601                .segments
602                .iter()
603                .zip(&segs)
604                .take_while(|(a, b)| a == b)
605                .count();
606            if let Some(mut dicts) = self.bm25.dicts.take() {
607                dicts.truncate(kept);
608                let mut ok = dicts.len() == kept;
609                for &t in &segs[kept..] {
610                    match load_segment_dict(&mut self.pager, tuple_ptr(t)) {
611                        Ok(d) if ok => dicts.push(d),
612                        _ => ok = false,
613                    }
614                }
615                if ok {
616                    self.bm25.dicts = Some(dicts);
617                }
618            }
619            self.bm25.manifest.segments = segs;
620            self.bm25.manifest.seg_docs = seg_docs;
621            self.bm25.pending.clear();
622        }
623        if persist_index {
624            self.index_rebase = false;
625            self.index_delta_ops = None;
626        }
627        if ctx.cat_bytes.is_some() {
628            self.dirty_rows.clear();
629            self.catalog_rewrite = false;
630        }
631        self.dirty_catalog = false;
632        if persist_index {
633            self.dirty_index = false;
634            self.index_persist = IndexPersist::default();
635        } else if self.dirty_index {
636            self.index_persist.commits += 1;
637        }
638        self.dirty_cache = false;
639        // Batched policy: successful flush consumes the pending batch.
640        self.cache_batch.reset();
641        // Record how many fsyncs this flush issued, for Stats reporting.
642        // Thread-local counter guarantees we see only this handle's own
643        // sync_all calls between the snapshot above and this read.
644        self.fsyncs_last_flush =
645            (crate::fsync_count().wrapping_sub(fsync_before)).min(u32::MAX as u64) as u32;
646        Ok(())
647    }
648
649    /// Pre-flush prelude shared by [`Mnemo::flush`] and the
650    /// `__crash_partial_flush_for_testing` hook.
651    ///
652    /// Serializes the control plane (catalog, ANN index, cache directory)
653    /// and grows the WAL if needed. That's it: this used to persist a
654    /// leased header too (SEC-1 obsoleted it; see DUR-1 R-002.1 note in
655    /// the body for the full rationale), but after DUR-1 the only page-0
656    /// writes outside `create` go through the WAL via
657    /// [`Mnemo::relocate_header_through_wal`].
658    ///
659    /// The historical pre-stamping used to close the nonce-reuse window
660    /// flagged in Phase 1.1 of the improvement plan: a crash anywhere
661    /// between here and the WAL commit left a file whose on-disk header
662    /// recorded a `write_counter` past every nonce the rest of this
663    /// transaction could produce, so the next reopen started from a
664    /// counter that guaranteed uniqueness against any orphan data pages
665    /// still on disk. SEC-1's per-session random nonce prefix gives the
666    /// same guarantee without needing a persisted counter, which is why
667    /// this routine no longer writes page 0.
668    pub(super) fn prepare_for_flush(&mut self, persist_index: bool) -> Result<FlushPrelude> {
669        // Serialize.
670        // FMT-9c.2: on v9 usually just the changed rows, as a delta run.
671        let cat_delta = self.dirty_catalog && self.catalog_as_delta();
672        let cat_bytes = if !self.dirty_catalog {
673            None
674        } else if cat_delta {
675            let rows: Vec<(u32, CatalogEntry)> = self
676                .dirty_rows
677                .iter()
678                .filter(|&&i| i < self.catalog.len())
679                .map(|&i| (i as u32, self.catalog[i].clone()))
680                .collect();
681            let d = CatalogDelta {
682                prev: ptr_tuple(self.header.catalog_delta),
683                rows,
684            };
685            Some(rmp_serde::to_vec(&d).map_err(|e| MnemoError::Serialize(e.to_string()))?)
686        } else {
687            if self.is_v9() {
688                self.compact_tombstones();
689            }
690            Some(
691                rmp_serde::to_vec(&self.catalog)
692                    .map_err(|e| MnemoError::Serialize(e.to_string()))?,
693            )
694        };
695        // FMT-9c.3: a v9 commit usually writes just its index changes.
696        let idx_delta = persist_index && self.index_delta_ops.is_some();
697        let idx_bytes: Option<Vec<u8>> = if !persist_index {
698            None
699        } else if let Some(ops) = &self.index_delta_ops {
700            let d = IndexDeltaRef {
701                prev: ptr_tuple(self.header.index_delta),
702                ops,
703            };
704            Some(rmp_serde::to_vec(&d).map_err(|e| MnemoError::Serialize(e.to_string()))?)
705        } else {
706            match &self.ann {
707                Some(ann) => {
708                    let mut b =
709                        rmp_serde::to_vec(ann).map_err(|e| MnemoError::Serialize(e.to_string()))?;
710                    // FMT-9: v9 index runs carry a layout byte first.
711                    if self.is_v9() {
712                        b.insert(0, self.index_layout_override.unwrap_or(V9_INDEX_LAYOUT));
713                    }
714                    Some(b)
715                }
716                None => None,
717            }
718        };
719        // Serialize the result-cache directory when it's dirty. An
720        // empty directory serializes to a small header + 0-element
721        // array; still cheap enough that we don't special-case it.
722        let cache_bytes: Option<Vec<u8>> = if self.dirty_cache {
723            Some(
724                rmp_serde::to_vec(&self.cache_dir)
725                    .map_err(|e| MnemoError::Serialize(e.to_string()))?,
726            )
727        } else {
728            None
729        };
730
731        let cat_pc = cat_bytes
732            .as_ref()
733            .map_or(0, |b| b.len().div_ceil(PAYLOAD).max(1));
734        let idx_pc = idx_bytes
735            .as_ref()
736            .map_or(0, |b| b.len().div_ceil(PAYLOAD).max(1));
737        let cache_pc = cache_bytes
738            .as_ref()
739            .map_or(0, |b| b.len().div_ceil(PAYLOAD).max(1));
740        // Upper bound on the manifest run: one extra entry, <=82 bytes each
741        // (rmp_serde encodes a Snapshot as a 9-element fixarray of i64/u64,
742        // worst case 81 bytes plus a 1-byte array header).
743        // v9 snapshots carry two more u64s (≤ 20 bytes with the array header).
744        let per_snapshot = if self.is_v9() { 102 } else { 82 };
745        let man_upper = 9 + (self.manifest.len() + 1) * per_snapshot;
746        let man_pc_est = man_upper.div_ceil(PAYLOAD).max(1);
747        // FMT-9: the free-list run (≤ 28 bytes per run: every pending and
748        // superseded run plus a split and a relocated WAL region) and the
749        // key-slot run.
750        let (free_pc_est, keys_pc) = if self.is_v9() {
751            let runs = self.free.len() + self.pending_free.len() + 12;
752            let free_pc = (runs * 28 + 64).div_ceil(PAYLOAD).max(1);
753            let keys_pc = if self.dirty_keys {
754                rmp_serde::to_vec(&self.key_slots)
755                    .map_err(|e| MnemoError::Serialize(e.to_string()))?
756                    .len()
757                    .div_ceil(PAYLOAD)
758                    .max(1)
759            } else {
760                0
761            };
762            (free_pc, keys_pc)
763        } else {
764            (0, 0)
765        };
766
767        // Grow WAL if needed (DUR-1: relocation is WAL-logged and does
768        // its own fsyncs). The cache directory rides in the same
769        // transaction so its page count contributes to the reservation.
770        // FMT-9d: the BM25 segment (and its manifest, one page).
771        let bm25_seg = self.bm25_next_segment()?;
772        let bm25_pc = bm25_seg
773            .as_ref()
774            .map_or(0, |(b, _)| b.len().div_ceil(PAYLOAD).max(1));
775        // FMT-9c: on v9 only runs of up to V9_WAL_RUN_MAX_PAGES go through
776        // the WAL; longer ones are written in place.
777        let v9 = self.is_v9();
778        let in_wal = |pc: usize| {
779            if v9 && pc as u64 > V9_WAL_RUN_MAX_PAGES {
780                0
781            } else {
782                pc
783            }
784        };
785        self.ensure_wal_capacity(
786            in_wal(cat_pc)
787                + in_wal(idx_pc)
788                + in_wal(cache_pc)
789                + in_wal(man_pc_est)
790                + in_wal(free_pc_est)
791                + in_wal(keys_pc)
792                + in_wal(bm25_pc)
793                + usize::from(bm25_pc > 0)
794                + 1,
795        )?;
796
797        // DUR-1 (R-002.1): the pre-flush "leased header" write that used
798        // to live here is gone. It existed to close the Phase 1.1 nonce
799        // reuse window (reopen must see a `write_counter` past any nonce
800        // this flush could produce before data pages hit disk). SEC-1
801        // superseded that: nonces now carry a per-session random prefix
802        // and `write_counter` is no longer a nonce input, so the leased
803        // write bought us nothing but an extra fsync per flush. Orphan
804        // data pages past `header.next_page` on a crashed flush are
805        // still safe — the next session's random prefix makes any later
806        // write at the same page_no uniquely nonced regardless of
807        // `write_counter`.
808
809        Ok(FlushPrelude {
810            bm25_seg,
811            cat_bytes,
812            cat_delta,
813            idx_delta,
814            idx_bytes,
815            cache_bytes,
816        })
817    }
818
819    /// Flush and close: consumes the handle and releases the file and its
820    /// OS advisory lock before returning, so the same file can be reopened
821    /// right away (by this process or another). On a read-write handle it
822    /// flushes first, persisting a dirty ANN index too; on a read-only
823    /// handle there's nothing to persist.
824    ///
825    /// Using the handle after `close` is a compile error. If the flush
826    /// fails, the error is returned and the handle is dropped all the same:
827    /// changes since the last successful [`Mnemo::flush`] are lost, as
828    /// they would be on a plain `drop` (which never flushes).
829    ///
830    /// A struct that owns a handle and closes it from `&mut self` keeps it
831    /// in an `Option` and `take()`s it:
832    ///
833    /// ```no_run
834    /// use mnemo_engine::{Mnemo, Result};
835    ///
836    /// struct App {
837    ///     db: Option<Mnemo>,
838    /// }
839    ///
840    /// impl App {
841    ///     fn shutdown(&mut self) -> Result<()> {
842    ///         match self.db.take() {
843    ///             Some(db) => db.close(),
844    ///             None => Ok(()), // already closed
845    ///         }
846    ///     }
847    /// }
848    /// ```
849    ///
850    /// Changed in v0.12.0: `close` took `&mut self` and left the file and
851    /// lock held until the handle was dropped.
852    ///
853    /// **If the final flush fails, the handle is dropped with it**, and the
854    /// writes that weren't flushed are lost (a full disk on a phone, say).
855    /// [`Mnemo::try_close`] gives the handle back on that path, so the caller
856    /// can free space and retry.
857    pub fn close(mut self) -> Result<()> {
858        if !self.read_only {
859            // PERF-1: closing persists a dirty ANN index too, so the next
860            // open has nothing to re-assign.
861            self.index_persist.forced = true;
862            self.flush()?;
863        }
864        // Dropping the handle closes the file, which releases the lock.
865        drop(self);
866        Ok(())
867    }
868
869    /// [`Mnemo::close`] that keeps the data when the final flush fails: the
870    /// error carries the handle back, with every unflushed write still in
871    /// it, as [`std::io::BufWriter::into_inner`] does. Retry with
872    /// [`Mnemo::flush`] or another `try_close` once the cause is fixed.
873    /// A read-only handle never flushes, so it always closes. Added in
874    /// v0.12.2 (RB-001.22).
875    ///
876    /// ```no_run
877    /// # use mnemo_engine::Mnemo;
878    /// # fn run(db: Mnemo) -> mnemo_engine::Result<()> {
879    /// match db.try_close() {
880    ///     Ok(()) => {}
881    ///     Err(e) => {
882    ///         eprintln!("close failed: {}", e.error());
883    ///         let mut db = e.into_inner(); // still open, still holding the writes
884    ///         db.flush()?;                  // e.g. after freeing space
885    ///         db.close()?;
886    ///     }
887    /// }
888    /// # Ok(()) }
889    /// ```
890    pub fn try_close(mut self) -> std::result::Result<(), CloseError> {
891        if !self.read_only {
892            self.index_persist.forced = true;
893            if let Err(error) = self.flush() {
894                return Err(CloseError {
895                    handle: Box::new(self),
896                    error,
897                });
898            }
899        }
900        drop(self);
901        Ok(())
902    }
903
904    /// PERF-1: flush, persisting the ANN index even if the
905    /// [`INDEX_PERSIST_EVERY_COMMITS`] / [`INDEX_PERSIST_EVERY_CHANGES`]
906    /// policy wouldn't yet. Plain [`Mnemo::flush`] writes only the catalog
907    /// between persists; the index is derived, so a crash costs nothing but
908    /// re-assigning the newer records on the next load.
909    pub fn flush_index(&mut self) -> Result<()> {
910        if self.read_only {
911            return Err(MnemoError::ReadOnly);
912        }
913        self.index_persist.forced = true;
914        self.flush()
915    }
916
917    /// **TEST ONLY — do not use.** Reproduces a crash inside
918    /// [`Mnemo::flush`] *after* the prelude has leased counter+page slots
919    /// and persisted the leased header, but *before* the WAL is committed.
920    /// Runs `prepare_for_flush` + `pager.flush` and returns — leaving
921    /// data pages and a leased header on disk, with no commit frame.
922    ///
923    /// Used by `tests/integration.rs::nonce_unique_after_crashed_data_flush`
924    /// to verify that this window (Phase 1.1 of the improvement plan) does
925    /// not enable AES-GCM nonce reuse. Calling this in production code
926    /// strands data pages; never expose it from a binding.
927    #[doc(hidden)]
928    pub fn __crash_partial_flush_for_testing(&mut self) -> Result<()> {
929        if self.read_only {
930            return Err(MnemoError::ReadOnly);
931        }
932        if !self.dirty_catalog && !self.dirty_index {
933            return Ok(());
934        }
935        // FMT-9b: v9 records and vectors reach their pages at the top of a
936        // flush; do that part too.
937        self.ensure_gen_lease()?;
938        self.pack_records()?;
939        self.pack_vectors()?;
940        let _prelude = self.prepare_for_flush(self.dirty_index)?;
941        self.pager.flush()
942    }
943
944    /// Bound the in-memory page cache to `pages` decrypted pages.
945    ///
946    /// The cache holds decrypted page payloads to speed repeated reads. By
947    /// default it is capped at 1024 pages (~8 MiB; 8192 before v0.10.0).
948    /// Lower the cap to trade hit rate for a smaller footprint, or raise
949    /// it for a hotter cache. The
950    /// cap governs *clean* pages — pages with un-flushed writes are always
951    /// retained until [`Mnemo::flush`], regardless of the cap.
952    pub fn set_cache_capacity(&mut self, pages: usize) {
953        self.pager.set_cache_capacity(pages);
954    }
955
956    /// FMT-9b (v9 files): keep the fp16 vector column in memory while it
957    /// takes at most `bytes` (default [`DEFAULT_VECTOR_CACHE_BUDGET`],
958    /// 96 MiB, about 125K vectors at 384 dims). Above it, recall reads
959    /// vector entries through the page cache instead: less memory, slower
960    /// recall. Lowering it below the resident size drops the resident copy.
961    pub fn set_vector_cache_budget(&mut self, bytes: usize) {
962        self.vector_cache_budget = bytes;
963        let need = self.col.scored_rows * veccol::entry_len(self.dimensions);
964        if self.col.resident && need > bytes {
965            self.col.data = Vec::new();
966            self.col.norms = Vec::new();
967            self.col.have = Vec::new();
968            self.col.resident = false;
969        }
970    }
971
972    /// Page-cache occupancy: `(pages_cached, capacity)`. Renamed from
973    /// `cache_stats` in v0.4.0: the result-cache API (Phase 10.1) took
974    /// that name for its per-namespace [`CacheStats`] summary, and the
975    /// page-cache pair is the older/less-user-facing of the two, so it
976    /// gets the more-specific name.
977    pub fn page_cache_stats(&self) -> (usize, usize) {
978        self.pager.cache_stats()
979    }
980
981    // === Result cache (Phase 10.1 + 10.3) ============================
982}