From 162efbe4f7cfff140f105b83f028eac4b5c61bad Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 23 Nov 2026 14:39:19 +0100 Subject: [PATCH 1/2] store: write the manifest before the beatree pages, logging the value changes The manifest used to wait for the beatree update (about 60 ms) before the hash-table pages could be written. Now each sync writes its value changeset to a small log (about 2 MB) alongside the hash-table WAL and the rollback delta, and writes the manifest once those are durable. The manifest keeps the previous beatree state and marks the log as pending (meta version 2). The hash-table writeout then runs while the beatree update finishes, and a second manifest write records the new beatree state. On open, a pending log is applied to the recorded beatree state; the beatree is copy-on-write, so pages written by the interrupted sync are free in that state. Co-Authored-By: Claude Opus 5.5 --- nomt/src/bitbox/rehash.rs | 8 +-- nomt/src/store/meta.rs | 30 +++++++- nomt/src/store/mod.rs | 43 ++++++++++- nomt/src/store/sync.rs | 138 ++++++++++++++++++++++-------------- nomt/src/store/value_log.rs | 86 ++++++++++++++++++++++ 5 files changed, 242 insertions(+), 63 deletions(-) create mode 100644 nomt/src/store/value_log.rs diff --git a/nomt/src/bitbox/rehash.rs b/nomt/src/bitbox/rehash.rs index 4fa393850d..4523eaa356 100644 --- a/nomt/src/bitbox/rehash.rs +++ b/nomt/src/bitbox/rehash.rs @@ -69,7 +69,7 @@ pub(crate) fn finish_pending_rehash(path: &Path, page_pool: &PagePool) -> anyhow .write(true) .open(&meta_path) .with_context(|| format!("failed to open {}", meta_path.display()))?; - let mut meta = Meta::read(page_pool, &meta_fd) + let (mut meta, pending_value_log) = Meta::read_with_pending(page_pool, &meta_fd) .with_context(|| format!("failed to read {}", meta_path.display()))?; meta.validate()?; @@ -93,7 +93,7 @@ pub(crate) fn finish_pending_rehash(path: &Path, page_pool: &PagePool) -> anyhow } n if n == marker.old_num_pages && ht_len == new_len => { meta.bitbox_num_pages = marker.new_num_pages; - Meta::write(page_pool, &meta_fd, &meta) + Meta::write_with_pending(page_pool, &meta_fd, &meta, pending_value_log) .context("failed to finish pending rehash metadata update")?; } n if n == marker.old_num_pages && ht_len == old_len => { @@ -135,7 +135,7 @@ pub(crate) fn grow_hashtable( .write(true) .open(&meta_path) .with_context(|| format!("failed to open {}", meta_path.display()))?; - let mut meta = Meta::read(page_pool, &meta_fd) + let (mut meta, pending_value_log) = Meta::read_with_pending(page_pool, &meta_fd) .with_context(|| format!("failed to read {}", meta_path.display()))?; meta.validate()?; @@ -166,7 +166,7 @@ pub(crate) fn grow_hashtable( sync_dir(path)?; meta.bitbox_num_pages = new_num_pages; - Meta::write(page_pool, &meta_fd, &meta).context("failed to update NOMT metadata")?; + Meta::write_with_pending(page_pool, &meta_fd, &meta, pending_value_log).context("failed to update NOMT metadata")?; remove_file_if_exists(&path.join(MARKER_FILE))?; sync_dir(path)?; diff --git a/nomt/src/store/meta.rs b/nomt/src/store/meta.rs index 94d125f193..c2bf4b21dd 100644 --- a/nomt/src/store/meta.rs +++ b/nomt/src/store/meta.rs @@ -6,7 +6,8 @@ use std::os::unix::fs::FileExt as _; use crate::io::{self, PagePool}; pub(crate) const MAGIC: [u8; 4] = *b"NOMT"; -pub(crate) const VERSION: u32 = 1; +/// Version 2 adds the pending value log marker after the encoded [`Meta`]. +pub(crate) const VERSION: u32 = 2; pub(crate) const META_SIZE: usize = 64; /// This data structure describes the state of the btree. @@ -138,16 +139,39 @@ impl Meta { } pub fn read(page_pool: &PagePool, fd: &File) -> std::io::Result { + Ok(Self::read_with_pending(page_pool, fd)?.0) + } + + /// Reads the meta and the sync seqn of the pending value log, 0 if none. + pub fn read_with_pending(page_pool: &PagePool, fd: &File) -> std::io::Result<(Self, u32)> { let page = io::read_page(page_pool, fd, 0)?; let meta = Meta::decode(&page[..META_SIZE]); - Ok(meta) + let pending = if meta.version >= 2 { + u32::from_le_bytes(page[META_SIZE..META_SIZE + 4].try_into().unwrap()) + } else { + 0 + }; + Ok((meta, pending)) } pub fn write(page_pool: &PagePool, fd: &File, meta: &Meta) -> std::io::Result<()> { + Self::write_with_pending(page_pool, fd, meta, 0) + } + + /// Writes the meta, marking the value log of sync `pending` as not yet applied to the + /// beatree pages. 0 means none. + pub fn write_with_pending( + page_pool: &PagePool, + fd: &File, + meta: &Meta, + pending: u32, + ) -> std::io::Result<()> { let mut page = page_pool.alloc_fat_page(); + page.fill(0); meta.encode_to(&mut page.as_mut()[..META_SIZE]); + page[META_SIZE..META_SIZE + 4].copy_from_slice(&pending.to_le_bytes()); fd.write_all_at(&page[..], 0)?; - fd.sync_all()?; + fd.sync_data()?; Ok(()) } } diff --git a/nomt/src/store/mod.rs b/nomt/src/store/mod.rs index a3f986baae..1c7db96d26 100644 --- a/nomt/src/store/mod.rs +++ b/nomt/src/store/mod.rs @@ -30,6 +30,7 @@ mod flock; pub(crate) mod meta; mod page_loader; mod sync; +mod value_log; /// This is a lightweight handle and can be cloned cheaply. #[derive(Clone)] @@ -44,6 +45,7 @@ struct Shared { rollback: Option, io_pool: IoPool, meta_fd: File, + value_log_fd: File, flock: Option, poisoned: AtomicBool, @@ -146,7 +148,15 @@ impl Store { } } - let meta = meta::Meta::read(&page_pool, &meta_fd)?; + let value_log_fd = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .open(&o.path.join("value_log"))?; + // A manifest may reference the log, so its directory entry must be durable. + db_dir_fd.sync_all()?; + + let (mut meta, pending_value_log) = meta::Meta::read_with_pending(&page_pool, &meta_fd)?; meta.validate()?; let values = beatree::Tree::open( page_pool.clone(), @@ -180,12 +190,42 @@ impl Store { ) }) .transpose()?; + + // The last sync wrote its manifest but maybe not its beatree pages: apply its changeset + // to the beatree state the manifest records. + if pending_value_log != 0 { + if pending_value_log != meta.sync_seqn { + anyhow::bail!( + "pending value log {} does not match sync {}", + pending_value_log, + meta.sync_seqn + ); + } + let changeset = value_log::read(&value_log_fd, pending_value_log)?; + let mut beatree_sync = values.sync(); + beatree_sync.begin_sync(changeset); + let beatree_meta = beatree_sync.wait_pre_meta()?; + meta.version = meta::VERSION; + meta.ln_freelist_pn = beatree_meta.ln_freelist_pn; + meta.ln_bump = beatree_meta.ln_bump; + meta.bbn_freelist_pn = beatree_meta.bbn_freelist_pn; + meta.bbn_bump = beatree_meta.bbn_bump; + Meta::write(&page_pool, &meta_fd, &meta)?; + crate::task::join_task(&beatree_sync.post_meta()); + } + Ok(Self { sync: Arc::new(Mutex::new(sync::Sync::new( meta.sync_seqn, meta.bitbox_num_pages, meta.bitbox_seed, o.panic_on_sync, + beatree::SyncData { + ln_freelist_pn: meta.ln_freelist_pn, + ln_bump: meta.ln_bump, + bbn_freelist_pn: meta.bbn_freelist_pn, + bbn_bump: meta.bbn_bump, + }, ))), shared: Arc::new(Shared { rollback, @@ -194,6 +234,7 @@ impl Store { io_pool, _db_dir_fd: db_dir_fd, meta_fd, + value_log_fd, flock: Some(flock), poisoned: false.into(), }), diff --git a/nomt/src/store/sync.rs b/nomt/src/store/sync.rs index 12b53b01d5..c503883621 100644 --- a/nomt/src/store/sync.rs +++ b/nomt/src/store/sync.rs @@ -2,7 +2,7 @@ use nomt_core::page_id::PageId; use super::{ meta::{self, Meta}, - DirtyPage, Shared, + value_log, DirtyPage, Shared, }; use crate::{ beatree, bitbox, options::PanicOnSyncMode, page_cache::PageCache, rollback, task::join_task, @@ -13,6 +13,8 @@ pub struct Sync { pub(crate) bitbox_num_pages: u32, pub(crate) bitbox_seed: [u8; 16], pub(crate) panic_on_sync: Option, + /// The beatree state recorded in the last manifest. + pub(crate) beatree: beatree::SyncData, } impl Sync { @@ -21,15 +23,23 @@ impl Sync { bitbox_num_pages: u32, bitbox_seed: [u8; 16], panic_on_sync: Option, + beatree: beatree::SyncData, ) -> Self { Self { sync_seqn, bitbox_num_pages, bitbox_seed, panic_on_sync, + beatree, } } + /// Commits the changes. + /// + /// The manifest is written as soon as the hash-table WAL, the rollback delta and the value log + /// are durable, without waiting for the beatree pages. It records the previous beatree state + /// and marks the value log as pending. The hash-table pages are then written while the beatree + /// update finishes, and a second manifest write records the new beatree state. pub fn sync( &mut self, shared: &Shared, @@ -48,63 +58,81 @@ impl Sync { let mut rollback_sync = rollback.as_ref().map(|rollback| rollback.sync()); bitbox_sync.begin_sync(sync_seqn, page_cache, updated_pages); - beatree_sync.begin_sync(value_tx); - - // Persist the rollback delta while the trees are being prepared. All of them must - // succeed before the manifest references their new state. - let rollback_result = match rollback_delta { - // UNWRAP: a rollback delta is only produced when rollback is enabled. - Some(delta) => rollback.as_ref().unwrap().commit(delta), - None => Ok(()), - }; - let bitbox_result = bitbox_sync.wait_pre_meta(); - let beatree_result = beatree_sync.wait_pre_meta(); - rollback_result?; - bitbox_result?; - let beatree_meta_wd = beatree_result?; - - let (rollback_start_live, rollback_end_live) = match rollback_sync { - Some(ref mut rollback) => rollback.begin_sync(), - None => (0, 0), - }; - - if let Some(PanicOnSyncMode::PostWal) = self.panic_on_sync { - panic!("panic_on_sync is true (post-wal)") - } - let new_meta = Meta { - magic: meta::MAGIC, - version: meta::VERSION, - ln_freelist_pn: beatree_meta_wd.ln_freelist_pn, - ln_bump: beatree_meta_wd.ln_bump, - bbn_freelist_pn: beatree_meta_wd.bbn_freelist_pn, - bbn_bump: beatree_meta_wd.bbn_bump, - sync_seqn, - bitbox_num_pages: self.bitbox_num_pages, - bitbox_seed: self.bitbox_seed, - rollback_start_live, - rollback_end_live, - }; - Meta::write(&shared.io_pool.page_pool(), &shared.meta_fd, &new_meta)?; - self.sync_seqn += 1; - - if let Some(PanicOnSyncMode::PostMeta) = self.panic_on_sync { - panic!("panic_on_sync is true (post-meta)"); - } + let changeset: Vec<_> = value_tx.into_iter().collect(); + let value_log = value_log::encode(sync_seqn, &changeset); + beatree_sync.begin_sync(changeset); - if let Some(ref mut rollback) = rollback_sync { - rollback.post_meta(); - } + std::thread::scope(|s| -> anyhow::Result<()> { + let value_log_write = s.spawn(|| value_log::write(&shared.value_log_fd, &value_log)); - // Finish the beatree sync while the hash-table pages are written out. - let beatree_post_meta = beatree_sync.post_meta(); - let bitbox_result = bitbox_sync.post_meta(shared.io_pool.make_handle()); - join_task(&beatree_post_meta); - bitbox_result?; + // Persist the rollback delta while the trees are being prepared. All of them must + // succeed before the manifest references their new state. + let rollback_result = match rollback_delta { + // UNWRAP: a rollback delta is only produced when rollback is enabled. + Some(delta) => rollback.as_ref().unwrap().commit(delta), + None => Ok(()), + }; + let bitbox_result = bitbox_sync.wait_pre_meta(); + // UNWRAP: the writer does not panic. + let value_log_result = value_log_write.join().unwrap(); + rollback_result?; + bitbox_result?; + value_log_result?; - if let Some(ref rollback) = rollback_sync { - rollback.wait_post_meta()?; - } - Ok(()) + let (rollback_start_live, rollback_end_live) = match rollback_sync { + Some(ref mut rollback) => rollback.begin_sync(), + None => (0, 0), + }; + + if let Some(PanicOnSyncMode::PostWal) = self.panic_on_sync { + panic!("panic_on_sync is true (post-wal)") + } + + let mut new_meta = Meta { + magic: meta::MAGIC, + version: meta::VERSION, + ln_freelist_pn: self.beatree.ln_freelist_pn, + ln_bump: self.beatree.ln_bump, + bbn_freelist_pn: self.beatree.bbn_freelist_pn, + bbn_bump: self.beatree.bbn_bump, + sync_seqn, + bitbox_num_pages: self.bitbox_num_pages, + bitbox_seed: self.bitbox_seed, + rollback_start_live, + rollback_end_live, + }; + let page_pool = shared.io_pool.page_pool(); + Meta::write_with_pending(&page_pool, &shared.meta_fd, &new_meta, sync_seqn)?; + self.sync_seqn += 1; + + if let Some(ref mut rollback) = rollback_sync { + rollback.post_meta(); + } + + // Write out the hash-table pages while the beatree update completes. + let ht_writeout = s.spawn(|| bitbox_sync.post_meta(shared.io_pool.make_handle())); + + let beatree_result = beatree_sync.wait_pre_meta(); + if let Some(PanicOnSyncMode::PostMeta) = self.panic_on_sync { + panic!("panic_on_sync is true (post-meta)"); + } + let beatree_meta = beatree_result?; + new_meta.ln_freelist_pn = beatree_meta.ln_freelist_pn; + new_meta.ln_bump = beatree_meta.ln_bump; + new_meta.bbn_freelist_pn = beatree_meta.bbn_freelist_pn; + new_meta.bbn_bump = beatree_meta.bbn_bump; + Meta::write(&page_pool, &shared.meta_fd, &new_meta)?; + self.beatree = beatree_meta; + + join_task(&beatree_sync.post_meta()); + // UNWRAP: the writeout does not panic. + ht_writeout.join().unwrap()?; + + if let Some(ref rollback) = rollback_sync { + rollback.wait_post_meta()?; + } + Ok(()) + }) } } diff --git a/nomt/src/store/value_log.rs b/nomt/src/store/value_log.rs new file mode 100644 index 0000000000..43f8f1b61f --- /dev/null +++ b/nomt/src/store/value_log.rs @@ -0,0 +1,86 @@ +//! The value log holds the beatree changeset of the latest sync. +//! +//! A sync makes the log durable before the manifest, so the manifest can be written before the +//! beatree pages are. Until the beatree pages are durable, the manifest marks the log as pending +//! and recovery applies it to the previous beatree state. + +use crate::beatree::{Key, ValueChange}; +use std::{fs::File, os::unix::fs::FileExt as _}; + +const DELETE: u8 = 0; +const INSERT: u8 = 1; +const INSERT_OVERFLOW: u8 = 2; + +/// Encodes the changeset of sync `sync_seqn`. +pub fn encode(sync_seqn: u32, changeset: &[(Key, ValueChange)]) -> Vec { + let mut buf = Vec::with_capacity(16 + changeset.len() * 64); + buf.extend_from_slice(&sync_seqn.to_le_bytes()); + buf.extend_from_slice(&(changeset.len() as u64).to_le_bytes()); + for (key, change) in changeset { + buf.extend_from_slice(key); + match change { + ValueChange::Delete => buf.push(DELETE), + ValueChange::Insert(value) => { + buf.push(INSERT); + buf.extend_from_slice(&(value.len() as u32).to_le_bytes()); + buf.extend_from_slice(value); + } + ValueChange::InsertOverflow(value, hash) => { + buf.push(INSERT_OVERFLOW); + buf.extend_from_slice(&(value.len() as u32).to_le_bytes()); + buf.extend_from_slice(value); + buf.extend_from_slice(hash); + } + } + } + buf +} + +/// Replaces the log contents and makes them durable. +pub fn write(fd: &File, buf: &[u8]) -> std::io::Result<()> { + fd.write_all_at(buf, 0)?; + fd.set_len(buf.len() as u64)?; + fd.sync_data() +} + +/// Reads the changeset of sync `sync_seqn`. +pub fn read(fd: &File, sync_seqn: u32) -> anyhow::Result> { + let len = fd.metadata()?.len() as usize; + let mut buf = vec![0; len]; + fd.read_exact_at(&mut buf, 0)?; + + let mut pos = 0; + let mut take = |n: usize| -> anyhow::Result<&[u8]> { + let bytes = buf + .get(pos..pos + n) + .ok_or_else(|| anyhow::anyhow!("value log truncated"))?; + pos += n; + Ok(bytes) + }; + let u32_at = |b: &[u8]| u32::from_le_bytes(b.try_into().unwrap()); + + let log_seqn = u32_at(take(4)?); + if log_seqn != sync_seqn { + anyhow::bail!("value log is for sync {log_seqn}, expected {sync_seqn}"); + } + let count = u64::from_le_bytes(take(8)?.try_into().unwrap()) as usize; + let mut changeset = Vec::with_capacity(count); + for _ in 0..count { + let key: Key = take(32)?.try_into().unwrap(); + let change = match take(1)?[0] { + DELETE => ValueChange::Delete, + INSERT => { + let len = u32_at(take(4)?) as usize; + ValueChange::Insert(take(len)?.to_vec()) + } + INSERT_OVERFLOW => { + let len = u32_at(take(4)?) as usize; + let value = take(len)?.to_vec(); + ValueChange::InsertOverflow(value, take(32)?.try_into().unwrap()) + } + tag => anyhow::bail!("invalid value log entry tag {tag}"), + }; + changeset.push((key, change)); + } + Ok(changeset) +} From 7faedf5349ad2b673863a4a975b5ba091e03b10e Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 23 Nov 2026 14:40:30 +0100 Subject: [PATCH 2/2] store: write out the hash-table pages through their own I/O pool Co-Authored-By: Claude Opus 5.5 --- nomt/src/store/mod.rs | 6 ++++++ nomt/src/store/sync.rs | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/nomt/src/store/mod.rs b/nomt/src/store/mod.rs index 1c7db96d26..9ec8f00379 100644 --- a/nomt/src/store/mod.rs +++ b/nomt/src/store/mod.rs @@ -44,6 +44,9 @@ struct Shared { pages: bitbox::DB, rollback: Option, io_pool: IoPool, + /// Writes out the hash-table pages after the manifest, so the beatree update that runs + /// meanwhile does not queue behind them. + ht_io_pool: IoPool, meta_fd: File, value_log_fd: File, flock: Option, @@ -88,6 +91,7 @@ impl Store { } let io_pool = io::start_io_pool(o.io_workers, page_pool.clone()); + let ht_io_pool = io::start_io_pool(o.io_workers, page_pool.clone()); let meta_fd = { let mut options = OpenOptions::new(); @@ -232,6 +236,7 @@ impl Store { values, pages, io_pool, + ht_io_pool, _db_dir_fd: db_dir_fd, meta_fd, value_log_fd, @@ -358,6 +363,7 @@ impl Drop for Shared { // Otherwise, these IO workers might still be writing to the files while another process // acquired the flock. self.io_pool.shutdown(); + self.ht_io_pool.shutdown(); drop(self.flock.take()); } } diff --git a/nomt/src/store/sync.rs b/nomt/src/store/sync.rs index c503883621..a1f12326e8 100644 --- a/nomt/src/store/sync.rs +++ b/nomt/src/store/sync.rs @@ -111,7 +111,7 @@ impl Sync { } // Write out the hash-table pages while the beatree update completes. - let ht_writeout = s.spawn(|| bitbox_sync.post_meta(shared.io_pool.make_handle())); + let ht_writeout = s.spawn(|| bitbox_sync.post_meta(shared.ht_io_pool.make_handle())); let beatree_result = beatree_sync.wait_pre_meta(); if let Some(PanicOnSyncMode::PostMeta) = self.panic_on_sync {