diff --git a/nomt/src/beatree/README.md b/nomt/src/beatree/README.md index e8237e0b48..abaff60d30 100644 --- a/nomt/src/beatree/README.md +++ b/nomt/src/beatree/README.md @@ -9,7 +9,7 @@ - UBN — upper branch nodes, everything that is not a LN or BBN. - PN — a page number in a storage file. - commit — an operation where a batch of changes applied to the database atomically. -- sync — an operation where one or more commits are flushed to the persistent storage. +- sync — an operation that persists a changeset and publishes the updated Beatree index after the manifest is updated. ## Preliminaries @@ -114,26 +114,20 @@ Next, due to shadow paging we do not overwrite any live data and thus we will on ## Code Design -There is a `Tree` structure, +`Tree` owns the following state: -Logically the `Tree` owns the following pieces of data (logically, non-exhausive): +- the in-memory index of bottom-level branch nodes; +- the leaf cache and the leaf and branch page stores; +- the I/O handles, sync workers, and read-transaction counter. -- sequence number. Incremented by each `commit`. -- branch node pool -- staging map (btreemap or hashmap that store the key value pairs): - - primary staging map - - secondary staging map +It provides these operations: -and offers the following logical operations: +- `open(...)` opens the stores and reconstructs the index from the branch pages. +- `lookup(key)` reads through the current index, using cached leaves or loading pages from disk. +- `read_transaction()` captures the index as of the last finished sync. The transaction keeps that view until it is dropped. +- `sync()` acquires the sync mutex and returns a `SyncController`. The controller accepts the changeset and coordinates persistence and publication. -- `open() → Tree`, open or recover the database from the given wal instance. -- `commit([KV])`. Change the btree in the specified way. After this returns the get method below will return the new data. -- `lookup(K)`, -- `sync()`, dump the current changes to the underlying storage medium. Doesn't block commits. Blocks on sync. - > NOTE: in practice this could take different forms, e.g. it could be split into several methods (one for writing WAL, second for syncing, etc). - -`commit` stores write are stored in the primary staging map. Commit does not alter the index. -`lookup` first checks the primary staging and if not found checks the secondary staging and if not found checks the index and hits the disk. +There are no staging maps. Each sync receives its changeset directly, and lookups see the new values only after the updated index is published. ### Branch Node Pool @@ -173,19 +167,15 @@ node_pointers: [LNPN or BNID] // n * 32 ### `sync` op -`sync` works as follows: +The sync protocol is: -- assert that the secondary staging is empty. -- move the primary staging to secondary staging. - (from this point on, the commits will be editing the primary staging.) -- a new version of the index is built from the secondary staging. - - the untouched nodes from the previous index are reused as is via references. -- then atomically - - the secondary staging is discarded. - - the new index replaces the old one. - - the nodes of the old index are freed up. - - the new BBNs and LNs are dumped into io engine and other sync-stuff is performed like metadata fsync. +1. `Tree::sync()` acquires the sync mutex, which the controller holds throughout the operation. +2. `begin_sync(changeset)` starts an asynchronous task that collects the changes into a vector, sorts them by key, and rejects repeated keys. +3. `prepare_sync` waits for outstanding read transactions to finish, then clones the current index and storage handles. The update builds a new index using copy-on-write and writes the changed leaf, branch, overflow, and freelist pages. +4. `wait_pre_meta()` waits for preparation and both store fsyncs, then returns the metadata needed to update the manifest. The caller writes the manifest before proceeding. +5. `post_meta()` starts a task that waits for the cache updates and eviction to finish, then calls `finish_sync` to replace the shared index under a write lock. The caller must join this task before completing the commit. +At the Beatree level, a read transaction created after the preparation's reader wait and before the index swap retains the previous view even after the sync finishes. The next sync waits for it to be dropped before reusing freed pages. At the NOMT level, `access_lock` excludes readers throughout a commit. ### BBN Dumper @@ -221,18 +211,9 @@ There are 3 essential btree handling operations: #### Update -The btree update algorithm accepts: - -1. a list of key value pairs, -2. a handle to the Branch Node Pool. -3. the commit sequence number - -The algorithm is expected to build a new tree that reflects changes after adding or removing the specified key pairs. The algorithm returns: +`ops::update` consumes a vector of `(Key, ValueChange)` pairs sorted by key with no repeated keys, along with the current index, caches, stores, and worker and I/O handles. `begin_sync` establishes the ordering and uniqueness requirements before calling it. -- the BNID of the root of the new tree. -- the list of BNIDs of the new BBNs. -- the list of BNIDs of nodes obsoleted by the new tree. -- the list of LNPNs of newly created leaves, the list of LNPNs of obsoleted leaves. +The leaf stage applies the value changes and produces changes to leaf page references. The branch stage applies those changes to a copy of the index. After writing the pages and updated freelists, the algorithm returns the new store metadata, the new index, and a receiver for completion of cache updates, eviction, and deferred drops. The caller waits for that work before publishing the index. #### Reconstruct diff --git a/nomt/src/beatree/iterator.rs b/nomt/src/beatree/iterator.rs index aaaa676770..4806bf52dc 100644 --- a/nomt/src/beatree/iterator.rs +++ b/nomt/src/beatree/iterator.rs @@ -1,12 +1,7 @@ //! Database iterators over the Beatree. -use std::{ - cmp::Ordering, - ops::{Range, RangeFrom}, - sync::Arc, -}; +use std::{ops::Range, sync::Arc}; -use imbl::ordmap::{Iter as OrdMapIter, OrdMap}; use nomt_core::trie::ValueHash; use super::{ @@ -14,12 +9,11 @@ use super::{ branch::node::{get_key, BranchNode}, index::Index, leaf::node::LeafNode, - Key, LeafNodeRef, ValueChange, + Key, LeafNodeRef, }; /// An iterator over the state of the beatree at some particular point. /// -/// This combines the in-memory overlays with the state of the leaf pages on the disk. /// This iterator does not handle the fetching of pages internally, but instead provides the needed /// page numbers. The [`super::ReadTransaction`]` will provide facilities for dispatching I/O with a /// provided handle. @@ -29,20 +23,12 @@ use super::{ /// that the standard iterator combinators can't be used with it, making it less versatile than a /// typical Rust iterator. pub struct BeatreeIterator { - memory_values: StagingIterator, leaf_values: LeafIterator, } impl BeatreeIterator { - pub(super) fn new( - primary_staging: OrdMap, - secondary_staging: Option>, - bbn_index: Index, - start: Key, - end: Option, - ) -> Self { + pub(super) fn new(bbn_index: Index, start: Key, end: Option) -> Self { BeatreeIterator { - memory_values: StagingIterator::new(primary_staging, secondary_staging, start, end), leaf_values: LeafIterator::new(bbn_index, start, end), } } @@ -56,74 +42,7 @@ impl BeatreeIterator { /// Values can take the form of regular values (stored in-line in the leaf) or overflow values, /// which only store metadata about the value. pub fn next<'a>(&'a mut self) -> Option> { - enum Action { - TakeLeaf, - TakeMemory, - } - - let action = loop { - match (self.leaf_values.peek_key(), self.memory_values.peek()) { - (None, None) => return None, - (Some(_), None) => break Action::TakeLeaf, - (None, Some((_, ValueChange::Delete))) => { - // skip deleted in-memory values unless they correspond to a leaf value. - let _ = self.memory_values.next(); - continue; - } - (None, Some(_)) => break Action::TakeMemory, - (Some((leaves_key, leaf_pending)), Some((memory_key, memory_value))) => { - match (super::key_cmp(memory_key, &leaves_key), memory_value) { - (Ordering::Less, ValueChange::Delete) => { - // skip deleted in-memory values that don't correspond to a leaf value. - // this can happen when the item was inserted in the earlier overlay, - // having never existed on-disk, and then deleted also in memory. - // we can just skip these safely. - let _ = self.memory_values.next(); - continue; - } - (Ordering::Less, _) => { - // the next memory key is before the next leaf key. take the memory - // value. - break Action::TakeMemory; - } - (Ordering::Equal, _) if leaf_pending => { - // the keys are equal, but the leaf is pending so we are blocked - // until the next page is supplied. - return Some(IterOutput::Blocked); - } - (Ordering::Equal, ValueChange::Delete) => { - // skip both values if they are equal but the in-memory version has - // been deleted. - let _ = self.leaf_values.next(); - let _ = self.memory_values.next(); - continue; - } - (Ordering::Equal, _) => { - // skip the leaf value if they are equal but the in-memory version - // exists. - let _ = self.leaf_values.next(); - break Action::TakeMemory; - } - (Ordering::Greater, _) => { - // the next leaf key is before the next memory key. take the leaf value. - break Action::TakeLeaf; - } - } - } - } - }; - - match action { - Action::TakeLeaf => self.leaf_values.next(), - Action::TakeMemory => match self.memory_values.next().unwrap() { - // PANIC: this case is checked previously. - (_, ValueChange::Delete) => panic!(), - (k, ValueChange::Insert(val)) => return Some(IterOutput::Item(*k, val)), - (k, ValueChange::InsertOverflow(ref overflow_cell, ref value_hash)) => { - return Some(IterOutput::OverflowItem(*k, *value_hash, overflow_cell)) - } - }, - } + self.leaf_values.next() } /// Get an iterator over the next leaf page numbers needed by the iterator. @@ -217,27 +136,14 @@ impl LeafIterator { return iter; }; - let separator = get_key(&branch, index_in_branch); iter.state = LeafIteratorState::Blocked { branch, index_in_branch, - separator, last: None, }; iter } - // the bool, if `true`, indicates that the key is pending (a new leaf is needed). - fn peek_key(&mut self) -> Option<(Key, bool)> { - match self.state { - LeafIteratorState::Done { .. } => None, - LeafIteratorState::Blocked { ref separator, .. } => Some((*separator, true)), - LeafIteratorState::Proceeding { ref current, .. } => { - Some((current.leaf.key(current.index), false)) - } - } - } - fn next<'a>(&'a mut self) -> Option> { // Most steps remain within the same leaf. Advance its cursor in place instead // of moving the entire state, including its branch and leaf handles, twice. @@ -344,10 +250,9 @@ impl LeafIterator { } Some(k) => { // UNWRAP: items returned in `next_key` always exist in index. - let (separator, branch) = self.index.lookup(k).unwrap(); + let (_, branch) = self.index.lookup(k).unwrap(); LeafIteratorState::Blocked { index_in_branch: 0, - separator, branch, last: Some(last), } @@ -361,7 +266,6 @@ impl LeafIterator { { LeafIteratorState::Blocked { index_in_branch: next_index_in_branch, - separator, branch, last: Some(last), } @@ -485,7 +389,6 @@ enum LeafIteratorState { Blocked { branch: Arc, index_in_branch: usize, - separator: Key, // this ensures that borrows can be kept valid. last: Option, }, @@ -499,109 +402,6 @@ enum LeafIteratorState { }, } -struct StagingIterator { - primary: OrdMapOwnedIter, - secondary: Option, -} - -impl StagingIterator { - fn new( - primary_staging: OrdMap, - secondary_staging: Option>, - start: Key, - end: Option, - ) -> Self { - StagingIterator { - primary: OrdMapOwnedIter::new(primary_staging, start, end), - secondary: secondary_staging.map(|s| OrdMapOwnedIter::new(s, start, end)), - } - } - - fn peek<'a>(&'a mut self) -> Option<(&'a Key, &'a ValueChange)> { - let primary_peek = self.primary.peek(); - let secondary_peek = self.secondary.as_mut().and_then(|s| s.peek()); - - match (primary_peek, secondary_peek) { - (None, None) => None, - (Some(x), None) | (None, Some(x)) => Some(x), - (Some(primary), Some(secondary)) => { - if super::key_cmp(primary.0, secondary.0).is_le() { - // if equal, favor the primary (more recent) staging map. - Some(primary) - } else { - Some(secondary) - } - } - } - } - - fn next<'a>(&'a mut self) -> Option<(&'a Key, &'a ValueChange)> { - let primary_peek = self.primary.peek().map(|(k, _)| k); - let secondary_peek = self - .secondary - .as_mut() - .and_then(|s| s.peek()) - .map(|(k, _)| k); - match (primary_peek, secondary_peek) { - (None, None) => None, - (Some(_), None) => self.primary.next(), - (None, Some(_)) => self.next_secondary(), - (Some(primary), Some(secondary)) => { - match super::key_cmp(primary, secondary) { - Ordering::Less => self.primary.next(), - Ordering::Equal => { - // if equal, favor the primary (more recent) staging map. - // consume the secondary item. - // UNWRAP: known to be `Some` - let _ = self.next_secondary(); - self.primary.next() - } - Ordering::Greater => self.next_secondary(), - } - } - } - } - - fn next_secondary<'a>(&'a mut self) -> Option<(&'a Key, &'a ValueChange)> { - self.secondary.as_mut().and_then(|s| s.next()) - } -} - -// This lets us do a range iteration over an `OrdMap` in an owned manner, as a streaming iterator. -struct OrdMapOwnedIter { - _map: OrdMap, - iter: std::iter::Peekable>, -} - -impl OrdMapOwnedIter { - fn peek<'a>(&'a mut self) -> Option<(&'a Key, &'a ValueChange)> { - self.iter.peek().map(|x| (x.0, x.1)) - } - - fn next<'a>(&'a mut self) -> Option<(&'a Key, &'a ValueChange)> { - self.iter.next().map(|x| (x.0, x.1)) - } -} - -impl OrdMapOwnedIter { - fn new(map: OrdMap, start: Key, end: Option) -> Self { - let iter = if let Some(end) = end { - map.range(Range { start, end }) - } else { - map.range(RangeFrom { start }) - }; - - // hack: an owned cursor would be very, very useful instead of doing this. - // SAFETY: the OrdMap is kept alive and not used mutably during the lifetime of this - // struct. - let iter: OrdMapIter<'static, Key, ValueChange> = unsafe { std::mem::transmute(iter) }; - OrdMapOwnedIter { - _map: map, - iter: iter.peekable(), - } - } -} - #[cfg(test)] mod tests { use super::IterOutput; @@ -612,10 +412,9 @@ mod tests { index::Index, leaf::node::{LeafBuilder, LeafNode}, ops::bit_ops, - Key, LeafNodeRef, PageNumber, ValueChange, + Key, LeafNodeRef, PageNumber, }; - use imbl::OrdMap; use std::sync::Arc; lazy_static::lazy_static! { @@ -626,10 +425,6 @@ mod tests { x.to_be_bytes().to_vec() } - fn decode_value(v: &[u8]) -> u64 { - u64::from_be_bytes(v.try_into().unwrap()) - } - fn build_leaf(values: Vec<(Key, u64)>) -> (Key, Arc) { let n = values.len(); let total_value_size = n * 8; @@ -684,55 +479,6 @@ mod tests { k } - #[test] - fn overlay_takes_priority() { - let (_, leaf) = build_leaf(vec![ - (key(1), 1), - (key(2), 2), - (key(3), 3), - (key(4), 4), - (key(5), 5), - ]); - - let branch = build_branch(vec![(key(0), 69.into())]); - let index = build_index(vec![branch.clone()]); - - let secondary_staging = vec![ - (key(1), ValueChange::Delete), - (key(2), ValueChange::Insert(encode_value(200))), - (key(3), ValueChange::Insert(encode_value(300))), - ] - .into_iter() - .collect::>(); - - let primary_staging = vec![ - (key(3), ValueChange::Delete), - (key(4), ValueChange::Insert(encode_value(400))), - ] - .into_iter() - .collect::>(); - - let mut iterator = BeatreeIterator::new( - primary_staging, - Some(secondary_staging), - index, - Key::default(), - None, - ); - let mut collected = Vec::new(); - while let Some(iter_output) = iterator.next() { - match iter_output { - IterOutput::Blocked => iterator.provide_leaf(LeafNodeRef { - inner: leaf.clone(), - }), - IterOutput::Item(key, value) => collected.push((key, decode_value(value))), - IterOutput::OverflowItem(_, _, _) => panic!(), - } - } - - assert_eq!(collected, vec![(key(2), 200), (key(4), 400), (key(5), 5)]); - } - #[test] fn needed_leaves_is_accurate() { // split across 2 branches @@ -742,7 +488,7 @@ mod tests { let index = build_index(vec![branch_1.clone(), branch_2.clone()]); let get_needed = |start, end| { - let iter = BeatreeIterator::new(OrdMap::new(), None, index.clone(), start, end); + let iter = BeatreeIterator::new(index.clone(), start, end); iter.needed_leaves().map(|pn| pn.0).collect::>() }; @@ -763,7 +509,7 @@ mod tests { { let start = key(2); let mut leaves = vec![leaf_1.clone(), leaf_2.clone()].into_iter(); - let mut iter = BeatreeIterator::new(OrdMap::new(), None, index.clone(), start, None); + let mut iter = BeatreeIterator::new(index.clone(), start, None); while let Some(output) = iter.next() { match output { IterOutput::Blocked => iter.provide_leaf(LeafNodeRef { @@ -785,13 +531,7 @@ mod tests { { let end = key(7); let mut leaves = vec![leaf_1.clone(), leaf_2.clone()].into_iter(); - let mut iter = BeatreeIterator::new( - OrdMap::new(), - None, - index.clone(), - Key::default(), - Some(end), - ); + let mut iter = BeatreeIterator::new(index.clone(), Key::default(), Some(end)); while let Some(output) = iter.next() { match output { IterOutput::Blocked => iter.provide_leaf(LeafNodeRef { @@ -808,13 +548,7 @@ mod tests { { let end = key(4); let mut leaves = vec![leaf_1.clone()].into_iter(); - let mut iter = BeatreeIterator::new( - OrdMap::new(), - None, - index.clone(), - Key::default(), - Some(end), - ); + let mut iter = BeatreeIterator::new(index.clone(), Key::default(), Some(end)); while let Some(output) = iter.next() { match output { IterOutput::Blocked => iter.provide_leaf(LeafNodeRef { @@ -838,13 +572,7 @@ mod tests { { let end = key(7); let mut leaves = vec![leaf_1.clone(), leaf_2.clone()].into_iter(); - let mut iter = BeatreeIterator::new( - OrdMap::new(), - None, - index.clone(), - Key::default(), - Some(end), - ); + let mut iter = BeatreeIterator::new(index.clone(), Key::default(), Some(end)); while let Some(output) = iter.next() { match output { IterOutput::Blocked => iter.provide_leaf(LeafNodeRef { diff --git a/nomt/src/beatree/mod.rs b/nomt/src/beatree/mod.rs index c231feaee1..b83c174289 100644 --- a/nomt/src/beatree/mod.rs +++ b/nomt/src/beatree/mod.rs @@ -2,13 +2,12 @@ use allocator::{Store, StoreReader, FREELIST_EMPTY}; use anyhow::{Context, Result}; use branch::BRANCH_NODE_SIZE; use crossbeam_channel::{Receiver, Sender}; -use imbl::OrdMap; use leaf::node::MAX_LEAF_VALUE_SIZE; use nomt_core::trie::ValueHash; use ops::overflow; use parking_lot::{ArcMutexGuard, Condvar, Mutex, RwLock}; -use std::{fs::File, mem, path::Path, sync::Arc}; +use std::{fs::File, path::Path, sync::Arc}; use threadpool::ThreadPool; use crate::{ @@ -67,12 +66,6 @@ struct Shared { leaf_store: Store, bbn_store: Store, leaf_store_rd: StoreReader, - /// Primary staging collects changes that are committed but not synced yet. Upon sync, changes - /// from here are moved to secondary staging. - primary_staging: OrdMap, - /// Secondary staging collects committed changes that are currently being synced. This is None - /// if there is no sync in progress. - secondary_staging: Option>, leaf_cache: leaf_cache::LeafCache, } @@ -83,15 +76,6 @@ struct Sync { ln_fsync: Arc, } -impl Shared { - fn take_staged_changeset(&mut self) -> OrdMap { - assert!(self.secondary_staging.is_none()); - let staged = mem::take(&mut self.primary_staging); - self.secondary_staging = Some(staged.clone()); - staged - } -} - impl Tree { pub fn open( page_pool: PagePool, @@ -134,8 +118,6 @@ impl Tree { leaf_store_rd: StoreReader::new(leaf_store.clone(), io_pool.page_pool().clone()), leaf_store, bbn_store, - primary_staging: OrdMap::new(), - secondary_staging: None, leaf_cache: leaf_cache::LeafCache::new(32, leaf_cache_size), }; @@ -154,21 +136,11 @@ impl Tree { }) } - /// Lookup a key in the btree. This blocks the current thread. + /// Lookup a key in the btree as of the last finished sync. This blocks the current thread. + /// + /// Changes passed to a sync are not visible until that sync finishes. pub fn lookup(&self, key: Key) -> Option> { let shared = self.shared.read(); - - // First look up in the primary staging which contains the most recent changes. - if let Some(val) = shared.primary_staging.get(&key) { - return val.as_option().map(|v| v.to_vec()); - } - - // Then check the secondary staging which is a bit older, but fresher still than the btree. - if let Some(val) = shared.secondary_staging.as_ref().and_then(|x| x.get(&key)) { - return val.as_option().map(|v| v.to_vec()); - } - - // Finally, look up in the btree. ops::lookup_blocking( key, &shared.bbn_index, @@ -200,7 +172,7 @@ impl Tree { } } - /// Initiate a new read transaction, as-of the current state of the last commit. + /// Initiate a new read transaction, as of the last finished sync. /// This blocks new sync operations from starting until it is dropped. pub fn read_transaction(&self) -> ReadTransaction { // Increment the count. This will block any sync from starting between now and the point @@ -209,8 +181,6 @@ impl Tree { let shared = self.shared.read(); let inner = Arc::new(ReadTransactionInner { bbn_index: shared.bbn_index.clone(), - primary_staging: shared.primary_staging.clone(), - secondary_staging: shared.secondary_staging.clone(), leaf_store: StoreReader::new(shared.leaf_store.clone(), shared.page_pool.clone()), leaf_cache: shared.leaf_cache.clone(), read_counter: self.read_transaction_counter.clone(), @@ -219,24 +189,8 @@ impl Tree { ReadTransaction { inner } } - /// Commit a set of changes to the btree. - /// - /// The changeset is a list of key value pairs to be added or removed from the btree. - /// The changeset is applied atomically. If the changeset is empty, the btree is not modified. - // There might be some temptation to unify this with prepare_sync, but this should not be done - // because in the future sync and commit will be called on different threads at different times. - fn commit( - shared: &Arc>, - changeset: impl IntoIterator, - ) { - let mut inner = shared.write(); - let staging = &mut inner.primary_staging; - for (key, value) in changeset { - staging.insert(key, value); - } - } - - /// Dump all changes performed by commits to the underlying storage medium. + /// Write `changeset` to the underlying storage medium. The changeset must be sorted by key with + /// no key repeated. /// The returned received indicates that all eviction has completed and it is safe to swap the /// index. This receiver must be blocked on before finishing sync. /// @@ -246,9 +200,9 @@ impl Tree { sync: &Sync, shared: &Arc>, read_transaction_counter: &ReadTransactionCounter, + changeset: Vec<(Key, ValueChange)>, ) -> std::io::Result<(SyncData, Index, Receiver>)> { // Take the shared lock. Briefly. - let staged_changeset; let bbn_index; let page_pool; let leaf_cache; @@ -291,8 +245,11 @@ impl Tree { // It is safe for a read transaction to be created here, since it follows the conclusion // of the most recent sync and therefore references no logically free pages. - let mut shared = shared.write(); - staged_changeset = shared.take_staged_changeset(); + // Keep the write lock. A read lock appears safe because the sync mutex serializes + // index updates; snapshot and concurrent-lookup checks passed with both modes. + // `Nomt` already holds `access_lock` for writing throughout the commit, so there + // is no demonstrated benefit. Revisit only if the concurrency model changes. + let shared = shared.write(); bbn_index = shared.bbn_index.clone(); page_pool = shared.page_pool.clone(); leaf_cache = shared.leaf_cache.clone(); @@ -320,7 +277,7 @@ impl Tree { // + All necessary page writes will be issued to the store and their completion waited // upon. However, these changes are not reflected until `finish_sync`. ops::update( - staged_changeset.clone(), + changeset, bbn_index, leaf_cache, leaf_store, @@ -336,7 +293,6 @@ impl Tree { fn finish_sync(shared: &Arc>, bbn_index: Index) { // Take the shared lock again to complete the update to the new shared state let mut shared = shared.write(); - shared.secondary_staging = None; shared.bbn_index = bbn_index; } } @@ -444,7 +400,9 @@ struct SharedSyncController { impl SyncController { /// Begins the sync process. /// - /// Accepts a list of changes to be committed to the btree. + /// Accepts a list of changes to be committed to the btree. A key must not appear more than + /// once; otherwise the sync fails. The changes are not visible to lookups or read transactions + /// until the sync finishes. /// /// Non-blocking. pub fn begin_sync( @@ -453,10 +411,21 @@ impl SyncController { ) { let inner = self.inner.clone(); let begin_sync_task = move || { - Tree::commit(&inner.shared, changeset); + let mut changeset: Vec<_> = changeset.into_iter().collect(); + changeset.sort_unstable_by(|a, b| a.0.cmp(&b.0)); + if changeset.windows(2).any(|w| w[0].0 == w[1].0) { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "beatree changeset contains a repeated key", + )); + } - let (out_meta, out_bbn_index, out_pre_swap_rx) = - Tree::prepare_sync(&inner.sync, &inner.shared, &inner.read_transaction_counter)?; + let (out_meta, out_bbn_index, out_pre_swap_rx) = Tree::prepare_sync( + &inner.sync, + &inner.shared, + &inner.read_transaction_counter, + changeset, + )?; let mut sync_data = inner.sync_data.lock(); *sync_data = Some(out_meta); @@ -515,8 +484,8 @@ impl SyncController { } } -/// A read-transaction freezes a read-only state of the beatree as-of the last commit and enables -/// lookups while it is alive. +/// A read-transaction freezes a read-only state of the beatree as of the last finished sync and +/// enables lookups while it is alive. /// /// The existence of a read transaction blocks new `Sync`s from starting, but may start when /// a sync is already ongoing and does not block an ongoing sync from completing. @@ -524,8 +493,7 @@ impl SyncController { /// This is because sync may perform destructive changes to leaves, invalidating the read /// transaction. /// -/// Further commits may be performed while the read transaction is live, but they won't be reflected -/// within the transaction. +/// A read transaction started during a sync does not reflect that sync's changes. /// /// This is cheap to clone. #[derive(Clone)] @@ -535,8 +503,6 @@ pub struct ReadTransaction { struct ReadTransactionInner { bbn_index: Index, - primary_staging: OrdMap, - secondary_staging: Option>, leaf_store: StoreReader, leaf_cache: LeafCache, read_counter: ReadTransactionCounter, @@ -545,13 +511,7 @@ struct ReadTransactionInner { impl ReadTransaction { /// Create a new iterator with the given half-open start and end range. pub fn iterator(&self, start: Key, end: Option) -> BeatreeIterator { - BeatreeIterator::new( - self.inner.primary_staging.clone(), - self.inner.secondary_staging.clone(), - self.inner.bbn_index.clone(), - start, - end, - ) + BeatreeIterator::new(self.inner.bbn_index.clone(), start, end) } /// Initiate an asynchronous leaf page fetch. This may return immediately if the leaf is cached. @@ -593,21 +553,6 @@ impl ReadTransaction { io_handle: &IoHandle, user_data: u64, ) -> Result>, AsyncLookup> { - // First look up in the primary staging which contains the most recent changes. - if let Some(val) = self.inner.primary_staging.get(&key) { - return Ok(val.as_option().map(|v| v.to_vec())); - } - - // Then check the secondary staging which is a bit older, but fresher still than the btree. - if let Some(val) = self - .inner - .secondary_staging - .as_ref() - .and_then(|x| x.get(&key)) - { - return Ok(val.as_option().map(|v| v.to_vec())); - } - let leaf_pn = match ops::partial_lookup(key, &self.inner.bbn_index) { None => return Ok(None), Some(pn) => pn, @@ -803,3 +748,48 @@ struct ReadTransactionCounterInner { read_transactions: Mutex, cvar: Condvar, } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sync_rejects_repeated_key() { + let dir = tempfile::tempdir().unwrap(); + let open = |name| { + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .open(dir.path().join(name)) + .unwrap(); + file.set_len(BRANCH_NODE_SIZE as u64).unwrap(); + Arc::new(file) + }; + let page_pool = PagePool::new(); + let io_pool = crate::io::start_test_io_pool(1, page_pool.clone()); + let tree = Tree::open( + page_pool, + &io_pool, + 0, + 0, + 1, + 1, + open("bbn"), + open("ln"), + 1, + 16, + ) + .unwrap(); + + let mut sync = tree.sync(); + sync.begin_sync(vec![ + ([1; 32], ValueChange::Insert(vec![1])), + ([1; 32], ValueChange::Delete), + ]); + let Err(err) = sync.wait_pre_meta() else { + panic!("sync accepted a repeated key"); + }; + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + } +} diff --git a/nomt/src/beatree/ops/update/leaf_stage.rs b/nomt/src/beatree/ops/update/leaf_stage.rs index c47ad4bfc7..bbb327f15f 100644 --- a/nomt/src/beatree/ops/update/leaf_stage.rs +++ b/nomt/src/beatree/ops/update/leaf_stage.rs @@ -1,7 +1,6 @@ use std::ops::Range; use std::sync::Arc; -use imbl::OrdMap; use threadpool::ThreadPool; use crate::beatree::{ @@ -88,7 +87,7 @@ pub fn run( leaf_reader: StoreReader, leaf_writer: SyncAllocator, io_handle: IoHandle, - changeset: OrdMap, + changeset: Vec<(Key, ValueChange)>, thread_pool: ThreadPool, num_workers: usize, ) -> std::io::Result { @@ -100,18 +99,18 @@ pub fn run( let page_pool = leaf_reader.page_pool().clone(); let changeset = changeset - .iter() + .into_iter() .map(|(k, v)| match v { - ValueChange::Insert(v) => Ok((*k, Some((v.clone(), false)))), + ValueChange::Insert(v) => Ok((k, Some((v, false)))), ValueChange::InsertOverflow(large_value, value_hash) => { let (pages, num_writes) = overflow::chunk(&large_value, &leaf_writer, &page_pool, &io_handle)?; overflow_io += num_writes; - let cell = overflow::encode_cell(large_value.len(), value_hash.clone(), &pages); - Ok((*k, Some((cell, true)))) + let cell = overflow::encode_cell(large_value.len(), value_hash, &pages); + Ok((k, Some((cell, true)))) } - ValueChange::Delete => Ok((*k, None)), + ValueChange::Delete => Ok((k, None)), }) .collect::>>()?; diff --git a/nomt/src/beatree/ops/update/mod.rs b/nomt/src/beatree/ops/update/mod.rs index b7ebc1a49f..d2d81e1906 100644 --- a/nomt/src/beatree/ops/update/mod.rs +++ b/nomt/src/beatree/ops/update/mod.rs @@ -1,5 +1,4 @@ use crossbeam_channel::Receiver; -use imbl::OrdMap; use threadpool::ThreadPool; use std::{collections::BTreeMap, sync::Arc}; @@ -43,9 +42,10 @@ const LEAF_BULK_SPLIT_TARGET: usize = (LEAF_NODE_BODY_SIZE * 3) / 4; /// Change the btree in the specified way. Updates the branch index in-place. /// -/// The changeset is a list of key value pairs to be added or removed from the btree. +/// The changeset is a list of key value pairs to be added or removed from the btree, sorted by key +/// with no key repeated. pub fn update( - changeset: OrdMap, + changeset: Vec<(Key, ValueChange)>, mut bbn_index: Index, leaf_cache: LeafCache, leaf_store: Store, diff --git a/nomt/src/lib.rs b/nomt/src/lib.rs index 1e82e2cf21..48d82a53c9 100644 --- a/nomt/src/lib.rs +++ b/nomt/src/lib.rs @@ -622,23 +622,18 @@ impl Session { Ok(self.merkle_updater.prove::(path)?) } - /// Finish the session. Provide the actual reads and writes (in sorted order) that are to be - /// considered within the finished session. + /// Finish the session. Provide the actual reads and writes, sorted by key path with no key + /// repeated, that are to be considered within the finished session. /// /// This function blocks until the merkle root and changeset are computed. + /// + /// Fails if the actuals are not strictly sorted by key path. pub fn finish( mut self, actuals: Vec<(KeyPath, KeyReadWrite)>, ) -> anyhow::Result { - if cfg!(debug_assertions) { - // Check that the actuals are sorted by key path. - for i in 1..actuals.len() { - assert!( - actuals[i].0 > actuals[i - 1].0, - "actuals are not sorted at index {}", - i - ); - } + if let Some(i) = (1..actuals.len()).find(|&i| actuals[i].0 <= actuals[i - 1].0) { + anyhow::bail!("actuals are not strictly sorted at index {}", i); } let merkle_update_handle = self.merkle_updater.update_and_prove::( compact_actuals::(&actuals, self.actuals_concurrency), diff --git a/nomt/tests/actuals_order.rs b/nomt/tests/actuals_order.rs new file mode 100644 index 0000000000..ee28d1c702 --- /dev/null +++ b/nomt/tests/actuals_order.rs @@ -0,0 +1,34 @@ +use nomt::{hasher::Blake3Hasher, KeyReadWrite, Nomt, Options, SessionParams}; + +fn setup_nomt(name: &str) -> (tempfile::TempDir, Nomt) { + let dir = tempfile::tempdir().unwrap(); + let mut o = Options::new(); + o.path(dir.path().join(name)); + o.commit_concurrency(1); + let nomt = Nomt::open(o).unwrap(); + (dir, nomt) +} + +#[test] +fn finish_rejects_repeated_key() { + let (_dir, nomt) = setup_nomt("repeated_key"); + let session = nomt.begin_session(SessionParams::default()); + let actuals = vec![ + ([1; 32], KeyReadWrite::Write(Some(vec![1]))), + ([1; 32], KeyReadWrite::Write(None)), + ]; + assert!(session.finish(actuals).is_err()); + assert!(nomt.root().is_empty()); +} + +#[test] +fn finish_rejects_unsorted_keys() { + let (_dir, nomt) = setup_nomt("unsorted_keys"); + let session = nomt.begin_session(SessionParams::default()); + let actuals = vec![ + ([2; 32], KeyReadWrite::Write(Some(vec![2]))), + ([1; 32], KeyReadWrite::Write(Some(vec![1]))), + ]; + assert!(session.finish(actuals).is_err()); + assert!(nomt.root().is_empty()); +}