diff --git a/nomt/src/beatree/branch/node.rs b/nomt/src/beatree/branch/node.rs index 21a3cb80b5..d4ee4ce1f6 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,13 @@ pub struct BranchNode { pub(super) page: FatPage, } +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() + } +} + impl BranchNode { pub fn new_in(page_pool: &PagePool) -> Self { BranchNode { @@ -55,10 +62,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..dcd782d001 100644 --- a/nomt/src/beatree/leaf/node.rs +++ b/nomt/src/beatree/leaf/node.rs @@ -53,6 +53,13 @@ pub struct LeafNode { pub inner: FatPage, } +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() + } +} + impl LeafNode { #[inline] pub fn n(&self) -> usize { 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 823008ffb5..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}; @@ -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. @@ -96,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); } @@ -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..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); } @@ -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/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 { diff --git a/nomt/src/beatree/ops/update/mod.rs b/nomt/src/beatree/ops/update/mod.rs index b7ebc1a49f..060ef20848 100644 --- a/nomt/src/beatree/ops/update/mod.rs +++ b/nomt/src/beatree/ops/update/mod.rs @@ -93,16 +93,18 @@ 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 || { 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 +140,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 +151,6 @@ impl NodesTracker { pending_base: None, extra_freed: Vec::new(), new_inserted: 0, - deferred_drop_pages: Vec::new(), } } @@ -201,7 +199,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/bitbox/mod.rs b/nomt/src/bitbox/mod.rs index d499e3e2d8..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(()) } @@ -438,17 +442,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..d3260a608b 100644 --- a/nomt/src/bitbox/wal/read.rs +++ b/nomt/src/bitbox/wal/read.rs @@ -38,6 +38,17 @@ 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 { + // 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]); + } + 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/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); +} 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()?; 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, 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 cb1413c821..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() } @@ -409,6 +401,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 +413,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 +445,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 +490,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 +516,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 +690,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 +711,9 @@ where recovery.candidates[i].path.display() ) })?; + if recovery.candidates[i].max == end_live { + break; + } } } @@ -1114,6 +1130,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. 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), + } +} 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..ab20e58bbe --- /dev/null +++ b/nomt/tests/ht_write_error.rs @@ -0,0 +1,94 @@ +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 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. 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_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. + 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()); + }); + let committed = rx + .recv_timeout(Duration::from_secs(120)) + .expect("commit with failing hash-table writes hung"); + set_fsize_limit(libc::RLIM_INFINITY); + + 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 (third_root, _) = reference.commit(); + + let mut t = Test::new_with_params(name, 1, 64_000, None, false); + assert_eq!( + t.root(), + 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, third_root, + "merkle pages of the failed commit were not recovered from the WAL" + ); +} 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" + ); +}