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/beatree/branch/node.rs b/nomt/src/beatree/branch/node.rs index 21a3cb80b5..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}, @@ -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(), ) } @@ -417,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, @@ -514,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()); } @@ -587,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 @@ -597,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 }; @@ -616,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, ); } @@ -652,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 { @@ -663,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/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/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/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/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; 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 + )); + } +} diff --git a/nomt/src/lib.rs b/nomt/src/lib.rs index 1e82e2cf21..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, @@ -377,7 +398,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 +420,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(()) } @@ -485,8 +511,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)); } @@ -500,9 +525,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 { @@ -517,6 +547,7 @@ impl SessionAccessGuard { Self { _guard: guard, thread_sessions, + _not_send: std::marker::PhantomData, } } } @@ -534,6 +565,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, @@ -796,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; } @@ -838,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; } @@ -878,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()); } @@ -920,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/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/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/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/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}"); + } +} 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" + ); +} 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() + ); +} 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); +} 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); +} 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`.