From 01c08c6df8de8a2ac9d225bee284b9717537d3b8 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 13 Oct 2026 14:50:17 +0200 Subject: [PATCH 01/12] Keep branch and leaf nodes alive in their write commands New branch and leaf nodes were written with a raw page pointer and kept alive through deferred_drop_pages until all I/O was drained. If an I/O error made update return early, the nodes could be freed while their writes were still in flight. Let the write command hold an Arc to the node instead, and remove the deferred drop bookkeeping. Co-Authored-By: Claude Opus 5.5 --- nomt/src/beatree/branch/node.rs | 12 +++++++----- nomt/src/beatree/leaf/node.rs | 6 ++++++ nomt/src/beatree/ops/update/branch_stage.rs | 14 +------------- nomt/src/beatree/ops/update/leaf_stage.rs | 3 +-- nomt/src/beatree/ops/update/mod.rs | 6 ------ nomt/src/io/linux.rs | 3 ++- nomt/src/io/mod.rs | 9 +++++---- nomt/src/io/page_pool.rs | 8 -------- nomt/src/io/unix.rs | 3 ++- 9 files changed, 24 insertions(+), 40 deletions(-) diff --git a/nomt/src/beatree/branch/node.rs b/nomt/src/beatree/branch/node.rs index 21a3cb80b5..d7436c486d 100644 --- a/nomt/src/beatree/branch/node.rs +++ b/nomt/src/beatree/branch/node.rs @@ -9,7 +9,7 @@ use crate::{ ops::bit_ops::{bitwise_memcpy, reconstruct_key}, Key, }, - io::{page_pool::Page, FatPage, PagePool}, + io::{FatPage, PagePool, PAGE_SIZE}, }; // Here is the layout of a branch node: @@ -44,6 +44,12 @@ pub struct BranchNode { pub(super) page: FatPage, } +impl AsRef<[u8; PAGE_SIZE]> for BranchNode { + fn as_ref(&self) -> &[u8; PAGE_SIZE] { + self.as_slice().try_into().unwrap() + } +} + impl BranchNode { pub fn new_in(page_pool: &PagePool) -> Self { BranchNode { @@ -55,10 +61,6 @@ impl BranchNode { &*self.page } - pub fn page(&self) -> Page { - self.page.page() - } - pub fn view(&self) -> BranchNodeView<'_> { BranchNodeView { inner: self.as_slice(), diff --git a/nomt/src/beatree/leaf/node.rs b/nomt/src/beatree/leaf/node.rs index e2a19dbb91..1f4a14eed2 100644 --- a/nomt/src/beatree/leaf/node.rs +++ b/nomt/src/beatree/leaf/node.rs @@ -53,6 +53,12 @@ pub struct LeafNode { pub inner: FatPage, } +impl AsRef<[u8; PAGE_SIZE]> for LeafNode { + fn as_ref(&self) -> &[u8; PAGE_SIZE] { + (&*self.inner).try_into().unwrap() + } +} + impl LeafNode { #[inline] pub fn n(&self) -> usize { diff --git a/nomt/src/beatree/ops/update/branch_stage.rs b/nomt/src/beatree/ops/update/branch_stage.rs index 823008ffb5..efda864544 100644 --- a/nomt/src/beatree/ops/update/branch_stage.rs +++ b/nomt/src/beatree/ops/update/branch_stage.rs @@ -22,12 +22,6 @@ use super::extend_range_protocol::{ /// Tracker of all changes that happen to branch nodes during an update pub type BranchesTracker = super::NodesTracker; -/// Data, including buffers, which may be dropped only once I/O has certainly concluded. -#[derive(Default)] -pub struct PostIoDrop { - deferred_drop_pages: Vec>>, -} - /// Outputs of the branch stage. #[derive(Default)] pub struct BranchStageOutput { @@ -35,8 +29,6 @@ pub struct BranchStageOutput { pub freed_pages: Vec, /// The number of submitted I/Os. pub submitted_io: usize, - /// Data which should be dropped after all submitted I/Os have concluded. - pub post_io_drop: PostIoDrop, } /// Change the btree's branch nodes in the specified way. @@ -135,9 +127,6 @@ fn apply_bbn_changes( output .freed_pages .extend(worker_output.branches_tracker.extra_freed.drain(..)); - output.post_io_drop.deferred_drop_pages.push(std::mem::take( - &mut worker_output.branches_tracker.deferred_drop_pages, - )); } // Branch changeset is created by aggregating the outcomes of multiple workers, @@ -485,10 +474,9 @@ impl super::branch_updater::HandleNewBranch for NewBranchHandler { bbn.set_bbn_pn(page_number.0); let bbn = Arc::new(bbn); - let page = bbn.page(); self.io_handle .send(IoCommand { - kind: IoKind::WriteRaw(fd, page_number.0 as u64, page), + kind: IoKind::WriteShared(fd, page_number.0 as u64, bbn.clone()), user_data: 0, }) .expect("I/O Pool Down"); diff --git a/nomt/src/beatree/ops/update/leaf_stage.rs b/nomt/src/beatree/ops/update/leaf_stage.rs index c47ad4bfc7..b29dd4b42f 100644 --- a/nomt/src/beatree/ops/update/leaf_stage.rs +++ b/nomt/src/beatree/ops/update/leaf_stage.rs @@ -717,10 +717,9 @@ impl super::leaf_updater::HandleNewLeaf for NewLeafHandler { let page_number = self.leaf_writer.allocate()?; - let page = leaf.inner.page(); self.io_handle .send(IoCommand { - kind: IoKind::WriteRaw(fd, page_number.0 as u64, page), + kind: IoKind::WriteShared(fd, page_number.0 as u64, leaf.clone()), user_data: 0, }) .expect("I/O Pool Down"); diff --git a/nomt/src/beatree/ops/update/mod.rs b/nomt/src/beatree/ops/update/mod.rs index b7ebc1a49f..44dbb858cc 100644 --- a/nomt/src/beatree/ops/update/mod.rs +++ b/nomt/src/beatree/ops/update/mod.rs @@ -102,7 +102,6 @@ pub fn update( let (tx, rx) = crossbeam_channel::bounded(1); let post_io_task = move || { leaf_stage_outputs.post_io_work.run(&leaf_cache); - drop(branch_stage_outputs.post_io_drop); leaf_cache.evict(); }; spawn_task(&thread_pool, post_io_task, tx); @@ -138,9 +137,6 @@ pub struct NodesTracker { pub pending_base: Option<(Key, Arc, Option)>, /// Page numbers which were allocated and discarded entirely during this update. pub extra_freed: Vec, - /// Pages which are potentially being written and which must be kept alive until I/O - /// is guaranteed complete. - pub deferred_drop_pages: Vec>, pub new_inserted: usize, } @@ -152,7 +148,6 @@ impl NodesTracker { pending_base: None, extra_freed: Vec::new(), new_inserted: 0, - deferred_drop_pages: Vec::new(), } } @@ -201,7 +196,6 @@ impl NodesTracker { pn: PageNumber, ) { self.extra_freed.push(pn); - self.deferred_drop_pages.push(node.clone()); self.pending_base = Some((separator, node, cutoff)); } } diff --git a/nomt/src/io/linux.rs b/nomt/src/io/linux.rs index a9796bacf1..9bf49dec0d 100644 --- a/nomt/src/io/linux.rs +++ b/nomt/src/io/linux.rs @@ -208,7 +208,8 @@ fn submission_entry(command: &mut IoCommand) -> squeue::Entry { .offset(page_index * PAGE_SIZE as u64) .build() } - IoKind::WriteRaw(fd, page_index, ref page) => { + IoKind::WriteShared(fd, page_index, ref page) => { + let page: &[u8; PAGE_SIZE] = page.as_ref().as_ref(); opcode::Write::new(types::Fd(fd), page.as_ptr(), PAGE_SIZE as u32) .offset(page_index * PAGE_SIZE as u64) .build() diff --git a/nomt/src/io/mod.rs b/nomt/src/io/mod.rs index 3448d43982..332438aaef 100644 --- a/nomt/src/io/mod.rs +++ b/nomt/src/io/mod.rs @@ -2,7 +2,6 @@ std::compile_error!("NOMT only supports Unix-based OSs"); use crossbeam_channel::{Receiver, RecvError, SendError, Sender, TryRecvError}; -use page_pool::Page; use std::{ fmt, fs::File, @@ -52,7 +51,9 @@ pub enum IoKind { Read(RawFd, u64, FatPage), Write(RawFd, u64, FatPage), WriteArc(RawFd, u64, Arc), - WriteRaw(RawFd, u64, Page), + /// Retain the immutable node until its queued write completes, even if + /// preparation returns early or unwinds before joining the writeout. + WriteShared(RawFd, u64, Arc + Send + Sync>), } impl fmt::Debug for IoKind { @@ -61,7 +62,7 @@ impl fmt::Debug for IoKind { IoKind::Read(fd, pn, _) => write!(f, "Read(fd={}, pn={})", fd, pn), IoKind::Write(fd, pn, _) => write!(f, "Write(fd={}, pn={})", fd, pn), IoKind::WriteArc(fd, pn, _) => write!(f, "WriteArc(fd={}, pn={})", fd, pn), - IoKind::WriteRaw(fd, pn, _) => write!(f, "WriteRaw(fd={}, pn={})", fd, pn), + IoKind::WriteShared(fd, pn, _) => write!(f, "WriteShared(fd={}, pn={})", fd, pn), } } } @@ -77,7 +78,7 @@ impl IoKind { match self { IoKind::Read(_, _, buf) | IoKind::Write(_, _, buf) => buf, IoKind::WriteArc(_, _, _) => panic!("attempted to extract owned buf from write_arc"), - IoKind::WriteRaw(_, _, _) => panic!("attempted to extract buf from write_raw"), + IoKind::WriteShared(_, _, _) => panic!("attempted to extract buf from write_shared"), } } diff --git a/nomt/src/io/page_pool.rs b/nomt/src/io/page_pool.rs index 6fa6a91db8..982ab8d836 100644 --- a/nomt/src/io/page_pool.rs +++ b/nomt/src/io/page_pool.rs @@ -76,14 +76,6 @@ impl FatPage { pub fn as_mut_ptr(&self) -> *mut u8 { self.page.as_mut_ptr() } - - /// Returns underlying [`Page`]. - /// - /// Care must be taken that the returned page is not used after `self` is dropped. However, - /// failing to do so will not cause safety bugs. - pub fn page(&self) -> Page { - self.page.clone() - } } impl Clone for FatPage { diff --git a/nomt/src/io/unix.rs b/nomt/src/io/unix.rs index d4b0a24e85..fbc9bd9e15 100644 --- a/nomt/src/io/unix.rs +++ b/nomt/src/io/unix.rs @@ -73,7 +73,8 @@ fn execute(mut command: IoCommand) -> CompleteIo { (page_index * PAGE_SIZE as u64) as libc::off_t, ) }, - IoKind::WriteRaw(fd, page_index, ref mut page) => unsafe { + IoKind::WriteShared(fd, page_index, ref page) => unsafe { + let page: &[u8; PAGE_SIZE] = page.as_ref().as_ref(); libc::pwrite( fd, page.as_ptr() as *const libc::c_void, From cd7c5387b84906923324631a6c50b85bada9de11 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 13 Oct 2026 14:50:50 +0200 Subject: [PATCH 02/12] Free overflow pages of a replaced cell with nothing kept before it LeafUpdater::keep_up_to returned early when there were no cells to keep before the updated key, which skipped reclaiming the overflow pages of the cell being replaced. This happens for the first key of a leaf and for consecutive updated keys, and leaked those overflow pages. Co-Authored-By: Claude Opus 5.5 --- nomt/src/beatree/ops/update/leaf_updater.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/nomt/src/beatree/ops/update/leaf_updater.rs b/nomt/src/beatree/ops/update/leaf_updater.rs index 4da53aaafb..8342d175ec 100644 --- a/nomt/src/beatree/ops/update/leaf_updater.rs +++ b/nomt/src/beatree/ops/update/leaf_updater.rs @@ -227,15 +227,14 @@ impl LeafUpdater { }, }; - if from == to { - // nothing to keep - return; + if from != to { + let values_size = base.node.values_size(from, to); + self.ops.push(LeafOp::KeepChunk(from, to, values_size)); + self.gauge.ingest(to - from, values_size); } - let values_size = base.node.values_size(from, to); - self.ops.push(LeafOp::KeepChunk(from, to, values_size)); - self.gauge.ingest(to - from, values_size); - + // Replacing a cell must reclaim its overflow pages even when no preceding + // cells were kept (the first key, or consecutive updated keys). if found { let (val, overflow) = base.cell(to); if overflow { From acbb907046ffbbb894a81d87b1df4a58cbd0d7cf Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 13 Oct 2026 14:51:53 +0200 Subject: [PATCH 03/12] Keep the WAL when hash-table writes fail, and recover from a torn WAL write_ht ignored the results of the page writes, so post-meta truncated the WAL even if some pages never reached the hash table. Drain all writes and return the first error, which keeps the WAL for recovery. Recovery parsed the whole WAL before checking its sequence number, so a WAL left incomplete by a sync that never concluded made opening fail. Read only the header first and discard a WAL from another sync without parsing it. Co-Authored-By: Claude Opus 5.5 --- nomt/src/bitbox/mod.rs | 9 ++++++--- nomt/src/bitbox/wal/read.rs | 22 ++++++++++++++++++++++ nomt/src/bitbox/writeout.rs | 6 +++++- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/nomt/src/bitbox/mod.rs b/nomt/src/bitbox/mod.rs index d499e3e2d8..8a19c1b64d 100644 --- a/nomt/src/bitbox/mod.rs +++ b/nomt/src/bitbox/mod.rs @@ -438,17 +438,20 @@ fn recover( wal_fd.seek(SeekFrom::Start(0))?; - let mut wal_reader = WalBlobReader::new(page_pool, wal_fd)?; - // This condition triggers either if: // 1. the WAL holds data for a sync that never concluded. Safe to discard. // 2. the WAL holds data for a sync that fully concluded. (somehow). Safe to discard. - if wal_reader.sync_seqn() != sync_seqn { + // + // Only the header is read here: the WAL of a sync that never concluded may be incomplete. + if WalBlobReader::read_sync_seqn(page_pool, wal_fd)? != sync_seqn { // fsync generously here since it's a one-time operation. writeout::truncate_wal(wal_fd, true)?; return Ok(()); } + let mut wal_reader = WalBlobReader::new(page_pool, wal_fd)?; + debug_assert_eq!(wal_reader.sync_seqn(), sync_seqn); + // The indices of pages (in the metabits page space) that were changed and require updates. // Note those are not ht page numbers yet and still require additional conversion. let mut changed_meta_page_ixs = HashSet::new(); diff --git a/nomt/src/bitbox/wal/read.rs b/nomt/src/bitbox/wal/read.rs index aabd2df7a9..e531a30263 100644 --- a/nomt/src/bitbox/wal/read.rs +++ b/nomt/src/bitbox/wal/read.rs @@ -38,6 +38,28 @@ pub struct WalBlobReader { } impl WalBlobReader { + /// Read the sequence even when an uncommitted WAL has an incomplete body. + pub(crate) fn read_sync_seqn(page_pool: &PagePool, wal_fd: &File) -> anyhow::Result { + use std::os::unix::fs::FileExt; + + // The WAL uses direct I/O, so both the buffer and requested length stay + // page-aligned. Only the returned prefix may be shorter than a page. + let mut page = page_pool.alloc_fat_page(); + let len = loop { + match wal_fd.read_at(&mut page, 0) { + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, + result => break result?, + } + }; + if len < 5 { + bail!("Unexpected end of WAL header"); + } + if page[0] != WAL_ENTRY_TAG_START { + bail!("unexpected WAL entry tag at start: {}", page[0]); + } + Ok(u32::from_le_bytes(page[1..5].try_into().unwrap())) + } + /// Creates a new WAL blob reader. /// /// The `wal_fd` is expected to be positioned at the start of the WAL file. The file must be diff --git a/nomt/src/bitbox/writeout.rs b/nomt/src/bitbox/writeout.rs index ab42eb12bd..f24b5842bf 100644 --- a/nomt/src/bitbox/writeout.rs +++ b/nomt/src/bitbox/writeout.rs @@ -52,10 +52,14 @@ pub(super) fn write_ht( sent += 1; } + // Drain every submitted write and keep the first error. The WAL must not be truncated if any + // page failed to reach the hash table. + let mut write_result = Ok(()); while sent > 0 { - io_handle.recv().unwrap(); + write_result = write_result.and(io_handle.recv().unwrap().result); sent -= 1; } + write_result?; ht_fd.sync_all()?; From 25cd9a3961d094e213c4b5e1151c3a06e80c4a59 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 13 Oct 2026 14:53:10 +0200 Subject: [PATCH 04/12] Harden rollback log recovery - Stop at the manifest's last live record. A crash during an append can leave an incomplete record after it, which recovery used to reject. - Check for gaps in segment IDs only up to the end of the live range, because an interrupted recovery may leave gaps among the segments after it. - Check that live records are contiguous across segment boundaries. The first live record may come after the manifest's start, because that start can be an expired record whose segment was already pruned. Co-Authored-By: Claude Opus 5.5 --- nomt/src/seglog/mod.rs | 67 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 55 insertions(+), 12 deletions(-) diff --git a/nomt/src/seglog/mod.rs b/nomt/src/seglog/mod.rs index cb1413c821..eaa17a6aeb 100644 --- a/nomt/src/seglog/mod.rs +++ b/nomt/src/seglog/mod.rs @@ -409,6 +409,7 @@ struct Recovery { start_live: RecordId, end_live: RecordId, payload_buf: Vec, + last_live_record: Option, live_segment_start: Option, live_segment_end: Option, } @@ -420,6 +421,7 @@ impl Recovery { start_live, end_live, payload_buf: Vec::new(), + last_live_record: None, live_segment_start: None, live_segment_end: None, } @@ -451,24 +453,13 @@ impl Recovery { } // Now do some checks. - for i in 0..self.candidates.len() { - let candidate = &self.candidates[i]; + for candidate in &self.candidates { if candidate.id == 0 { return Err(anyhow::anyhow!( "Segment ID is nil, file: {}", candidate.path.display() )); } - if i > 0 { - let prev = &self.candidates[i - 1]; - if prev.id != candidate.id - 1 { - return Err(anyhow::anyhow!( - "Gap in segment IDs: this {}, last {}", - candidate.id, - prev.id - )); - } - } } Ok(()) @@ -507,6 +498,18 @@ impl Recovery { let (was_live, became_live, became_nonlive) = self.on_next_record(index, record_id); if was_live || became_live || became_nonlive { + // Live records must be contiguous across segment boundaries. The first one may + // come after the manifest's start, if that start is an expired record whose + // segment was already pruned. + if let Some(last) = self.last_live_record { + ensure!( + record_id == last.next(), + "Live record IDs are not ordered: this {}, expected {}", + record_id, + last.next(), + ); + } + self.last_live_record = Some(record_id); seg_reader.read_payload(&mut self.payload_buf)?; process_record(record_id, &self.payload_buf)?; } else { @@ -521,6 +524,11 @@ impl Recovery { max = Some(record_id); } last = Some(record_id); + // A crash may leave an incomplete header or payload after the manifest's final + // committed record. Do not parse that suffix. + if record_id == self.end_live { + break; + } } // If the segment is empty, we set the min and max to nil. They are always Some after this // function returns. @@ -690,6 +698,19 @@ where recovery.scan_root_dir(&root_dir_path, &filename_prefix)?; if !empty_live_range { for i in 0..recovery.candidates.len() { + // Segments after the live range may have been partially removed by an interrupted + // recovery, so check for gaps only until the end of the live range is found. + if i > 0 { + let candidate = &recovery.candidates[i]; + let prev = &recovery.candidates[i - 1]; + if prev.id != candidate.id - 1 { + return Err(anyhow::anyhow!( + "Gap in segment IDs: this {}, last {}", + candidate.id, + prev.id + )); + } + } recovery .scan_segment(i, &mut process_record) .with_context(|| { @@ -698,6 +719,9 @@ where recovery.candidates[i].path.display() ) })?; + if recovery.candidates[i].max == end_live { + break; + } } } @@ -1114,6 +1138,25 @@ mod tests { Ok(()) } + #[test] + fn recovery_start_live_in_pruned_segment() -> Result<()> { + // The manifest may point at an expired record whose segment was already pruned. + let h = TestHarness::new()?; + h.new_segment(2)? + .write_record(2, &vec![2u8; 10])? + .write_record(3, &vec![3u8; 10])? + .write()?; + let (_log, records) = h.open_log(default_max_segment_size(), 1, 3)?; + assert_eq!( + records, + vec![ + (RecordId::from(2), vec![2u8; 10]), + (RecordId::from(3), vec![3u8; 10]), + ] + ); + Ok(()) + } + #[test] fn append_after_recovery_empty_head_segment() -> Result<()> { // This checks that appending to the empty head segment works. From 5ce119decf3bf176de38e520598918ace1b898be Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 13 Oct 2026 14:54:01 +0200 Subject: [PATCH 05/12] Fix rollback log edge cases - After truncating, the new end of the live range was the record before the earliest removed delta. When every retained delta was removed, that record had already expired: it either came back after reopening, or pruning failed if its segment was already gone. Use the last retained delta, or nil. - max_rollback_log_len(0) made the rollback sync thread panic on the first commit. Reject it in the setter, like io_workers(0). Co-Authored-By: Claude Opus 5.5 --- nomt/src/options.rs | 3 ++- nomt/src/rollback/mod.rs | 22 +++++++++------------- nomt/src/seglog/mod.rs | 8 -------- 3 files changed, 11 insertions(+), 22 deletions(-) diff --git a/nomt/src/options.rs b/nomt/src/options.rs index c0f9a1436e..bcb40e85fb 100644 --- a/nomt/src/options.rs +++ b/nomt/src/options.rs @@ -129,10 +129,11 @@ impl Options { /// Set the maximum number of commits that can be rolled back. /// - /// Only relevant if rollback is enabled. + /// Only relevant if rollback is enabled. Must be greater than zero. /// /// Default: 100. pub fn max_rollback_log_len(&mut self, max_rollback_log_len: u32) { + assert!(max_rollback_log_len > 0); self.max_rollback_log_len = max_rollback_log_len; } diff --git a/nomt/src/rollback/mod.rs b/nomt/src/rollback/mod.rs index 83f47c9df6..8ec6072931 100644 --- a/nomt/src/rollback/mod.rs +++ b/nomt/src/rollback/mod.rs @@ -181,30 +181,26 @@ impl Rollback { } let mut traceback = BTreeMap::new(); - let mut earliest_record_id = None; while n > 0 { // Pop the most recent delta from the log and add its original values to the traceback, // potentially overwriting some of the values that were added in previous iterations. // // UNWRAP: we checked above that `n` is greater or equal to the total number of deltas // and `n` is strictly decreasing. - let (record_id, delta) = in_memory.pop_recent().unwrap(); - earliest_record_id = Some(record_id); + let (_, delta) = in_memory.pop_recent().unwrap(); for (key, value) in delta.priors { traceback.insert(key, value); } n -= 1; } - // UNWRAP: we checked above that `n` is greater than 0 and that means that there is at - // least one delta that we will remove. - let earliest_record_id = earliest_record_id.unwrap(); - - // We got the earliest record ID that we will remove. To obtain the new live range start - // we need to get the ID of the element prior to that, hence `prev`. - // - // UNWRAP: `prev` returns `None` iff the record ID is nil. We know that `earliest_record_id` - // can't be nil because there were some elements in the log that we removed. - let new_end_live = earliest_record_id.prev().unwrap(); + // The new end of the live range is the last retained delta, or nil if none is left. The + // record before the earliest removed one is not used: it may have expired already, and + // would come back after reopening. + let new_end_live = in_memory + .log + .back() + .map(|(id, _)| *id) + .unwrap_or_else(RecordId::nil); // Set pending truncate to the new end live. // diff --git a/nomt/src/seglog/mod.rs b/nomt/src/seglog/mod.rs index eaa17a6aeb..e91b71f218 100644 --- a/nomt/src/seglog/mod.rs +++ b/nomt/src/seglog/mod.rs @@ -57,14 +57,6 @@ impl RecordId { RecordId(self.0 + 1) } - pub fn prev(&self) -> Option { - if self.0 == 0 { - None - } else { - Some(RecordId(self.0 - 1)) - } - } - fn bytes(&self) -> [u8; 8] { self.0.to_le_bytes() } From c6101d7c0043220dbf50985c0d7575d70dee9e38 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 13 Oct 2026 14:50:48 +0200 Subject: [PATCH 06/12] Drain in-flight work before propagating commit errors Several commit paths returned on the first error while sibling tasks or submitted writes were still running: leaf and branch workers, the I/O completions in update, the bbn/ln fsyncs, the bitbox WAL writeout, and the post-meta cleanup in Sync. Wait for all of them and then return the first error. Also poison the store when a commit unwinds, not only when it returns an error. Ported from 7be9540. Sync::sync changed on master since: it already waits for both preparations before the meta write, so that part is dropped. After the meta write the rollback cleanup is now awaited before the beatree task is joined, so that neither an error from the hash-table writeout nor a panic in the beatree task skips it. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Mythos 5.2 Claude-Session: https://claude.ai/code/session_017wb3qEshHAdfkLFsmMCXfc --- nomt/src/beatree/mod.rs | 7 +++-- nomt/src/beatree/ops/update/branch_stage.rs | 6 ++--- nomt/src/beatree/ops/update/leaf_stage.rs | 6 ++--- nomt/src/beatree/ops/update/mod.rs | 7 +++-- nomt/src/bitbox/mod.rs | 10 ++++--- nomt/src/store/mod.rs | 29 ++++++++++++++++----- nomt/src/store/sync.rs | 11 ++++---- nomt/src/task.rs | 27 +++++++++++++++++-- 8 files changed, 76 insertions(+), 27 deletions(-) diff --git a/nomt/src/beatree/mod.rs b/nomt/src/beatree/mod.rs index c231feaee1..c3987db5e4 100644 --- a/nomt/src/beatree/mod.rs +++ b/nomt/src/beatree/mod.rs @@ -486,8 +486,11 @@ impl SyncController { /// This must be called after [`Self::begin_sync`]. pub fn wait_pre_meta(&mut self) -> std::io::Result { join_task(&self.begin_sync_result_rx)?; - self.inner.sync.bbn_fsync.wait()?; - self.inner.sync.ln_fsync.wait()?; + // Both fsyncs have started; wait for both even when one fails. + let bbn_result = self.inner.sync.bbn_fsync.wait(); + let ln_result = self.inner.sync.ln_fsync.wait(); + bbn_result?; + ln_result?; // UNWRAP: fsync of bbn and ln above ensures that sync_data is Some. let sync_data = self.inner.sync_data.lock().take().unwrap(); diff --git a/nomt/src/beatree/ops/update/branch_stage.rs b/nomt/src/beatree/ops/update/branch_stage.rs index efda864544..134898a8a3 100644 --- a/nomt/src/beatree/ops/update/branch_stage.rs +++ b/nomt/src/beatree/ops/update/branch_stage.rs @@ -10,7 +10,7 @@ use crate::{ index::Index, Key, }, - task::{join_task, spawn_task}, + task::{join_task_result, spawn_task}, }; use super::branch_updater::{BaseBranch, BranchUpdater, DigestResult as BranchDigestResult}; @@ -88,8 +88,8 @@ pub fn run( let mut output = BranchStageOutput::default(); let mut branch_changeset: Vec<(Key, Option>)> = vec![]; - for _ in 0..num_workers { - let worker_output = join_task(&worker_result_rx)?; + for completed in 0..num_workers { + let worker_output = join_task_result(&worker_result_rx, num_workers - completed - 1)?; apply_bbn_changes(&mut output, &mut branch_changeset, worker_output); } diff --git a/nomt/src/beatree/ops/update/leaf_stage.rs b/nomt/src/beatree/ops/update/leaf_stage.rs index b29dd4b42f..4fb3a5190d 100644 --- a/nomt/src/beatree/ops/update/leaf_stage.rs +++ b/nomt/src/beatree/ops/update/leaf_stage.rs @@ -23,7 +23,7 @@ use crate::beatree::{ Key, ValueChange, }; use crate::io::{IoCommand, IoHandle, IoKind}; -use crate::task::{join_task, spawn_task}; +use crate::task::{join_task_result, spawn_task}; /// Tracker of all changes that happen to leaves during an update pub type LeavesTracker = super::NodesTracker; @@ -174,8 +174,8 @@ pub fn run( let mut output = LeafStageOutput::default(); output.submitted_io += overflow_io; - for _ in 0..num_workers { - let worker_output = join_task(&worker_result_rx)?; + for completed in 0..num_workers { + let worker_output = join_task_result(&worker_result_rx, num_workers - completed - 1)?; apply_worker_changes(&leaf_reader, &mut output, worker_output); } diff --git a/nomt/src/beatree/ops/update/mod.rs b/nomt/src/beatree/ops/update/mod.rs index 44dbb858cc..060ef20848 100644 --- a/nomt/src/beatree/ops/update/mod.rs +++ b/nomt/src/beatree/ops/update/mod.rs @@ -93,11 +93,14 @@ pub fn update( crate::beatree::writeout::submit_freelist_write(&io_handle, &leaf_store, ln_freelist_pages); crate::beatree::writeout::submit_freelist_write(&io_handle, &bbn_store, bbn_freelist_pages); - // make sure that all write requests succeeded. + // Drain every submitted request, including when an earlier write failed, and keep the first + // error. + let mut write_result = Ok(()); for _ in 0..total_io { // UNWRAP: we receive only what we sent. No `RecvErr` expected. - io_handle.recv().unwrap().result?; + write_result = write_result.and(io_handle.recv().unwrap().result); } + write_result?; let (tx, rx) = crossbeam_channel::bounded(1); let post_io_task = move || { diff --git a/nomt/src/bitbox/mod.rs b/nomt/src/bitbox/mod.rs index 8a19c1b64d..a9aa753691 100644 --- a/nomt/src/bitbox/mod.rs +++ b/nomt/src/bitbox/mod.rs @@ -17,7 +17,7 @@ use crate::{ io::{self, page_pool::FatPage, IoCommand, IoHandle, IoKind, PagePool, PAGE_SIZE}, page_cache::{Page, PageCache}, store::{BucketInfo, DirtyPage}, - task::{join_task, spawn_task, TaskResult}, + task::{spawn_task, unwrap_task_result, TaskResult}, }; use self::{ht_file::HTOffsets, meta_map::MetaMap}; @@ -391,8 +391,12 @@ impl SyncController { /// /// Must be invoked by the sync thread. Blocking. pub fn wait_pre_meta(&self) -> anyhow::Result<()> { - join_task(&self.begin_sync_result_rx)?; - join_task(&self.pre_meta_result_rx)?; + let preparation = self.begin_sync_result_rx.recv().unwrap(); + // If preparation stopped before spawning the WAL writeout, its sender was dropped and + // this returns immediately. + let wal = self.pre_meta_result_rx.recv(); + unwrap_task_result(preparation)?; + unwrap_task_result(wal.expect("successful preparation must report WAL readiness"))?; Ok(()) } diff --git a/nomt/src/store/mod.rs b/nomt/src/store/mod.rs index a3f986baae..c4099f7325 100644 --- a/nomt/src/store/mod.rs +++ b/nomt/src/store/mod.rs @@ -51,6 +51,21 @@ struct Shared { _db_dir_fd: Arc, } +/// Poisons the store unless the commit completes, including when it unwinds. +struct CommitPoisonGuard<'a> { + poisoned: &'a AtomicBool, + complete: bool, +} + +impl Drop for CommitPoisonGuard<'_> { + fn drop(&mut self) { + if !self.complete { + self.poisoned + .store(true, std::sync::atomic::Ordering::Relaxed); + } + } +} + impl Store { /// Open the store with the provided `Options`. pub fn open(o: &crate::Options, page_pool: PagePool) -> anyhow::Result { @@ -290,7 +305,11 @@ impl Store { anyhow::bail!("Store is poisoned due to prior error"); } - if let Err(e) = sync.sync( + let mut poison_guard = CommitPoisonGuard { + poisoned: &self.shared.poisoned, + complete: false, + }; + sync.sync( &self.shared, value_tx, self.shared.pages.clone(), @@ -299,12 +318,8 @@ impl Store { rollback_delta, page_cache, updated_pages, - ) { - self.shared - .poisoned - .store(true, std::sync::atomic::Ordering::Relaxed); - return Err(e); - } + )?; + poison_guard.complete = true; Ok(()) } } diff --git a/nomt/src/store/sync.rs b/nomt/src/store/sync.rs index 12b53b01d5..2b23d2328c 100644 --- a/nomt/src/store/sync.rs +++ b/nomt/src/store/sync.rs @@ -96,15 +96,16 @@ impl Sync { rollback.post_meta(); } - // Finish the beatree sync while the hash-table pages are written out. + // Finish the beatree sync while the hash-table pages are written out, and finish every + // cleanup before propagating an error. let beatree_post_meta = beatree_sync.post_meta(); let bitbox_result = bitbox_sync.post_meta(shared.io_pool.make_handle()); + let rollback_result = rollback_sync + .as_ref() + .map_or(Ok(()), |rollback| rollback.wait_post_meta()); join_task(&beatree_post_meta); bitbox_result?; - - if let Some(ref rollback) = rollback_sync { - rollback.wait_post_meta()?; - } + rollback_result?; Ok(()) } } diff --git a/nomt/src/task.rs b/nomt/src/task.rs index 1a22f5d07c..7251624337 100644 --- a/nomt/src/task.rs +++ b/nomt/src/task.rs @@ -44,9 +44,32 @@ where R: Send + 'static, { // UNWRAP: The sender is not expected to be dropped by the spawned task. - let res = receiver.recv().unwrap(); - match res { + unwrap_task_result(receiver.recv().unwrap()) +} + +/// Propagate a completed task's panic after all required sibling tasks are joined. +pub(crate) fn unwrap_task_result(result: TaskResult) -> R { + match result { Ok(res) => res, Err(err_payload) => std::panic::resume_unwind(err_payload), } } + +/// Join one fallible task, draining the remaining sibling results before +/// returning an error or resuming a panic. Successful results remain streaming. +pub(crate) fn join_task_result( + receiver: &crossbeam_channel::Receiver>>, + remaining: usize, +) -> Result { + let result = receiver.recv().unwrap(); + if !matches!(&result, Ok(Ok(_))) { + for _ in 0..remaining { + // All siblings must stop producing I/O before the failure escapes. + let _ = receiver.recv().unwrap(); + } + } + match result { + Ok(result) => result, + Err(payload) => std::panic::resume_unwind(payload), + } +} From 3418450609049e98b2e15a2e3312d17ff6ce8901 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 23 Nov 2026 16:40:11 +0100 Subject: [PATCH 07/12] tests: cover three of the ported hardening fixes Each of these fails on master and passes on this branch. - ht_write_error: every hash-table page write past 40 MiB fails (RLIMIT_FSIZE). The commit must report it; before 4eb47b5 it returned Ok and the reopened database had a different root. - overflow_leak: one 256 KiB value rewritten 300 times must not grow the leaf file beyond its first 32 MiB step (bc936da). - commit_panic: a commit that panics after the meta write is durable and a later commit attempt on the same handle must not destroy it (7be9540, poison on unwind). Co-Authored-By: Claude Mythos 5.2 Claude-Session: https://claude.ai/code/session_017wb3qEshHAdfkLFsmMCXfc --- nomt/tests/commit_panic.rs | 98 ++++++++++++++++++++++++++++++++++++ nomt/tests/ht_write_error.rs | 74 +++++++++++++++++++++++++++ nomt/tests/overflow_leak.rs | 22 ++++++++ 3 files changed, 194 insertions(+) create mode 100644 nomt/tests/commit_panic.rs create mode 100644 nomt/tests/ht_write_error.rs create mode 100644 nomt/tests/overflow_leak.rs diff --git a/nomt/tests/commit_panic.rs b/nomt/tests/commit_panic.rs new file mode 100644 index 0000000000..5288d16f62 --- /dev/null +++ b/nomt/tests/commit_panic.rs @@ -0,0 +1,98 @@ +use nomt::{ + hasher::Blake3Hasher, KeyReadWrite, Nomt, Options, PanicOnSyncMode, Root, SessionParams, +}; +use std::{path::PathBuf, sync::mpsc, time::Duration}; + +fn key(first: u8) -> [u8; 32] { + let mut k = [0u8; 32]; + k[0] = first; + k +} + +fn open(path: &PathBuf, panic_on_sync: Option) -> 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); + if let Some(mode) = panic_on_sync { + o.panic_on_sync(mode); + } + Nomt::open(o).unwrap() +} + +fn commit_catching(nomt: &Nomt, writes: &[(u8, u8)]) -> (Root, bool) { + let session = nomt.begin_session(SessionParams::default()); + let actuals = writes + .iter() + .map(|&(k, v)| (key(k), KeyReadWrite::Write(Some(vec![v])))) + .collect::>(); + for (k, _) in &actuals { + session.warm_up(*k); + } + let finished = session.finish(actuals).unwrap(); + let root = finished.root(); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| finished.commit(nomt))); + (root, r.is_err()) +} + +// A commit that panicked after the meta write is durable; a later commit attempt on the +// same instance must not destroy it. +#[test] +fn panicked_commit_survives_a_later_commit_attempt() { + let control = PathBuf::from("test/commit_panic_control"); + let _ = std::fs::remove_dir_all(&control); + let nomt = open(&control, Some(PanicOnSyncMode::PostMeta)); + let (control_root, panicked) = commit_catching(&nomt, &[(0x00, 1), (0x80, 2)]); + assert!(panicked); + drop(nomt); + let nomt = open(&control, None); + assert_eq!( + nomt.root(), + control_root, + "control: single panicked commit recovers" + ); + drop(nomt); + + let path = PathBuf::from("test/commit_panic"); + let _ = std::fs::remove_dir_all(&path); + + let (tx, rx) = mpsc::channel(); + let thread_path = path.clone(); + std::thread::spawn(move || { + let nomt = open(&thread_path, Some(PanicOnSyncMode::PostMeta)); + let (root1, panicked1) = commit_catching(&nomt, &[(0x00, 1), (0x80, 2)]); + let poisoned_after_first = nomt.is_poisoned(); + let (_, panicked2) = commit_catching(&nomt, &[(0x40, 3)]); + let poisoned_after_second = nomt.is_poisoned(); + drop(nomt); + let _ = tx.send(( + root1, + panicked1, + poisoned_after_first, + panicked2, + poisoned_after_second, + )); + }); + let (root1, panicked1, poisoned_after_first, panicked2, poisoned_after_second) = rx + .recv_timeout(Duration::from_secs(120)) + .expect("commit after a panicked commit hung"); + assert!(panicked1); + eprintln!( + "poisoned after first panic: {poisoned_after_first}; second commit panicked: {panicked2}; poisoned after second: {poisoned_after_second}" + ); + + let nomt = open(&path, None); + assert_eq!(nomt.read(key(0x00)).unwrap(), Some(vec![1])); + assert_eq!(nomt.read(key(0x80)).unwrap(), Some(vec![2])); + assert_eq!( + nomt.root(), + root1, + "first commit's values are durable, but its merkle pages were lost when the second commit replaced the WAL" + ); + assert!( + poisoned_after_first, + "store not poisoned after a commit panicked past the meta write" + ); +} diff --git a/nomt/tests/ht_write_error.rs b/nomt/tests/ht_write_error.rs new file mode 100644 index 0000000000..aaa8798ead --- /dev/null +++ b/nomt/tests/ht_write_error.rs @@ -0,0 +1,74 @@ +mod common; + +use common::Test; +use std::{sync::mpsc, time::Duration}; + +const ACCOUNTS: u64 = 2000; +const FSIZE_LIMIT: u64 = 40 << 20; + +fn set_fsize_limit(limit: u64) { + let lim = libc::rlimit { + rlim_cur: limit, + rlim_max: libc::RLIM_INFINITY, + }; + unsafe { + libc::signal(libc::SIGXFSZ, libc::SIG_IGN); + assert_eq!(libc::setrlimit(libc::RLIMIT_FSIZE, &lim), 0); + } +} + +// A commit whose hash-table page writes fail must not report success. +// +// RLIMIT_FSIZE makes every write past 40 MiB fail with EFBIG. Only the 250 MiB hash-table file +// has pages there, so the WAL, meta and beatree writes of the second commit all succeed. +// This must stay the only test in this binary: the limit is process-wide. +#[test] +fn ht_write_error_is_reported() { + let name = "ht_write_error"; + let mut t = Test::new_with_params(name, 1, 64_000, None, true); + for i in 0..ACCOUNTS { + common::set_balance(&mut t, i, 1000); + } + t.commit(); + + for i in 0..ACCOUNTS { + common::set_balance(&mut t, i, 2000); + } + set_fsize_limit(FSIZE_LIMIT); + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.commit().0)); + drop(t); + let _ = tx.send(r.ok()); + }); + let committed = rx + .recv_timeout(Duration::from_secs(120)) + .expect("commit with failing hash-table writes hung"); + set_fsize_limit(libc::RLIM_INFINITY); + + let Some(committed_root) = committed else { + // The commit reported the failure. That is the correct outcome. + return; + }; + + let mut reference = Test::new_with_params("ht_write_error_reference", 1, 64_000, None, true); + for i in 0..ACCOUNTS { + common::set_balance(&mut reference, i, 3000); + } + let (reference_root, _) = reference.commit(); + + let mut t = Test::new_with_params(name, 1, 64_000, None, false); + assert_eq!( + t.root(), + committed_root, + "root after reopen differs from the root the commit reported" + ); + for i in 0..ACCOUNTS { + common::set_balance(&mut t, i, 3000); + } + let (root, _) = t.commit(); + assert_eq!( + root, reference_root, + "commit reported success, but the reopened database computes a wrong root" + ); +} diff --git a/nomt/tests/overflow_leak.rs b/nomt/tests/overflow_leak.rs new file mode 100644 index 0000000000..963f84cdac --- /dev/null +++ b/nomt/tests/overflow_leak.rs @@ -0,0 +1,22 @@ +mod common; + +use common::Test; + +// Replacing a large value must free the overflow pages of the value it replaces. +// +// The leaf file grows in steps of 8192 pages (32 MiB). One live 256 KiB value fits in the first +// step however often it is rewritten; 300 leaked copies need 19200 pages. +#[test] +fn replaced_overflow_value_is_freed() { + let name = "overflow_leak"; + let mut t = Test::new(name); + for i in 0..300u32 { + t.write_id(0, Some(vec![i as u8; 4096 * 64])); + t.commit(); + } + let ln_len = std::fs::metadata(format!("test/{name}/ln")).unwrap().len(); + assert!( + ln_len <= 8192 * 4096, + "leaf file is {ln_len} bytes for a single live 256 KiB value" + ); +} From 3dd6615d00d2edf5589df7195935bbe5eb10d2af Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Mon, 23 Nov 2026 18:32:10 +0100 Subject: [PATCH 08/12] tests: keep the database on one thread in ht_write_error The test opened the database on the test thread and moved it, with its open session, into a helper thread for the commit that is expected to fail, so that a hang could be reported. A session is about to be tied to the thread that created it, and the test would no longer compile. Do all the database work on the helper thread. Co-Authored-By: Claude Mythos 5.2 Claude-Session: https://claude.ai/code/session_017wb3qEshHAdfkLFsmMCXfc --- nomt/tests/ht_write_error.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/nomt/tests/ht_write_error.rs b/nomt/tests/ht_write_error.rs index aaa8798ead..3d7775b2c0 100644 --- a/nomt/tests/ht_write_error.rs +++ b/nomt/tests/ht_write_error.rs @@ -25,18 +25,19 @@ fn set_fsize_limit(limit: u64) { #[test] fn ht_write_error_is_reported() { let name = "ht_write_error"; - let mut t = Test::new_with_params(name, 1, 64_000, None, true); - for i in 0..ACCOUNTS { - common::set_balance(&mut t, i, 1000); - } - t.commit(); - - for i in 0..ACCOUNTS { - common::set_balance(&mut t, i, 2000); - } - set_fsize_limit(FSIZE_LIMIT); let (tx, rx) = mpsc::channel(); + // The database is used on one thread, which this thread watches for a hang. std::thread::spawn(move || { + let mut t = Test::new_with_params(name, 1, 64_000, None, true); + for i in 0..ACCOUNTS { + common::set_balance(&mut t, i, 1000); + } + t.commit(); + + for i in 0..ACCOUNTS { + common::set_balance(&mut t, i, 2000); + } + set_fsize_limit(FSIZE_LIMIT); let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.commit().0)); drop(t); let _ = tx.send(r.ok()); From d19e1b105e0428fbc339c8208bf2fc13d3aab5dc Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 24 Nov 2026 17:43:18 +0100 Subject: [PATCH 09/12] beatree: explain why the page-size conversions cannot fail Co-Authored-By: Claude Mythos 5.2 --- nomt/src/beatree/branch/node.rs | 1 + nomt/src/beatree/leaf/node.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/nomt/src/beatree/branch/node.rs b/nomt/src/beatree/branch/node.rs index d7436c486d..d4ee4ce1f6 100644 --- a/nomt/src/beatree/branch/node.rs +++ b/nomt/src/beatree/branch/node.rs @@ -46,6 +46,7 @@ pub struct BranchNode { impl AsRef<[u8; PAGE_SIZE]> for BranchNode { fn as_ref(&self) -> &[u8; PAGE_SIZE] { + // UNWRAP: a `FatPage` always derefs to a slice of exactly `PAGE_SIZE` bytes. self.as_slice().try_into().unwrap() } } diff --git a/nomt/src/beatree/leaf/node.rs b/nomt/src/beatree/leaf/node.rs index 1f4a14eed2..dcd782d001 100644 --- a/nomt/src/beatree/leaf/node.rs +++ b/nomt/src/beatree/leaf/node.rs @@ -55,6 +55,7 @@ pub struct LeafNode { impl AsRef<[u8; PAGE_SIZE]> for LeafNode { fn as_ref(&self) -> &[u8; PAGE_SIZE] { + // UNWRAP: a `FatPage` always derefs to a slice of exactly `PAGE_SIZE` bytes. (&*self.inner).try_into().unwrap() } } From 416426b2251400cbfcecae8164293c0d0fabcddf Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 24 Nov 2026 18:36:56 +0100 Subject: [PATCH 10/12] bitbox: read the WAL header with io::read_page Replaces the hand-rolled read loop. The caller only recovers from a non-empty WAL, which is now asserted in debug builds. Co-Authored-By: Claude Mythos 5.2 --- nomt/src/bitbox/wal/read.rs | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/nomt/src/bitbox/wal/read.rs b/nomt/src/bitbox/wal/read.rs index e531a30263..d3260a608b 100644 --- a/nomt/src/bitbox/wal/read.rs +++ b/nomt/src/bitbox/wal/read.rs @@ -40,20 +40,9 @@ pub struct WalBlobReader { impl WalBlobReader { /// Read the sequence even when an uncommitted WAL has an incomplete body. pub(crate) fn read_sync_seqn(page_pool: &PagePool, wal_fd: &File) -> anyhow::Result { - use std::os::unix::fs::FileExt; - - // The WAL uses direct I/O, so both the buffer and requested length stay - // page-aligned. Only the returned prefix may be shorter than a page. - let mut page = page_pool.alloc_fat_page(); - let len = loop { - match wal_fd.read_at(&mut page, 0) { - Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, - result => break result?, - } - }; - if len < 5 { - bail!("Unexpected end of WAL header"); - } + // The caller only recovers from a non-empty WAL, and the WAL is written in whole pages. + debug_assert!(wal_fd.metadata()?.len() > 0, "WAL must not be empty"); + let page = io::read_page(page_pool, wal_fd, 0)?; if page[0] != WAL_ENTRY_TAG_START { bail!("unexpected WAL entry tag at start: {}", page[0]); } From b3b5c3cfd1211075b63db5b9e90739e59fa520b3 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 24 Nov 2026 18:40:35 +0100 Subject: [PATCH 11/12] tests: cover reading the WAL header of short, mistagged and torn WALs Co-Authored-By: Claude Mythos 5.2 --- nomt/src/bitbox/wal/tests.rs | 71 +++++++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/nomt/src/bitbox/wal/tests.rs b/nomt/src/bitbox/wal/tests.rs index 0746579c0e..592fcefe27 100644 --- a/nomt/src/bitbox/wal/tests.rs +++ b/nomt/src/bitbox/wal/tests.rs @@ -1,5 +1,9 @@ use super::{WalBlobBuilder, WalBlobReader, WalEntry}; -use crate::{io::page_pool::PagePool, merkle::ElidedChildren, page_diff::PageDiff}; +use crate::{ + io::{page_pool::PagePool, PAGE_SIZE}, + merkle::ElidedChildren, + page_diff::PageDiff, +}; use std::{fs::OpenOptions, io::Write as _}; #[test] @@ -108,3 +112,68 @@ fn test_write_read() { ); assert_eq!(reader.read_entry().unwrap(), None); } + +fn wal_file_with(contents: &[u8]) -> (tempfile::TempDir, std::fs::File) { + let tempdir = tempfile::tempdir().unwrap(); + let mut wal_fd = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .open(tempdir.path().join("wal")) + .unwrap(); + wal_fd.write_all(contents).unwrap(); + (tempdir, wal_fd) +} + +#[test] +fn read_sync_seqn_rejects_wal_shorter_than_a_page() { + let (_tempdir, wal_fd) = wal_file_with(&[super::WAL_ENTRY_TAG_START; 100]); + assert!(WalBlobReader::read_sync_seqn(&PagePool::new(), &wal_fd).is_err()); +} + +#[test] +fn read_sync_seqn_rejects_bad_start_tag() { + let (_tempdir, wal_fd) = wal_file_with(&[0; PAGE_SIZE]); + assert!(WalBlobReader::read_sync_seqn(&PagePool::new(), &wal_fd).is_err()); +} + +// A sync that never concluded may leave only a prefix of its WAL. The header must still be +// readable, so that recovery can tell the WAL belongs to another sync and discard it. +#[test] +fn read_sync_seqn_reads_torn_wal() { + let mut builder = WalBlobBuilder::new().unwrap(); + builder.reset(69); + let mut diff = PageDiff::default(); + for i in 0..126 { + diff.set_changed(i); + } + for bucket in 0..3 { + builder.write_update( + [bucket as u8; 32], + &diff, + (0..126).map(|x| [x; 32]), + ElidedChildren::new(), + bucket, + ); + } + builder.finalize(); + assert!(builder.as_slice().len() > PAGE_SIZE); + let (_tempdir, wal_fd) = wal_file_with(&builder.as_slice()[..PAGE_SIZE]); + + let page_pool = PagePool::new(); + assert_eq!( + WalBlobReader::read_sync_seqn(&page_pool, &wal_fd).unwrap(), + 69 + ); + + // The body is incomplete: parsing it fails. + let mut reader = WalBlobReader::new(&page_pool, &wal_fd).unwrap(); + let torn = loop { + match reader.read_entry() { + Ok(Some(_)) => continue, + Ok(None) => break false, + Err(_) => break true, + } + }; + assert!(torn); +} From ae68fbc9c27778f05111a74f20686b98d47c131c Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Tue, 24 Nov 2026 23:13:52 +0100 Subject: [PATCH 12/12] tests: reopen after the failed hash-table write in ht_write_error The test stopped as soon as the commit reported the failure, which is what happens since the WAL is kept on a failed hash-table write. So it never checked what that fix is for: the commit's meta is written, its merkle pages are only in the WAL, and reopening has to replay them. Truncating the WAL despite the error left every test green. Reopen after the failure and compare with a database that made the same commits without the fault: the root, every balance, and the root of one more commit that touches every account. The root after opening is read from the root page alone, so the last check is the one that sees the other merkle pages. A commit that reports success is now a failure of the test. The limit makes writes past 40 MiB fail on every run, so that branch never ran. Co-Authored-By: Claude Fable 5.2 --- nomt/tests/ht_write_error.rs | 43 ++++++++++++++++++++++++++---------- 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/nomt/tests/ht_write_error.rs b/nomt/tests/ht_write_error.rs index 3d7775b2c0..ab20e58bbe 100644 --- a/nomt/tests/ht_write_error.rs +++ b/nomt/tests/ht_write_error.rs @@ -17,13 +17,17 @@ fn set_fsize_limit(limit: u64) { } } -// A commit whose hash-table page writes fail must not report success. +// A commit whose hash-table page writes fail must report the failure, and the database must +// come back complete when it is reopened. // // RLIMIT_FSIZE makes every write past 40 MiB fail with EFBIG. Only the 250 MiB hash-table file -// has pages there, so the WAL, meta and beatree writes of the second commit all succeed. +// has pages there, so the WAL, meta and beatree writes of the second commit all succeed. The +// commit is therefore durable: the meta names it, and the WAL holds the merkle pages that did +// not reach the hash table. Reopening must replay them. +// // This must stay the only test in this binary: the limit is process-wide. #[test] -fn ht_write_error_is_reported() { +fn ht_write_error_is_reported_and_recovered() { let name = "ht_write_error"; let (tx, rx) = mpsc::channel(); // The database is used on one thread, which this thread watches for a hang. @@ -47,29 +51,44 @@ fn ht_write_error_is_reported() { .expect("commit with failing hash-table writes hung"); set_fsize_limit(libc::RLIM_INFINITY); - let Some(committed_root) = committed else { - // The commit reported the failure. That is the correct outcome. - return; - }; + assert!( + committed.is_none(), + "commit reported success although hash-table writes failed" + ); + // The same three commits on a database whose writes all succeed. let mut reference = Test::new_with_params("ht_write_error_reference", 1, 64_000, None, true); + for i in 0..ACCOUNTS { + common::set_balance(&mut reference, i, 1000); + } + reference.commit(); + for i in 0..ACCOUNTS { + common::set_balance(&mut reference, i, 2000); + } + let (second_root, _) = reference.commit(); for i in 0..ACCOUNTS { common::set_balance(&mut reference, i, 3000); } - let (reference_root, _) = reference.commit(); + let (third_root, _) = reference.commit(); let mut t = Test::new_with_params(name, 1, 64_000, None, false); assert_eq!( t.root(), - committed_root, - "root after reopen differs from the root the commit reported" + second_root, + "the failed commit wrote its meta, so it must be the state after reopening" ); + for i in 0..ACCOUNTS { + assert_eq!(common::read_balance(&mut t, i), Some(2000)); + } + + // The root above is read from the root page alone. A commit that touches every account + // walks every merkle page, and gets a wrong root if one of them was left behind. for i in 0..ACCOUNTS { common::set_balance(&mut t, i, 3000); } let (root, _) = t.commit(); assert_eq!( - root, reference_root, - "commit reported success, but the reopened database computes a wrong root" + root, third_root, + "merkle pages of the failed commit were not recovered from the WAL" ); }