From 63d3791a041f3014bd47f3f5ccf23ce11a5baa22 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 23 Nov 2026 16:11:55 +0100 Subject: [PATCH 1/9] rollback: leave the log untouched when a rollback fails before its commit Nomt::rollback popped the deltas from the in-memory log and set pending_truncate before running the session that restores the old values. If that session failed, for example on a read error, the store was not poisoned and stayed usable, but the log had already lost the deltas. The next ordinary commit then took the stale pending_truncate and pruned live records, and a later rollback restored the wrong state. Read the prior values without consuming the log, and truncate it only once the session has finished. From there on the only failure left is in Store::commit, which poisons the store. The test fails a rollback by making merkle page reads fail, commits, reopens, and checks that rolling back that commit restores the root from before it. Co-Authored-By: Claude Mythos 5.2 --- nomt/src/lib.rs | 9 ++- nomt/src/rollback/mod.rs | 16 +++++ nomt/tests/rollback_failure.rs | 118 +++++++++++++++++++++++++++++++++ 3 files changed, 141 insertions(+), 2 deletions(-) create mode 100644 nomt/tests/rollback_failure.rs diff --git a/nomt/src/lib.rs b/nomt/src/lib.rs index 1e82e2cf21..21ca979d3c 100644 --- a/nomt/src/lib.rs +++ b/nomt/src/lib.rs @@ -377,7 +377,7 @@ impl Nomt { let Some(rollback) = self.store.rollback() else { anyhow::bail!("rollback: not enabled"); }; - let Some(traceback) = rollback.truncate(n)? else { + let Some(traceback) = rollback.traceback(n) else { anyhow::bail!("rollback: not enough logged for rolling back"); }; @@ -399,7 +399,12 @@ impl Nomt { actuals.push((key, value)); } - sess.finish(actuals)?.commit(&self)?; + let finished = sess.finish(actuals)?; + + // Only now consume the log: a failure above leaves the store usable, so it must leave + // the log as it was. A failure below poisons the store. + rollback.truncate(n)?; + finished.commit(&self)?; Ok(()) } diff --git a/nomt/src/rollback/mod.rs b/nomt/src/rollback/mod.rs index 83f47c9df6..6b851e356f 100644 --- a/nomt/src/rollback/mod.rs +++ b/nomt/src/rollback/mod.rs @@ -164,6 +164,22 @@ impl Rollback { Ok(()) } + /// Returns what [`Self::truncate`] would return for `n`, without touching the rollback log. + pub fn traceback(&self, n: usize) -> Option>>> { + let in_memory = self.shared.in_memory.lock(); + if n > in_memory.total_len() { + return None; + } + + let mut traceback = BTreeMap::new(); + for (_, delta) in in_memory.log.iter().rev().take(n) { + for (key, value) in &delta.priors { + traceback.insert(*key, value.clone()); + } + } + Some(traceback) + } + /// Truncates the rollback log by removing the last `n` deltas. /// /// This function returns the keys and values that we should apply to the database to restore diff --git a/nomt/tests/rollback_failure.rs b/nomt/tests/rollback_failure.rs new file mode 100644 index 0000000000..5b554b4fb0 --- /dev/null +++ b/nomt/tests/rollback_failure.rs @@ -0,0 +1,118 @@ +use nomt::{hasher::Blake3Hasher, KeyReadWrite, Nomt, Options, Root, SessionParams}; +use nomt_test_utils::account_path; +use std::{ + ffi::CString, + path::{Path, PathBuf}, + sync::mpsc, + time::Duration, +}; + +fn open(path: &Path) -> Nomt { + let mut o = Options::new(); + o.path(path); + o.commit_concurrency(1); + o.io_workers(1); + o.bitbox_seed([0; 16]); + o.hashtable_buckets(64_000); + o.rollback(true); + Nomt::open(o).unwrap() +} + +fn commit(nomt: &Nomt, writes: impl IntoIterator) -> Root { + let session = nomt.begin_session(SessionParams::default()); + let mut actuals = writes + .into_iter() + .map(|(id, v)| { + ( + account_path(id), + KeyReadWrite::Write(Some(v.to_le_bytes().to_vec())), + ) + }) + .collect::>(); + actuals.sort_by_key(|(k, _)| *k); + let finished = session.finish(actuals).unwrap(); + finished.commit(nomt).unwrap(); + nomt.root() +} + +fn fd_of(path: &Path) -> i32 { + let target = std::fs::canonicalize(path).unwrap(); + for entry in std::fs::read_dir("/proc/self/fd").unwrap() { + let entry = entry.unwrap(); + if std::fs::read_link(entry.path()).map_or(false, |l| l == target) { + return entry.file_name().to_str().unwrap().parse().unwrap(); + } + } + panic!("no open fd for {}", path.display()); +} + +fn with_failing_reads(fd: i32, f: impl FnOnce() -> R) -> R { + let null = CString::new("/dev/null").unwrap(); + let saved = unsafe { + let saved = libc::dup(fd); + assert!(saved >= 0); + let wronly = libc::open(null.as_ptr(), libc::O_WRONLY); + assert!(wronly >= 0); + assert_eq!(libc::dup2(wronly, fd), fd); + libc::close(wronly); + saved + }; + let r = f(); + unsafe { + assert_eq!(libc::dup2(saved, fd), fd); + libc::close(saved); + } + r +} + +#[test] +fn failed_rollback_leaves_the_log_intact() { + let path = PathBuf::from("test/failed_rollback_leaves_the_log_intact"); + let _ = std::fs::remove_dir_all(&path); + + let nomt = open(&path); + commit(&nomt, (0..2000).map(|i| (i, 1000))); + commit(&nomt, [(7, 1)]); + let root_3 = commit(&nomt, [(9, 2)]); + drop(nomt); + + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let nomt = open(&path); + let ht_fd = fd_of(&path.join("ht")); + let failed = with_failing_reads(ht_fd, || { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| nomt.rollback(1))) + }); + let failed = match failed { + Ok(Ok(())) => "ok".to_string(), + Ok(Err(e)) => format!("err: {e:#}"), + Err(_) => "panic".to_string(), + }; + let after_failure = (nomt.is_poisoned(), nomt.root()); + + let commit_4 = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| commit(&nomt, [(11, 3)]))) + .is_ok(); + drop(nomt); + + let nomt = open(&path); + let rollback = nomt.rollback(1).map_err(|e| format!("{e:#}")); + let _ = tx.send((failed, after_failure, commit_4, rollback, nomt.root())); + }); + let (failed, (poisoned, root_after_failure), commit_4, rollback, root_after_rollback) = + rx.recv_timeout(Duration::from_secs(120)).expect("hung"); + + eprintln!("rollback(1) with failing merkle reads: {failed}; poisoned: {poisoned}"); + assert!( + failed.starts_with("err"), + "fault injection did not produce an Err" + ); + assert!(!poisoned); + assert_eq!(root_after_failure, root_3); + assert!(commit_4, "commit after the failed rollback failed"); + eprintln!("rollback(1) after reopen: {rollback:?}"); + assert_eq!( + root_after_rollback, root_3, + "rollback(1) after [failed rollback(1), commit, reopen] did not undo that commit" + ); +} From 246b40acdf58a4791f5ba1cabd1d19290066315f Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 23 Nov 2026 16:13:06 +0100 Subject: [PATCH 2/9] beatree: don't request overflow pages whose numbers are not known yet An overflow cell holds at most 15 page numbers. The numbers of the remaining pages are stored in the first overflow pages and become known as those are read. AsyncReader::submit only stopped once it had requested the total number of pages, so a caller that submits ahead of the completions indexed past the page numbers it had. The rollback worker does that when it fetches the prior value of a key whose leaf is not cached: for a value of more than 15 pages it panicked with an index out of bounds. The panic was raised again while unwinding through ReverseDeltaBuilder::drop and aborted the process. After a restart the cache is cold again, so overwriting or deleting such a value kept aborting. Stop at the last known page number instead. The remaining pages are requested when the completions that carry their numbers arrive. The test deletes a 100 kB value in a fresh process with rollback enabled, rolls the deletion back and reads the value. Co-Authored-By: Claude Mythos 5.2 --- nomt/src/beatree/ops/overflow.rs | 10 ++-- nomt/tests/rollback_large_value.rs | 75 ++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 6 deletions(-) create mode 100644 nomt/tests/rollback_large_value.rs diff --git a/nomt/src/beatree/ops/overflow.rs b/nomt/src/beatree/ops/overflow.rs index 527130cb34..087368fb12 100644 --- a/nomt/src/beatree/ops/overflow.rs +++ b/nomt/src/beatree/ops/overflow.rs @@ -237,9 +237,11 @@ impl AsyncReader { /// Submit a request over the I/O handle. /// - /// Returns `Some` with an index if a request was submitted. Otherwise, `None`. + /// Returns `Some` with an index if a request was submitted. Otherwise, `None`: either every + /// page has been requested, or the numbers of the remaining pages are in pages that have not + /// been completed yet. pub fn submit(&mut self, io_handle: &IoHandle, user_data: u64) -> Option { - if self.is_done_requesting() { + if self.request_index == self.pages.len() { return None; } @@ -275,10 +277,6 @@ impl AsyncReader { } } - fn is_done_requesting(&self) -> bool { - self.request_index == self.total_pages - } - fn is_done(&self) -> bool { self.process_index == self.total_pages } diff --git a/nomt/tests/rollback_large_value.rs b/nomt/tests/rollback_large_value.rs new file mode 100644 index 0000000000..56e464c599 --- /dev/null +++ b/nomt/tests/rollback_large_value.rs @@ -0,0 +1,75 @@ +use nomt::{hasher::Blake3Hasher, KeyReadWrite, Nomt, Options, SessionParams}; +use std::path::Path; + +fn open(path: &Path) -> Nomt { + let mut o = Options::new(); + o.path(path); + o.commit_concurrency(1); + o.io_workers(1); + o.bitbox_seed([0; 16]); + o.hashtable_buckets(4096); + o.rollback(true); + o.warm_up(false); + Nomt::open(o).unwrap() +} + +fn write(nomt: &Nomt, key: [u8; 32], value: Option>) { + nomt.begin_session(SessionParams::default()) + .finish(vec![(key, KeyReadWrite::Write(value))]) + .unwrap() + .commit(nomt) + .unwrap(); +} + +const KEY: [u8; 32] = [0x42; 32]; +const CHILD: &str = "LARGE_PRIOR_CHILD"; + +#[test] +fn prior_of_large_overflow_value_is_fetched() { + use std::os::unix::process::ExitStatusExt as _; + + let path = std::path::PathBuf::from("test/prior_of_large_overflow_value"); + if std::env::var_os(CHILD).is_some() { + let nomt = open(&path); + let session = nomt.begin_session(SessionParams::default()); + session.preserve_prior_value(KEY); + let finished = session.finish(vec![(KEY, KeyReadWrite::Write(None))]); + eprintln!("child: finish returned is_ok={}", finished.is_ok()); + finished.unwrap().commit(&nomt).unwrap(); + nomt.rollback(1).unwrap(); + assert_eq!(nomt.read(KEY).unwrap(), Some(vec![7u8; 100_000])); + return; + } + + let _ = std::fs::remove_dir_all(&path); + let nomt = open(&path); + write(&nomt, KEY, Some(vec![7u8; 100_000])); + write(&nomt, [0x01; 32], Some(vec![1])); + write(&nomt, [0xf1; 32], Some(vec![2])); + drop(nomt); + + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "prior_of_large_overflow_value_is_fetched", + "--nocapture", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + for line in stderr.lines().filter(|l| { + l.contains("panicked") + || l.contains("index out of") + || l.contains("abort") + || l.contains("child:") + }) { + eprintln!("child stderr: {line}"); + } + assert!( + out.status.success(), + "deleting a 100 kB value with a cold leaf cache killed the process: signal {:?}, code {:?}", + out.status.signal(), + out.status.code() + ); +} From a05b13404f6b5667e800d3e765832d313079b7e9 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 23 Nov 2026 16:16:16 +0100 Subject: [PATCH 3/9] io: classify io_uring completion errors by the code in the completion A failed completion was mapped to -1 and handed to IoKind::get_result, which is written for pread/pwrite and decides between retry and error from the thread's errno. io_uring reports the error in the completion and leaves errno alone, so the decision depended on whatever the worker thread's last failing syscall was. An EINTR completion could be reported as an error, and a real error such as EIO was retried, again and again, if errno still held EINTR from an interrupted submit. Decide from the completion's own code. This is the change of 3e97222 on nikolai/hardenings-and-nice-to-haves, moved into a function so that it can be tested: the test sets errno to the opposite of what the completion carries. Co-Authored-By: Claude Mythos 5.2 --- nomt/src/io/linux.rs | 52 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/nomt/src/io/linux.rs b/nomt/src/io/linux.rs index a9796bacf1..5a9a48001a 100644 --- a/nomt/src/io/linux.rs +++ b/nomt/src/io/linux.rs @@ -95,14 +95,9 @@ fn run_worker(page_pool: PagePool, command_rx: Receiver) { completion_sender, } = pending.remove(completion_event.user_data() as usize); - // io_uring never uses errno to pass back error information. - // Instead, completion_event.result() will contain what the equivalent - // system call would have returned in case of success, - // and in case of error completion_event.result() will contain -errno let io_uring_res = completion_event.result(); - let syscall_result = if io_uring_res >= 0 { io_uring_res } else { -1 }; - let result = match command.kind.get_result(syscall_result as isize) { + let result = match completion_result(&command.kind, io_uring_res) { IoKindResult::Ok => Ok(()), IoKindResult::Err => Err(std::io::Error::from_raw_os_error(io_uring_res.abs())), IoKindResult::Retry => { @@ -215,3 +210,48 @@ fn submission_entry(command: &mut IoCommand) -> squeue::Entry { } } } + +/// Classifies the result of a completion. +/// +/// io_uring never uses errno to pass back error information. Instead, the result is what the +/// equivalent system call would have returned in case of success, and `-errno` in case of error. +fn completion_result(kind: &IoKind, io_uring_res: i32) -> IoKindResult { + if io_uring_res >= 0 { + kind.get_result(io_uring_res as isize) + } else if io_uring_res == -libc::EINTR { + IoKindResult::Retry + } else { + IoKindResult::Err + } +} + +#[cfg(test)] +mod tests { + use super::{completion_result, IoKind, IoKindResult, PagePool, PAGE_SIZE}; + + fn set_errno(errno: i32) { + unsafe { *libc::__errno_location() = errno }; + } + + #[test] + fn completion_error_does_not_depend_on_errno() { + let kind = IoKind::Read(0, 0, PagePool::new().alloc_fat_page()); + + set_errno(libc::EINTR); + assert!(matches!( + completion_result(&kind, -libc::EIO), + IoKindResult::Err + )); + + set_errno(libc::EIO); + assert!(matches!( + completion_result(&kind, -libc::EINTR), + IoKindResult::Retry + )); + + assert!(matches!( + completion_result(&kind, PAGE_SIZE as i32), + IoKindResult::Ok + )); + } +} From 1a8408040ca40734ab3fef1707445a52faf883a4 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 23 Nov 2026 16:19:27 +0100 Subject: [PATCH 4/9] beatree: derive the branch cell pointer for writing from a mutable borrow BranchNode::cells_mut took the pointer for its mutable slice from `self.page[..].as_ptr()`, a shared borrow of the page, and cast it to `*mut`. BranchNodeBuilder::push_chunk writes the cell offsets through that slice, which is undefined behaviour: the bytes are written through a pointer that only grants read access. The borrow also covered just the first cell, not the n cells the slice spans. Take the pointer with as_mut_ptr() from a borrow of all the cells. Miri reports the write under both Stacked Borrows and Tree Borrows before this change and nothing under Tree Borrows after it: MIRIFLAGS="-Zmiri-disable-isolation -Zmiri-tree-borrows" \ cargo +nightly miri test -p nomt --lib -- \ beatree::branch::node::test::push_chunk Stacked Borrows still flags this test, now at FatPage::deref, which builds a mutable slice from a shared reference (io/page_pool.rs). That is a separate issue and is not changed here. Co-Authored-By: Claude Mythos 5.2 --- nomt/src/beatree/branch/node.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/nomt/src/beatree/branch/node.rs b/nomt/src/beatree/branch/node.rs index 21a3cb80b5..00bd10c467 100644 --- a/nomt/src/beatree/branch/node.rs +++ b/nomt/src/beatree/branch/node.rs @@ -129,8 +129,7 @@ impl BranchNode { // This is ensured to be within the bounds of the page by the assertion above. unsafe { std::slice::from_raw_parts_mut( - self.page[BRANCH_NODE_HEADER_SIZE..BRANCH_NODE_HEADER_SIZE + 2].as_ptr() - as *mut [u8; 2], + self.page[BRANCH_NODE_HEADER_SIZE..cells_end].as_mut_ptr() as *mut [u8; 2], self.n().into(), ) } From 49ad30cd7b1e3a438cde016c05b4bcc7ddfc1624 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 23 Nov 2026 16:49:29 +0100 Subject: [PATCH 5/9] Tie a session to the thread that created it A commit or rollback waits for every live session, and parking_lot's fair RwLock makes new sessions wait behind a queued commit. So that a thread holding a session can still open another one, such a thread takes the read lock recursively. "Holds a session" is tracked per thread, by the thread that created the session. Session was Send, so it could be created on one thread and held by another. That thread did not count as holding a session: its next begin_session or Nomt::read queued behind a waiting commit, and the commit waited for the session the thread held. Neither could proceed. The lock cannot see which thread holds a moved session, so make the move impossible: Session is no longer Send. It stays Sync, so other threads can still read through a shared reference. This is a breaking change for callers that hand a session to another thread, including across an .await on a multi-threaded runtime. torture did that: it opened the session on the runtime thread and moved it into blocking tasks to read and to commit. It now opens the session, reads with scoped threads and commits inside one blocking call. The doc test on Session checks that it is Sync and not Send. The second half failed before this change. Co-Authored-By: Claude Mythos 5.2 --- nomt/src/lib.rs | 27 ++++++++++- torture/src/agent.rs | 110 +++++++++++++++++-------------------------- 2 files changed, 68 insertions(+), 69 deletions(-) diff --git a/nomt/src/lib.rs b/nomt/src/lib.rs index 21ca979d3c..20d7e256d2 100644 --- a/nomt/src/lib.rs +++ b/nomt/src/lib.rs @@ -490,8 +490,7 @@ impl SessionParams { } thread_local! { - /// Live sessions created on this thread. Shared with each session, which may be dropped on - /// another thread. + /// Live sessions on this thread. A session stays on the thread that created it. static THREAD_SESSIONS: Arc = Arc::new(AtomicUsize::new(0)); } @@ -505,9 +504,14 @@ fn thread_has_live_session() -> bool { /// readers wait behind it. That commit waits for every live session, so a thread opening a second /// session would deadlock; such a thread takes the read lock recursively, past the queued writer. /// Every other thread waits, so overlapping sessions can't hold a commit off indefinitely. +/// +/// Which thread holds a session is only known from where it was created, so the guard, and with +/// it the session, must not move to another thread. struct SessionAccessGuard { _guard: ArcRwLockReadGuard, thread_sessions: Arc, + /// `MutexGuard` is `Sync` but not `Send`. + _not_send: std::marker::PhantomData>, } impl SessionAccessGuard { @@ -522,6 +526,7 @@ impl SessionAccessGuard { Self { _guard: guard, thread_sessions, + _not_send: std::marker::PhantomData, } } } @@ -539,6 +544,24 @@ impl Drop for SessionAccessGuard { /// When the session is finished, the application can confirm the changes by calling /// [`Session::finish`] or others and create a [`Witness`] that can be used to prove the /// correctness of replaying the same operations. +/// +/// A session belongs to the thread that created it. Other threads may use it by reference: +/// +/// ``` +/// fn shareable() {} +/// shareable::>(); +/// ``` +/// +/// but it cannot be moved to another thread: +/// +/// ```compile_fail +/// fn movable() {} +/// movable::>(); +/// ``` +/// +/// A commit or rollback waits for every live session, and only the thread that holds one may +/// open another while a commit is waiting. A session held by a different thread than the one +/// that created it would let that thread wait behind the commit that is waiting for it. pub struct Session { store: Store, actuals_concurrency: usize, diff --git a/torture/src/agent.rs b/torture/src/agent.rs index 2220d5bffd..5eba27148b 100644 --- a/torture/src/agent.rs +++ b/torture/src/agent.rs @@ -5,7 +5,6 @@ use nomt::{hasher::Blake3Hasher, Nomt, SessionParams}; use std::future::Future; use std::path::Path; use std::{path::PathBuf, sync::Arc, time::Duration}; -use tokio::task::JoinSet; use tokio::{ io::{BufReader, BufWriter}, net::{ @@ -63,9 +62,7 @@ pub async fn run(input: UnixStream) -> Result<()> { let task = async move { let start = std::time::Instant::now(); - agent.begin_session(); - agent.read(reads, read_concurrency).await; - let _ = agent.commit(changeset).await; + let _ = agent.commit(reads, read_concurrency, changeset).await; let elapsed = start.elapsed(); tracing::info!("commit took {}ms", elapsed.as_millis()); }; @@ -80,9 +77,7 @@ pub async fn run(input: UnixStream) -> Result<()> { should_crash: None, }) => { let start = std::time::Instant::now(); - agent.begin_session(); - agent.read(reads, read_concurrency).await; - let outcome = agent.commit(changeset).await; + let outcome = agent.commit(reads, read_concurrency, changeset).await; let elapsed = start.elapsed(); tracing::info!("commit took {}ms", elapsed.as_millis()); stream @@ -313,24 +308,18 @@ async fn initialize(stream: &mut Stream) -> Result { struct Agent { nomt: Option>, - session: Option>, } impl Agent { fn new() -> Self { - Self { - nomt: None, - session: None, - } + Self { nomt: None } } /// Open a NOMT instance at the specified path with the specified open parameters. /// - /// Drops any pending session and instance. + /// Drops any existing instance. async fn perform_open(&mut self, workdir: &Path, open_params: OpenPayload) -> OpenOutcome { if let Some(nomt) = self.nomt.take() { - // Drop any pending session. - let _ = self.session.take(); tracing::trace!("dropping the existing NOMT instance"); drop(nomt); } @@ -360,58 +349,19 @@ impl Agent { OpenOutcome::Success } - /// Begin a session, this must be called before `read` and `commit`, - /// which require an opened session. + /// Run one session: read the specified keys on `read_concurrency` threads, then commit the + /// specified changeset. /// - /// Panics if a session was already opened. - fn begin_session(&mut self) { - // UNWRAP: `nomt` is always `Some` except recreation. - let nomt = self.nomt.as_ref().unwrap(); - assert!(self.session.is_none()); - self.session - .replace(nomt.begin_session(SessionParams::default())); - } - - /// Read the specified keys from an already opened session, it requires - /// `begin_session` to have been called. - async fn read(&mut self, reads: Vec, read_concurrency: usize) { - // UNWRAP: `read` is expected to be called after `begin_session`. - let session = Arc::new(self.session.take().unwrap()); - let reads = Arc::new(reads); - - let mut reads_task = JoinSet::<()>::new(); - let reads_per_thread = reads.len() / read_concurrency; - for i in 0..read_concurrency { - let start = i * reads_per_thread; - let end = if i == read_concurrency - 1 { - reads.len() - } else { - (i + 1) * reads_per_thread - }; - reads_task.spawn_blocking({ - let reads = reads.clone(); - let session = session.clone(); - move || { - for key in &reads[start..end] { - let _res = session.read(*key).expect("read failed"); - } - } - }); - } - reads_task.join_all().await; - - self.session.replace(Arc::into_inner(session).unwrap()); - } - - /// Commit the specified changeset to an already opened session, it requires - /// `begin_session` to have been called. - /// - /// It consumes the session, thus after the call the session is expected to be reopened . - async fn commit(&mut self, changeset: Vec) -> Outcome { + /// The session is opened, used and finished inside one blocking call, because a session + /// must stay on the thread that created it. + async fn commit( + &mut self, + reads: Vec, + read_concurrency: usize, + changeset: Vec, + ) -> Outcome { // UNWRAP: `nomt` is always `Some` except recreation. let nomt = self.nomt.as_ref().unwrap(); - // UNWRAP: `commit` is expected to be called after `begin_session`. - let session = self.session.take().unwrap(); let mut actuals = Vec::with_capacity(changeset.len()); for change in changeset { @@ -426,8 +376,14 @@ impl Agent { } // Perform the commit. - let commit_result = - block_in_place(|| session.finish(actuals)?.commit(&nomt), "Panic in commit"); + let commit_result = block_in_place( + || { + let session = nomt.begin_session(SessionParams::default()); + read_concurrently(&session, &reads, read_concurrency); + session.finish(actuals)?.commit(&nomt) + }, + "Panic in commit", + ); let commit_outcome = classify_result(commit_result); // Log the outcome if it was not successful. @@ -463,7 +419,6 @@ impl Agent { hashtable_buckets: u32, preallocate_ht: bool, ) -> Outcome { - self.session.take(); self.nomt.take(); let mut options = nomt::Options::new(); @@ -512,6 +467,27 @@ impl Agent { } } +/// Read the specified keys from the session on `read_concurrency` threads. +fn read_concurrently(session: &Session, reads: &[Key], read_concurrency: usize) { + let reads_per_thread = reads.len() / read_concurrency; + std::thread::scope(|scope| { + for i in 0..read_concurrency { + let start = i * reads_per_thread; + let end = if i == read_concurrency - 1 { + reads.len() + } else { + (i + 1) * reads_per_thread + }; + let reads = &reads[start..end]; + scope.spawn(move || { + for key in reads { + let _res = session.read(*key).expect("read failed"); + } + }); + } + }); +} + /// Runs the provided blocking function on the current thread without /// blocking the executor, handling panics and returning them as stringified errors /// along with the specified `panic_context`. From d97d88181ba586c1835de83fd1a6e89e89e4d7ab Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 23 Nov 2026 18:16:48 +0100 Subject: [PATCH 6/9] merkle: record a node in the page diff even when it empties the page PageWalker::set_node recorded a terminator written to the first layer of a page, next to a terminator sibling, only by setting the diff's clear bit. Any later write to the same page in the same commit erases that bit (PageDiff::set_changed), and the node was then recorded in neither form. The hash-table writeout is not affected, because it writes the whole page. The WAL is: it logs only the nodes the diff lists, and recovery applies them on top of the old bucket. After a crash between the meta write and the end of the hash-table writeout, the old node survived, and the root after reopening was wrong while every value was right. Always record the node as changed, and set the clear bit on top. The test empties the left half of the root page and fills the right half in one commit that panics after the meta write, reopens, and compares the root with the same commit done cleanly. Co-Authored-By: Claude Mythos 5.2 --- nomt/src/merkle/page_walker.rs | 5 ++-- nomt/tests/wal.rs | 46 ++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/nomt/src/merkle/page_walker.rs b/nomt/src/merkle/page_walker.rs index 18fd6be908..dcbe1cb041 100644 --- a/nomt/src/merkle/page_walker.rs +++ b/nomt/src/merkle/page_walker.rs @@ -604,13 +604,14 @@ impl PageWalker { let stack_top = self.stack.last_mut().unwrap(); stack_top.page.set_node(node_index, node); + // Record the node even when the page becomes empty: a later write to this page erases + // the clear bit, and the diff must then still say that this node changed. + stack_top.diff.set_changed(node_index); if self.position.is_first_layer_in_page() && node == TERMINATOR && sibling_node == TERMINATOR { stack_top.diff.set_cleared(); - } else { - stack_top.diff.set_changed(node_index); } } diff --git a/nomt/tests/wal.rs b/nomt/tests/wal.rs index 1d51f04f92..e36bd95409 100644 --- a/nomt/tests/wal.rs +++ b/nomt/tests/wal.rs @@ -3,6 +3,12 @@ mod common; use common::Test; use nomt::PanicOnSyncMode; +fn key(first: u8) -> [u8; 32] { + let mut k = [0u8; 32]; + k[0] = first; + k +} + #[test] fn wal_recovery_test_post_meta_swap() { // Initialize the db with panic on sync equals true. @@ -73,3 +79,43 @@ fn wal_recovery_test_pre_meta_swap() { assert_eq!(common::read_balance(&mut t, i), None); } } + +// The commit empties the left half of the root page and fills the right half. The emptied node is +// first recorded as "page cleared", which the write to the other half then erases. +#[test] +fn wal_recovery_restores_a_node_cleared_before_another_write() { + let empty_left_fill_right = |t: &mut Test| { + t.write(key(0x00), None); + t.write(key(0x40), None); + t.write(key(0x80), Some(vec![3])); + t.write(key(0xC0), Some(vec![4])); + }; + let seed = |name: &str| { + let mut t = Test::new_with_params(name, 1, 64_000, None, true); + t.write(key(0x00), Some(vec![1])); + t.write(key(0x40), Some(vec![2])); + t.commit(); + }; + + let reference = "wal_cleared_node_reference"; + seed(reference); + let mut t = Test::new_with_params(reference, 1, 64_000, None, false); + empty_left_fill_right(&mut t); + let (expected_root, _) = t.commit(); + drop(t); + + let name = "wal_cleared_node"; + seed(name); + let mut t = Test::new_with_params(name, 1, 64_000, Some(PanicOnSyncMode::PostMeta), false); + empty_left_fill_right(&mut t); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + t.commit(); + })); + assert!(r.is_err()); + drop(t); + + let mut t = Test::new_with_params(name, 1, 64_000, None, false); + assert_eq!(t.read(key(0x00)), None); + assert_eq!(t.read(key(0x80)), Some(vec![3])); + assert_eq!(t.root(), expected_root); +} From 5262f87a495d4c334670f90562000c812eab6730 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 23 Nov 2026 18:18:59 +0100 Subject: [PATCH 7/9] beatree: keep a worker's new node when the right worker hands over a deletion With more than one commit worker, a worker that runs out of range asks its right neighbour for more and adds the entries it gets back to its own tracker. It did so with BTreeMap::extend, which replaces an entry that is already there. That happens: the right worker merges two leaves and hands over the merged leaf, but keeps its entry saying that the second of the old leaves is deleted. The left worker splits the merged leaf, and if the split falls on the old boundary it places a new leaf under that same separator. On its next extension it receives the "deleted" entry, which replaced the entry holding the new leaf. The leaf was written to disk but never linked into the tree, and the keys in it, which the commit had not touched, read as absent afterwards. The same code runs for branch nodes. Merge instead: keep the node placed here and take over the deletion. Two workers changing the same separator, one deleting and one inserting, is already an expected case in filter_leaves_changeset. The test uses two workers and 14 keys sized to fill four leaves, deletes three keys, and reads all of them back. Before the fix keys 8, 9 and 10 were gone. Co-Authored-By: Claude Mythos 5.2 --- .../ops/update/extend_range_protocol.rs | 16 +++++++- nomt/tests/extend_range_protocol.rs | 41 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/nomt/src/beatree/ops/update/extend_range_protocol.rs b/nomt/src/beatree/ops/update/extend_range_protocol.rs index 5b0859d508..c341d45d04 100644 --- a/nomt/src/beatree/ops/update/extend_range_protocol.rs +++ b/nomt/src/beatree/ops/update/extend_range_protocol.rs @@ -1,6 +1,7 @@ use crate::beatree::Key; use core::ops::Range; use crossbeam_channel::{Receiver, Sender, TryRecvError}; +use std::collections::btree_map::Entry; use super::{ChangedNodeEntry, NodesTracker}; @@ -191,7 +192,20 @@ pub fn request_range_extension( } } - nodes_tracker.inner.extend(response.changed); + for (key, entry) in response.changed { + match nodes_tracker.inner.entry(key) { + Entry::Vacant(vacant) => { + vacant.insert(entry); + } + Entry::Occupied(mut occupied) => { + // We already placed a node under a separator from which the right worker had + // only deleted one. Keep our node and take over the deletion. + let ours = occupied.get_mut(); + assert!(ours.deleted.is_none() && entry.inserted.is_none()); + ours.deleted = entry.deleted; + } + } + } if let Some(new_right_neighbor) = response.new_right_neighbor { worker_params.right_neighbor = new_right_neighbor; diff --git a/nomt/tests/extend_range_protocol.rs b/nomt/tests/extend_range_protocol.rs index 126c39b903..1646ebfbd7 100644 --- a/nomt/tests/extend_range_protocol.rs +++ b/nomt/tests/extend_range_protocol.rs @@ -85,3 +85,44 @@ fn extend_range_protocol_remove_cutoff() { vec![7, 8, 10, 11, 13, 15, 16, 17, 18, 19, 20], ); } + +// The second worker merges leaves 2 and 3 and hands the result to the first worker, which splits +// it at the old boundary between those leaves. When the first worker then extends its range +// again, it receives the second worker's note that the old leaf 3 is gone. That note must not +// replace the leaf the first worker has just placed under the same separator. +#[test] +fn extend_range_protocol_keeps_leaf_placed_under_deleted_separator() { + #[rustfmt::skip] + const KEYS_AND_VALUE_SIZES: [(u8, usize); 14] = [ + // leaf 1 + (1, 950), (2, 950), (3, 1200), + // leaf 2 + (4, 1100), (5, 1100), (6, 440), (7, 440), + // leaf 3 + (8, 1332), (9, 1200), (10, 430), (11, 32), + // leaf 4 + (12, 1000), (13, 1000), (14, 1000), + ]; + const TO_DELETE: [u8; 3] = [3, 4, 5]; + + let mut t = Test::new_with_params( + "extend_range_deleted_separator", + 2, // commit_concurrency + 64_000, // hashtable_buckets + None, // panic_on_sync + true, // cleanup_dir + ); + for (k, value_size) in KEYS_AND_VALUE_SIZES { + t.write(key(k), Some(vec![k; value_size])); + } + t.commit(); + for k in TO_DELETE { + t.write(key(k), None); + } + t.commit(); + + for (k, value_size) in KEYS_AND_VALUE_SIZES { + let expected = (!TO_DELETE.contains(&k)).then(|| vec![k; value_size]); + assert!(t.read(key(k)) == expected, "key {k}"); + } +} From 572930adbe491637a4d761943996aca4cc9c43a6 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 23 Nov 2026 18:28:22 +0100 Subject: [PATCH 8/9] beatree: fix three errors when a branch node is rebuilt with another prefix BranchNodeBuilder::push_chunk copies separators from an existing node into a new one. When the two nodes have different prefix lengths, each separator is re-cut: bits move between the shared prefix and the separator. Three things went wrong there. 1. The first separator of a node can be shorter than the node's prefix (trailing zeros are not stored), and is then stored with no bits. Its length under a shorter prefix was taken to be the difference of the prefixes, although the gauge that sizes the node counts its real length. The builder then wrote more bits than the gauge had allowed, and in a node that the gauge found exactly full the last separator ran into the first child pointer. The length now comes from the key, and only that many prefix bits are carried over. 2. The bytes of the old prefix to carry over were sliced without taking the bit offset of their start into account. When the prefix shrank by 58 bits or more, the slice could be one 8-byte chunk short and the last carried bits were dropped from every kept separator. 3. When the prefix grew, whole bytes of each old separator are skipped, but the slice kept its old length. bitwise_memcpy takes the number of chunks from that length: the real last chunk was treated as a middle one, written without a mask, and a trailing bit could be lost. Each of these gives a node whose separators or child pointers differ from the keys it was built from, so lookups go to the wrong leaf. Uniformly hashed keys rarely produce the prefix changes involved; keys with long shared prefixes do. Four tests reproduce the cases through BranchUpdater. A fifth rebuilds 4000 random nodes with a long shared prefix, inserting or deleting a key outside it, and compares every separator and pointer. All five fail without the change. Co-Authored-By: Claude Mythos 5.2 --- nomt/src/beatree/branch/node.rs | 62 ++-- .../beatree/ops/update/branch_prefix_tests.rs | 275 ++++++++++++++++++ nomt/src/beatree/ops/update/mod.rs | 2 + 3 files changed, 318 insertions(+), 21 deletions(-) create mode 100644 nomt/src/beatree/ops/update/branch_prefix_tests.rs diff --git a/nomt/src/beatree/branch/node.rs b/nomt/src/beatree/branch/node.rs index 00bd10c467..85d29c93a6 100644 --- a/nomt/src/beatree/branch/node.rs +++ b/nomt/src/beatree/branch/node.rs @@ -6,7 +6,7 @@ use super::BRANCH_NODE_SIZE; use crate::{ beatree::{ allocator::PageNumber, - ops::bit_ops::{bitwise_memcpy, reconstruct_key}, + ops::bit_ops::{bitwise_memcpy, reconstruct_key, separator_len}, Key, }, io::{page_pool::Page, FatPage, PagePool}, @@ -416,6 +416,16 @@ pub fn get_key(node: &BranchNode, index: usize) -> Key { reconstruct_key(prefix, node.raw_separator(index)) } +/// The length `bitwise_memcpy` requires of a source slice holding `bit_len` bits that start at +/// bit `bit_start` of its first byte. +fn source_byte_len(bit_start: usize, bit_len: usize) -> usize { + if bit_len == 0 { + 0 + } else { + ((bit_start + bit_len + 7) / 8).next_multiple_of(8) + } +} + pub struct BranchNodeBuilder { branch: BranchNode, index: usize, @@ -513,21 +523,28 @@ impl BranchNodeBuilder { base_prev_cell_pointer = base.view().cell(from - 1) } - for (base_cell, cell) in (&base.view().cells()[from..to]) - .iter() - .zip(&mut self.branch.cells_mut()[self.index..self.index + n_items]) - { + let prefix_len = self.branch.prefix_len() as usize; + for (base_index, (base_cell, cell)) in (from..to).zip( + (&base.view().cells()[from..to]) + .iter() + .zip(&mut self.branch.cells_mut()[self.index..self.index + n_items]), + ) { let base_cell_pointer = u16::from_le_bytes(*base_cell) as usize; - let mut separator_len = base_cell_pointer - base_prev_cell_pointer; + let base_len = base_cell_pointer - base_prev_cell_pointer; base_prev_cell_pointer = base_cell_pointer; - if is_prefix_extension { - separator_len += bit_prefix_len_difference; + let len = if base_index == 0 && base_len == 0 { + // The first separator of a node can be shorter than the node's prefix, due to + // trailing zero compression, and is then stored with no bits at all. How long it + // is under another prefix can only be told from the key. + separator_len(&get_key(base, 0)).saturating_sub(prefix_len) + } else if is_prefix_extension { + base_len + bit_prefix_len_difference } else { - separator_len = separator_len.saturating_sub(bit_prefix_len_difference); - } + base_len.saturating_sub(bit_prefix_len_difference) + }; - cell_pointer += separator_len as usize; + cell_pointer += len; cell.copy_from_slice(&u16::try_from(cell_pointer).unwrap().to_le_bytes()); } @@ -586,7 +603,7 @@ impl BranchNodeBuilder { return; } - let carry_prefix: Option<(usize, usize, usize)> = if is_prefix_extension { + let carry_prefix: Option<(usize, usize)> = if is_prefix_extension { // bit_prefix_len_difference is the amount of bits that need to be taken from // the base prefix and added in front of every separator. // The interested bits are the last bits of the prefix @@ -596,10 +613,8 @@ impl BranchNodeBuilder { let prefix_bit_start = bits_to_skip % 8; let base_prefix_start = BRANCH_NODE_HEADER_SIZE + base.n() as usize * 2; - let start = base_prefix_start + bytes_to_skip; - let byte_len = (((bit_prefix_len_difference as usize) + 7) / 8).next_multiple_of(8); - Some((start, start + byte_len, prefix_bit_start)) + Some((base_prefix_start + bytes_to_skip, prefix_bit_start)) } else { None }; @@ -615,21 +630,24 @@ impl BranchNodeBuilder { let RawSeparatorsData { start: mut base_separator_bytes_start, - byte_len: base_separator_bytes_len, + byte_len: mut base_separator_bytes_len, bit_start: mut base_separator_bit_start, bit_len: base_separator_bit_len, } = base.view().raw_separators_data(base_index, base_index + 1); // copy the prefix in place if this is_prefix_extension - if let Some((base_prefix_start, base_prefix_end, base_prefix_bit_start)) = carry_prefix - { + // + // A first separator shorter than the base's prefix takes only part of those bits. + let carried_bits = bit_prefix_len_difference.min(separator_bit_len); + if let Some((base_prefix_start, base_prefix_bit_start)) = carry_prefix { + let byte_len = source_byte_len(base_prefix_bit_start, carried_bits); bitwise_memcpy( &mut self.branch.page [separator_bytes_start..separator_bytes_start + separator_bytes_len], separator_bit_start, - &base.page[base_prefix_start..base_prefix_end], + &base.page[base_prefix_start..base_prefix_start + byte_len], base_prefix_bit_start, - bit_prefix_len_difference, + carried_bits, ); } @@ -651,7 +669,7 @@ impl BranchNodeBuilder { let bit_len; if is_prefix_extension { // carry_prefix is already being applied, so skip bits in the new node's separator - separator_bit_start += bit_prefix_len_difference; + separator_bit_start += carried_bits; handle_prefix_offset(&mut separator_bit_start, &mut separator_bytes_start); bit_len = base_separator_bit_len; } else { @@ -662,6 +680,8 @@ impl BranchNodeBuilder { &mut base_separator_bytes_start, ); bit_len = separator_bit_len; + // fewer bits are left to copy, from a later byte + base_separator_bytes_len = source_byte_len(base_separator_bit_start, bit_len); } bitwise_memcpy( diff --git a/nomt/src/beatree/ops/update/branch_prefix_tests.rs b/nomt/src/beatree/ops/update/branch_prefix_tests.rs new file mode 100644 index 0000000000..294e5af76a --- /dev/null +++ b/nomt/src/beatree/ops/update/branch_prefix_tests.rs @@ -0,0 +1,275 @@ +use super::branch_updater::{ + tests::make_branch, BaseBranch, BranchGauge, BranchUpdater, DigestResult, HandleNewBranch, +}; +use crate::beatree::{ + allocator::PageNumber, + branch::{node::get_key, BranchNode, BRANCH_NODE_BODY_SIZE}, + ops::bit_ops::separator_len, + Key, +}; +use crate::io::PagePool; + +#[derive(Default)] +struct Collect(Vec<(Key, BranchNode)>); + +impl HandleNewBranch for Collect { + fn handle_new_branch( + &mut self, + separator: Key, + node: BranchNode, + _cutoff: Option, + ) -> std::io::Result<()> { + self.0.push((separator, node)); + Ok(()) + } +} + +fn gauge_body_size(keys: impl Iterator) -> usize { + let mut gauge = BranchGauge::default(); + for k in keys { + gauge.ingest_key(k, separator_len(&k)); + } + gauge.body_size() +} + +fn set_bit(key: &mut Key, bit: usize) { + key[bit / 8] |= 0x80 >> (bit % 8); +} + +fn rebuild_with_tail(base: Vec<(Key, usize)>, tail: (Key, u32)) -> BranchNode { + let pool = PagePool::new(); + let mut updater = BranchUpdater::new(pool, Some(BaseBranch::new(make_branch(base))), None); + updater.ingest(tail.0, Some(PageNumber(tail.1))); + let mut out = Collect::default(); + let DigestResult::Finished = updater.digest(&mut out).unwrap() else { + panic!("unexpected NeedsMerge") + }; + assert_eq!(out.0.len(), 1); + out.0.pop().unwrap().1 +} + +fn assert_node_matches(node: &BranchNode, expected: &[(Key, u32)]) { + assert_eq!(node.n() as usize, expected.len()); + for (i, (key, pn)) in expected.iter().enumerate() { + assert_eq!( + node.node_pointer(i), + *pn, + "node_pointer({i}) changed (n = {})", + node.n() + ); + assert_eq!(get_key(node, i), *key, "separator {i} changed"); + } +} + +// The all-zero first separator is stored with zero bits once the node has a prefix. Rebuilding +// the node with a shorter prefix must not make it longer than the gauge counted. +#[test] +fn kept_first_separator_fits_the_gauge_when_the_prefix_shrinks() { + let mut base = vec![([0u8; 32], 4096usize)]; + for i in 0..398usize { + let mut k = [0u8; 32]; + k[1] = 0x10 | (i >> 8) as u8; + k[2] = i as u8; + let len = 43 + (i < 343) as usize; + set_bit(&mut k, len - 1); + assert_eq!(separator_len(&k), len); + base.push((k, 5000 + i)); + } + let mut tail = [0u8; 32]; + tail[1] = 0x20; + + let mut expected: Vec<(Key, u32)> = base.iter().map(|(k, pn)| (*k, *pn as u32)).collect(); + expected.push((tail, 9999)); + + assert_eq!( + gauge_body_size(expected.iter().map(|(k, _)| *k)), + BRANCH_NODE_BODY_SIZE + ); + + let node = rebuild_with_tail(base, (tail, 9999)); + assert_eq!(node.prefix_len(), 10); + assert_node_matches(&node, &expected); +} + +#[test] +fn kept_short_first_separator_does_not_spill_into_node_pointers() { + let mut k0 = [0u8; 32]; + k0[0] = 0x80; + let mut tail = [0u8; 32]; + tail[0] = 0xC0; + let mid = |i: usize| { + let mut k = k0; + k[16..18].copy_from_slice(&(i as u16).to_be_bytes()); + k + }; + + let mut found = None; + 'search: for m in 100..250usize { + for ext in (143..256).rev() { + let mut keys = vec![k0]; + keys.extend((1..=m).map(mid)); + if ext > 143 { + set_bit(&mut keys[m], ext); + } + keys.push(tail); + if gauge_body_size(keys.iter().copied()) == BRANCH_NODE_BODY_SIZE { + found = Some(keys); + break 'search; + } + } + } + let keys = found.expect("no exactly-full configuration found"); + + let expected: Vec<(Key, u32)> = keys + .iter() + .enumerate() + .map(|(i, k)| (*k, 70_000 + i as u32)) + .collect(); + let base = expected[..expected.len() - 1] + .iter() + .map(|(k, pn)| (*k, *pn as usize)) + .collect(); + + let node = rebuild_with_tail(base, *expected.last().unwrap()); + assert_eq!(node.prefix_len(), 1); + assert_node_matches(&node, &expected); +} + +#[test] +fn carried_prefix_is_copied_in_full_when_the_prefix_shrinks_by_many_bits() { + let mut expected = Vec::new(); + for i in 0..8u8 { + let mut k = [0u8; 32]; + k[0] = 0x07; + k[1..8].fill(0xff); + k[8] = 0xf1 + 2 * i; + expected.push((k, 100 + i as u32)); + } + let base = expected.iter().map(|(k, pn)| (*k, *pn as usize)).collect(); + let mut tail = [0u8; 32]; + tail[0] = 0x08; + expected.push((tail, 99)); + + let node = rebuild_with_tail(base, (tail, 99)); + assert_eq!(node.prefix_len(), 4); + assert_node_matches(&node, &expected); +} + +#[test] +fn long_separator_keeps_its_last_bits_when_the_prefix_grows() { + let mut k0 = [0u8; 32]; + k0[0] = 0x40; + let mut k1 = [0u8; 32]; + k1[..9].copy_from_slice(&[0xbd, 0x9b, 0xa9, 0x28, 0xdd, 0x85, 0x46, 0xd8, 0xb0]); + let mut k2 = [0u8; 32]; + k2[..16].copy_from_slice(&[ + 0xbd, 0x9b, 0xa9, 0x28, 0xdd, 0x85, 0x46, 0xd8, 0xc4, 0x00, 0x78, 0x61, 0xb5, 0x4b, 0xb3, + 0x20, + ]); + + let pool = PagePool::new(); + let base = make_branch(vec![(k0, 10), (k1, 11), (k2, 12)]); + let mut updater = BranchUpdater::new(pool, Some(BaseBranch::new(base)), None); + updater.ingest(k0, None); + let mut out = Collect::default(); + let DigestResult::Finished = updater.digest(&mut out).unwrap() else { + panic!("unexpected NeedsMerge") + }; + assert_eq!(out.0.len(), 1); + let node = &out.0[0].1; + assert_eq!(node.prefix_len(), 65); + assert_node_matches(node, &[(k1, 11), (k2, 12)]); +} + +// Rebuild nodes whose keys share a long prefix, inserting or deleting one key that does not share +// it, so that the prefix shrinks or grows by many bits. +#[test] +fn rebuilt_nodes_keep_every_separator_and_pointer() { + let mut state = 0x9E3779B97F4A7C15u64; + let mut next = move |bound: usize| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state % bound as u64) as usize + }; + + for round in 0..4000 { + let prefix_bits = 1 + next(200); + let mut prefix = [0u8; 32]; + for bit in 0..prefix_bits { + if next(2) == 1 { + set_bit(&mut prefix, bit); + } + } + + let mut keys = std::collections::BTreeSet::new(); + if next(2) == 0 { + keys.insert(prefix); + } + let n = 2 + next(30); + while keys.len() < n { + let mut key = prefix; + let suffix_bits = 1 + next(40); + for bit in 0..suffix_bits { + if next(2) == 1 { + set_bit(&mut key, prefix_bits + bit); + } + } + set_bit(&mut key, prefix_bits + suffix_bits - 1); + keys.insert(key); + } + + let mut outsider = prefix; + let flipped = next(prefix_bits); + outsider[flipped / 8] ^= 0x80 >> (flipped % 8); + for bit in flipped + 1..256 { + outsider[bit / 8] &= !(0x80 >> (bit % 8)); + } + if next(2) == 1 { + set_bit(&mut outsider, flipped + 1 + next(255 - flipped)); + } + + let insert = next(2) == 0; + let mut all: Vec = keys.iter().copied().collect(); + all.push(outsider); + all.sort(); + all.dedup(); + let with_pn = |keys: &[Key]| -> Vec<(Key, u32)> { + keys.iter() + .map(|k| (*k, 1000 + all.binary_search(k).unwrap() as u32)) + .collect() + }; + let without: Vec = all.iter().copied().filter(|k| *k != outsider).collect(); + let (base, expected) = if insert { + (with_pn(&without), with_pn(&all)) + } else { + (with_pn(&all), with_pn(&without)) + }; + + let pool = PagePool::new(); + let base = make_branch(base.iter().map(|(k, pn)| (*k, *pn as usize)).collect()); + let mut updater = BranchUpdater::new(pool, Some(BaseBranch::new(base)), None); + let outsider_pn = expected + .iter() + .find(|(k, _)| *k == outsider) + .map(|(_, pn)| *pn); + updater.ingest(outsider, outsider_pn.map(PageNumber)); + let mut out = Collect::default(); + let DigestResult::Finished = updater.digest(&mut out).unwrap() else { + panic!("unexpected NeedsMerge") + }; + + out.0.sort_by_key(|(separator, _)| *separator); + let rebuilt: Vec<(Key, u32)> = out + .0 + .iter() + .flat_map(|(_, node)| { + (0..node.n() as usize).map(move |i| (get_key(node, i), node.node_pointer(i))) + }) + .collect(); + assert!( + rebuilt == expected, + "round {round}: prefix {prefix_bits} bits, insert {insert}" + ); + } +} diff --git a/nomt/src/beatree/ops/update/mod.rs b/nomt/src/beatree/ops/update/mod.rs index b7ebc1a49f..2bc52ae4c4 100644 --- a/nomt/src/beatree/ops/update/mod.rs +++ b/nomt/src/beatree/ops/update/mod.rs @@ -23,6 +23,8 @@ mod extend_range_protocol; mod leaf_stage; mod leaf_updater; +#[cfg(test)] +mod branch_prefix_tests; #[cfg(test)] mod tests; From 63842ecb50aa62873a8be7b57bb6ce519b447430 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 23 Nov 2026 18:31:19 +0100 Subject: [PATCH 9/9] Reject a changeset when the root has changed and returned A finished session or an overlay is built against the pages of the database as they were when its session began: which pages exist, in which buckets, and which child pages are elided. At commit the only check was that the database's root still equalled the changeset's previous root. The root does not identify the pages. After a commit and its rollback, or a delete and a re-insert, the root is the same again while pages have been freed, moved or created. A changeset prepared before was accepted and wrote its page images into that different layout: pages landed in buckets that had been released, or twice under one id, and after a reopen proofs panicked or read wrong pages. Preparing two blocks on one parent, committing one, rolling it back and committing the other is exactly this sequence. Count the root changes. A session records the count when it begins, and its changeset is accepted only if the count is still the same, or, for one built on an overlay, if that overlay was the last thing committed. An overlay with a parent was already tied to its parent's commit and is unchanged. A commit that leaves the root as it is does not invalidate other changesets, as before. Tests: a session is rejected after a commit and its rollback, and an overlay after a delete and re-insert; both were accepted before. A session on an overlay still commits after that overlay, and a session still commits after a commit that changes nothing. The overlay fuzz target's model expected a parentless overlay to commit whenever the roots are equal. It now counts root changes as well. Co-Authored-By: Claude Mythos 5.2 --- fuzz/fuzz_targets/overlay.rs | 20 ++++++- nomt/src/lib.rs | 63 +++++++++++++++++++--- nomt/src/overlay.rs | 38 ++++++++++++++ nomt/tests/stale_changeset.rs | 99 +++++++++++++++++++++++++++++++++++ 4 files changed, 213 insertions(+), 7 deletions(-) create mode 100644 nomt/tests/stale_changeset.rs diff --git a/fuzz/fuzz_targets/overlay.rs b/fuzz/fuzz_targets/overlay.rs index 520ad736d9..c16d72004c 100644 --- a/fuzz/fuzz_targets/overlay.rs +++ b/fuzz/fuzz_targets/overlay.rs @@ -21,6 +21,8 @@ struct Slot { parent: Option, committed: bool, prev_root: Node, + /// For an overlay without a live parent: the DB's root version when its session began. + db_root_version: Option, /// The full state as of this overlay. model: Model, } @@ -30,6 +32,9 @@ struct State { committed: Model, /// The overlay committed most recently, unless a session was committed directly after it. last_committed_overlay: Option, + /// Counts the commits that changed the DB's root. An overlay built directly on the DB is + /// stale once the root has changed, even if it has since returned to the same value. + root_version: u64, slots: Vec, keys: Vec, } @@ -49,6 +54,7 @@ fn run(u: &mut Unstructured, path: &std::path::Path) -> Result<()> { db: Nomt::open(options).unwrap(), committed: Model::new(), last_committed_overlay: None, + root_version: 0, slots: Vec::new(), keys: Vec::new(), }; @@ -200,6 +206,7 @@ fn session(u: &mut Unstructured, state: &mut State) -> Result<()> { parent: base, committed: false, prev_root: base_root, + db_root_version: chain.is_empty().then_some(state.root_version), model, }); } @@ -208,6 +215,9 @@ fn session(u: &mut Unstructured, state: &mut State) -> Result<()> { // Equal roots mean the DB holds the same state the session was based on. if db_root == base_root { result.unwrap(); + if state.db.root().into_inner() != db_root { + state.root_version += 1; + } state.committed = model; state.last_committed_overlay = None; } else { @@ -227,7 +237,12 @@ fn commit_overlay(u: &mut Unstructured, state: &mut State) -> Result<()> { let parent_ok = slot .parent .map_or(true, |p| state.last_committed_overlay == Some(p)); - let expect_ok = parent_ok && slot.prev_root == state.db.root().into_inner(); + let db_root = state.db.root().into_inner(); + let expect_ok = parent_ok + && slot.prev_root == db_root + && slot + .db_root_version + .map_or(true, |version| version == state.root_version); // A commit attempt consumes the overlay, whether or not it succeeds. let overlay = slot.overlay.take().unwrap(); @@ -240,6 +255,9 @@ fn commit_overlay(u: &mut Unstructured, state: &mut State) -> Result<()> { }; if expect_ok { result.unwrap(); + if state.db.root().into_inner() != db_root { + state.root_version += 1; + } slot.committed = true; state.committed = slot.model.clone(); state.last_committed_overlay = Some(i); diff --git a/nomt/src/lib.rs b/nomt/src/lib.rs index 20d7e256d2..35237faaae 100644 --- a/nomt/src/lib.rs +++ b/nomt/src/lib.rs @@ -68,10 +68,25 @@ pub type Value = Vec; struct Shared { /// The current root of the trie. root: Root, + /// Incremented whenever a commit changes `root`. + /// + /// A changeset is built on the pages of the database as they were when its session began. + /// The root does not identify them: after a commit and its rollback, or a delete and a + /// re-insert, the root is the same again while pages have moved, appeared or gone. + root_version: u64, /// The marker of the last committed overlay. `None` if the last commit was not an overlay. last_commit_marker: Option, } +impl Shared { + fn set_root(&mut self, root: Root) { + if self.root != root { + self.root_version += 1; + } + self.root = root; + } +} + /// Whether a key was read, written, or both, along with old and new values. #[derive(Debug, Clone)] pub enum KeyReadWrite { @@ -252,6 +267,7 @@ impl Nomt { store, shared: Arc::new(Mutex::new(Shared { root: Root(root), + root_version: 0, last_commit_marker: None, })), access_lock: Arc::new(RwLock::new(())), @@ -319,7 +335,7 @@ impl Nomt { /// and permit a changeset to be committed either directly to the database or into an /// in-memory [`Overlay`]. pub fn begin_session(&self, params: SessionParams) -> Session { - let live_overlay = params.overlay; + let mut live_overlay = params.overlay; // We must take the access guard before instantiating the rollback delta, // because it creates a read transaction and any commits or rollbacks will block @@ -337,9 +353,14 @@ impl Nomt { None }; + let (db_root, root_version) = { + let shared = self.shared.lock(); + (shared.root, shared.root_version) + }; + live_overlay.set_base_version(root_version); let prev_root = live_overlay .parent_root() - .unwrap_or_else(|| self.root().into_inner()); + .unwrap_or_else(|| db_root.into_inner()); Session { store, @@ -824,7 +845,16 @@ impl FinishedSession { shared.root ); } - shared.root = Root(self.merkle_output.root); + if !self + .parent_overlay + .is_base_current(shared.root_version, shared.last_commit_marker.as_ref()) + { + anyhow::bail!( + "Changeset no longer valid (the database left root {:?} and returned to it)", + self.prev_root, + ); + } + shared.set_root(Root(self.merkle_output.root)); shared.last_commit_marker = None; } @@ -866,7 +896,16 @@ impl FinishedSession { shared.root ); } - shared.root = Root(self.merkle_output.root); + if !self + .parent_overlay + .is_base_current(shared.root_version, shared.last_commit_marker.as_ref()) + { + anyhow::bail!( + "Changeset no longer valid (the database left root {:?} and returned to it)", + self.prev_root, + ); + } + shared.set_root(Root(self.merkle_output.root)); shared.last_commit_marker = None; } @@ -906,7 +945,13 @@ impl Overlay { shared.root ); } - shared.root = self.root(); + if !self.is_base_current(shared.root_version) { + anyhow::bail!( + "Changeset no longer valid (the database left root {:?} and returned to it)", + self.prev_root(), + ); + } + shared.set_root(self.root()); shared.last_commit_marker = Some(self.mark_committed()); } @@ -948,7 +993,13 @@ impl Overlay { shared.root ); } - shared.root = self.root(); + if !self.is_base_current(shared.root_version) { + anyhow::bail!( + "Changeset no longer valid (the database left root {:?} and returned to it)", + self.prev_root(), + ); + } + shared.set_root(self.root()); shared.last_commit_marker = Some(self.mark_committed()); } diff --git a/nomt/src/overlay.rs b/nomt/src/overlay.rs index 8cd9c453b9..32d1f7b4fc 100644 --- a/nomt/src/overlay.rs +++ b/nomt/src/overlay.rs @@ -80,6 +80,13 @@ impl Overlay { (pages, values, rollback_delta) } + /// Whether the database, whose root is at the given version, is still in the state this + /// overlay was built on. An overlay with a parent is tied to that parent instead, see + /// [`Self::parent_matches_marker`]. + pub(super) fn is_base_current(&self, root_version: u64) -> bool { + self.inner.data.parent_status.is_some() || self.inner.base_version == root_version + } + /// Mark the overlay as committed and return a marker. pub(super) fn mark_committed(&self) -> OverlayMarker { let status = self.inner.data.status.clone(); @@ -94,6 +101,8 @@ struct OverlayInner { index: Index, data: Arc, seqn: u64, + /// See [`LiveOverlay::base_version`]. + base_version: u64, // ordered by recency. ancestor_data: Vec>, rollback_delta: Option, @@ -249,6 +258,8 @@ pub(super) struct LiveOverlay { parent: Option>, ancestor_data: Vec>, min_seqn: u64, + /// The version of the database root when the session using this overlay began. + base_version: u64, } impl LiveOverlay { @@ -262,6 +273,7 @@ impl LiveOverlay { parent: None, ancestor_data: Vec::new(), min_seqn: 0, + base_version: 0, }); }; @@ -297,6 +309,7 @@ impl LiveOverlay { parent: Some(parent), ancestor_data, min_seqn, + base_version: 0, }) } @@ -418,12 +431,37 @@ impl LiveOverlay { parent_status, }), seqn: new_seqn, + base_version: self.base_version, ancestor_data, rollback_delta, }), } } + /// Record the version of the database root at the time the session begins. + pub(super) fn set_base_version(&mut self, root_version: u64) { + self.base_version = root_version; + } + + /// Whether a session built on this overlay can be committed to the database directly, given + /// the version of the database root and the marker of the overlay committed last. + /// + /// Either the root has not changed since the session began, or the last commit was that of + /// the parent overlay. + pub(super) fn is_base_current( + &self, + root_version: u64, + marker: Option<&OverlayMarker>, + ) -> bool { + if self.base_version == root_version { + return true; + } + match (self.parent.as_ref(), marker) { + (Some(parent), Some(marker)) => parent.data.status.ptr_eq(&marker.0), + _ => false, + } + } + /// Get the overlay's root. If this is an empty overlay, returns `None`. pub(super) fn parent_root(&self) -> Option { self.parent.as_ref().map(|p| p.root) diff --git a/nomt/tests/stale_changeset.rs b/nomt/tests/stale_changeset.rs new file mode 100644 index 0000000000..c8f1360f55 --- /dev/null +++ b/nomt/tests/stale_changeset.rs @@ -0,0 +1,99 @@ +use nomt::{ + hasher::Blake3Hasher, trie::KeyPath, FinishedSession, KeyReadWrite, Nomt, Options, Root, + SessionParams, +}; +use std::path::PathBuf; + +fn open(name: &str) -> Nomt { + let path = PathBuf::from("test").join(name); + let _ = std::fs::remove_dir_all(&path); + let mut o = Options::new(); + o.path(path); + o.commit_concurrency(1); + o.bitbox_seed([0; 16]); + o.hashtable_buckets(4096); + o.rollback(true); + Nomt::open(o).unwrap() +} + +fn key(first: u8) -> KeyPath { + let mut key = [0; 32]; + key[0] = first; + key +} + +fn finish( + nomt: &Nomt, + params: SessionParams, + writes: &[(u8, Option)], +) -> FinishedSession { + let actuals = writes + .iter() + .map(|(k, v)| (key(*k), KeyReadWrite::Write(v.map(|v| vec![v])))) + .collect(); + nomt.begin_session(params).finish(actuals).unwrap() +} + +fn commit(nomt: &Nomt, writes: &[(u8, Option)]) -> Root { + finish(nomt, SessionParams::default(), writes) + .commit(nomt) + .unwrap(); + nomt.root() +} + +// A changeset is built against the pages of the database at that moment. After a commit and its +// rollback the root is the same again, but the pages are not. +#[test] +fn session_is_stale_after_commit_and_rollback() { + let nomt = open("stale_session_after_rollback"); + let base = commit(&nomt, &[(1, Some(1)), (2, Some(2))]); + + let stale = finish(&nomt, SessionParams::default(), &[(3, Some(3))]); + commit(&nomt, &[(4, Some(4))]); + nomt.rollback(1).unwrap(); + assert_eq!(nomt.root(), base); + + assert!(stale.commit(&nomt).is_err()); + assert_eq!(nomt.root(), base); +} + +#[test] +fn overlay_is_stale_after_root_returns_without_rollback() { + let nomt = open("stale_overlay_after_reinsert"); + let base = commit(&nomt, &[(1, Some(1)), (2, Some(2))]); + + let stale = finish(&nomt, SessionParams::default(), &[(3, Some(3))]).into_overlay(); + commit(&nomt, &[(1, None)]); + assert_eq!(commit(&nomt, &[(1, Some(1))]), base); + + assert!(stale.commit(&nomt).is_err()); + assert_eq!(nomt.root(), base); +} + +#[test] +fn session_on_an_overlay_commits_after_that_overlay() { + let nomt = open("session_after_its_overlay"); + commit(&nomt, &[(1, Some(1))]); + + let overlay = finish(&nomt, SessionParams::default(), &[(2, Some(2))]).into_overlay(); + let params = SessionParams::default().overlay([&overlay]).unwrap(); + let child = finish(&nomt, params, &[(3, Some(3))]); + let child_root = child.root(); + + overlay.commit(&nomt).unwrap(); + child.commit(&nomt).unwrap(); + assert_eq!(nomt.root(), child_root); +} + +#[test] +fn session_survives_a_commit_that_changes_nothing() { + let nomt = open("session_after_noop_commit"); + commit(&nomt, &[(1, Some(1))]); + + let pending = finish(&nomt, SessionParams::default(), &[(2, Some(2))]); + let pending_root = pending.root(); + commit(&nomt, &[]); + + pending.commit(&nomt).unwrap(); + assert_eq!(nomt.root(), pending_root); +}