diff --git a/nomt/src/lib.rs b/nomt/src/lib.rs index ccf33ff0ba..718ec6aa5f 100644 --- a/nomt/src/lib.rs +++ b/nomt/src/lib.rs @@ -5,7 +5,13 @@ use bitvec::prelude::*; use io::PagePool; use metrics::{Metric, Metrics}; -use std::{mem, sync::Arc}; +use std::{ + mem, + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }, +}; use merkle::{UpdatePool, Updater}; use nomt_core::{ @@ -269,7 +275,11 @@ impl Nomt { /// This is used for testing for now. #[doc(hidden)] pub fn read(&self, path: KeyPath) -> anyhow::Result> { - let _guard = self.access_lock.read(); + let _guard = if thread_has_live_session() { + self.access_lock.read_recursive() + } else { + self.access_lock.read() + }; self.store.load_value(path) } @@ -295,7 +305,8 @@ impl Nomt { /// Create a new [`Session`] object with the given parameters. /// /// This will block if there are any ongoing commits or rollbacks. Multiple sessions may - /// coexist. + /// coexist. A thread that already holds a live session doesn't wait for a commit or rollback + /// queued behind it, which would deadlock. /// /// The [`Session`] is a read-only handle on the database and is used to create a changeset to /// be applied to the database. Sessions provide read interfaces and additionally coordinate @@ -313,7 +324,7 @@ impl Nomt { // indefinitely for us to finish. let access_guard = params .take_global_guard - .then(|| RwLock::read_arc(&self.access_lock)); + .then(|| SessionAccessGuard::acquire(&self.access_lock)); let store = self.store.clone(); let rollback_delta = if params.record_rollback_delta { @@ -471,6 +482,49 @@ impl SessionParams { } } +thread_local! { + /// Live sessions created on this thread. Shared with each session, which may be dropped on + /// another thread. + static THREAD_SESSIONS: Arc = Arc::new(AtomicUsize::new(0)); +} + +fn thread_has_live_session() -> bool { + THREAD_SESSIONS.with(|n| n.load(Ordering::Relaxed) > 0) +} + +/// A session's read guard on `access_lock`. +/// +/// parking_lot's `RwLock` is fair: once a commit or rollback queues for the write side, new +/// 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. +struct SessionAccessGuard { + _guard: ArcRwLockReadGuard, + thread_sessions: Arc, +} + +impl SessionAccessGuard { + fn acquire(lock: &Arc>) -> Self { + let thread_sessions = THREAD_SESSIONS.with(Arc::clone); + let guard = if thread_sessions.load(Ordering::Relaxed) > 0 { + RwLock::read_arc_recursive(lock) + } else { + RwLock::read_arc(lock) + }; + thread_sessions.fetch_add(1, Ordering::Relaxed); + Self { + _guard: guard, + thread_sessions, + } + } +} + +impl Drop for SessionAccessGuard { + fn drop(&mut self) { + self.thread_sessions.fetch_sub(1, Ordering::Relaxed); + } +} + /// A session presents a way of interaction with the trie. /// /// The session enables the application to perform reads and prepare writes. @@ -488,7 +542,7 @@ pub struct Session { witness_mode: WitnessMode, // Note: this needs to be after rollback_delta and merkle_updater in declaration order, // so this is dropped after all read transactions are taken, even when the session is dropped. - access_guard: Option>, + access_guard: Option, prev_root: Root, _marker: std::marker::PhantomData, } @@ -1032,4 +1086,91 @@ mod tests { is_sync::>(); } + + #[test] + fn session_opens_while_commit_waits_for_another_session() { + use super::{KeyReadWrite, Nomt, Options, SessionParams}; + + let dir = tempfile::tempdir().unwrap(); + let mut o = Options::new(); + o.path(dir.path()); + o.hashtable_buckets(4096); + o.io_workers(1); + let nomt = std::sync::Arc::new(Nomt::::open(o).unwrap()); + let key = [1; 32]; + + let first = nomt.begin_session(SessionParams::default()); + let committer = std::thread::spawn({ + let nomt = nomt.clone(); + move || { + nomt.begin_session(SessionParams::default()) + .finish(vec![(key, KeyReadWrite::Write(Some(vec![1])))]) + .unwrap() + .commit(&nomt) + .unwrap() + } + }); + + // Wait until the commit is queued for the write lock behind `first`. + while nomt.access_lock.try_read().is_some() { + std::thread::yield_now(); + } + + // Neither may wait behind the queued commit: it waits for `first`, held by this thread. + let second = nomt.begin_session(SessionParams::default()); + assert_eq!(nomt.read(key).unwrap(), None); + drop((first, second)); + + committer.join().unwrap(); + assert_eq!(nomt.read(key).unwrap(), Some(vec![1])); + } + + #[test] + fn session_on_another_thread_waits_for_queued_commit() { + use super::{KeyReadWrite, Nomt, Options, SessionParams}; + + let dir = tempfile::tempdir().unwrap(); + let mut o = Options::new(); + o.path(dir.path()); + o.hashtable_buckets(4096); + o.io_workers(1); + let nomt = std::sync::Arc::new(Nomt::::open(o).unwrap()); + let key = [1; 32]; + + let first = nomt.begin_session(SessionParams::default()); + let committer = std::thread::spawn({ + let nomt = nomt.clone(); + move || { + nomt.begin_session(SessionParams::default()) + .finish(vec![(key, KeyReadWrite::Write(Some(vec![1])))]) + .unwrap() + .commit(&nomt) + .unwrap() + } + }); + while nomt.access_lock.try_read().is_some() { + std::thread::yield_now(); + } + + // This thread holds no session, so its session must queue behind the commit, or a + // stream of overlapping sessions could hold the commit off indefinitely. + let reader = std::thread::spawn({ + let nomt = nomt.clone(); + move || { + nomt.begin_session(SessionParams::default()) + .read(key) + .unwrap() + } + }); + for _ in 0..10_000 { + if reader.is_finished() { + break; + } + std::thread::yield_now(); + } + drop(first); + + committer.join().unwrap(); + assert_eq!(reader.join().unwrap(), Some(vec![1])); + } } diff --git a/nomt/src/merkle/mod.rs b/nomt/src/merkle/mod.rs index 0e660073e5..56150544f8 100644 --- a/nomt/src/merkle/mod.rs +++ b/nomt/src/merkle/mod.rs @@ -23,7 +23,7 @@ use crate::{ page_cache::{Page, PageCache, ShardIndex}, rw_pass_cell::WritePassEnvelope, store::{BucketIndex, DirtyPage, SharedMaybeBucketIndex, Store}, - task::{join_task, spawn_task, TaskResult}, + task::{join_task, spawn_task, spawn_thread_task, TaskResult}, HashAlgorithm, Witness, WitnessedOperations, WitnessedPath, WitnessedRead, WitnessedWrite, }; use threadpool::ThreadPool; @@ -220,7 +220,7 @@ impl UpdatePool { }; let warm_up = if self.do_warm_up { - Some(spawn_warm_up::(&self.worker_tp, params)) + Some(spawn_warm_up::(params)) } else { None }; @@ -562,16 +562,15 @@ struct WarmUpHandle { output_rx: Receiver>>, } -fn spawn_warm_up( - worker_tp: &ThreadPool, - params: worker::WarmUpParams, -) -> WarmUpHandle { +/// The warm-up runs until its session finishes, so it gets a thread of its own rather than one of +/// the commit workers: coexisting sessions would otherwise occupy all of them. +fn spawn_warm_up(params: worker::WarmUpParams) -> WarmUpHandle { let (warmup_tx, warmup_rx) = channel::unbounded(); let (output_tx, output_rx) = channel::bounded(1); let (finish_tx, finish_rx) = channel::bounded(1); - spawn_task( - &worker_tp, + spawn_thread_task( + "nomt-warm-up", move || worker::run_warm_up::(params, warmup_rx, finish_rx), output_tx, ); diff --git a/nomt/src/rollback/mod.rs b/nomt/src/rollback/mod.rs index 3deaa65b0b..6b4ea953bf 100644 --- a/nomt/src/rollback/mod.rs +++ b/nomt/src/rollback/mod.rs @@ -57,7 +57,6 @@ struct InMemory { } struct Shared { - worker_tp: ThreadPool, sync_tp: ThreadPool, in_memory: Mutex, seglog: Mutex, @@ -93,8 +92,6 @@ impl InMemory { } } -const ROLLBACK_TP_SIZE: usize = 2; - /// This structure manages the rollback log. Modifications to the rollback log are made using /// [`ReverseDeltaBuilder`] supplied to [`Rollback::commit`]. #[derive(Clone)] @@ -126,7 +123,6 @@ impl Rollback { }, )?; let shared = Arc::new(Shared { - worker_tp: ThreadPool::with_name("rollback-worker".into(), ROLLBACK_TP_SIZE), sync_tp: ThreadPool::with_name("rollback-sync".into(), 1), in_memory: Mutex::new(in_memory), seglog: Mutex::new(seglog), @@ -147,8 +143,7 @@ impl Rollback { // generality is primarily for testing. fn delta_builder_inner(&self, store: impl LoadValueAsync) -> ReverseDeltaBuilder { let priors = Arc::new(DashMap::new()); - let (command_tx, worker_result_rx) = - reverse_delta_worker::start(store, &self.shared.worker_tp, priors.clone()); + let (command_tx, worker_result_rx) = reverse_delta_worker::start(store, priors.clone()); ReverseDeltaBuilder { command_tx, diff --git a/nomt/src/rollback/reverse_delta_worker.rs b/nomt/src/rollback/reverse_delta_worker.rs index 42181c8f7c..a83b9390e1 100644 --- a/nomt/src/rollback/reverse_delta_worker.rs +++ b/nomt/src/rollback/reverse_delta_worker.rs @@ -3,13 +3,12 @@ use std::{collections::HashMap, sync::Arc}; use crossbeam::channel::{Receiver, RecvError, Sender}; use dashmap::DashMap; use nomt_core::trie::KeyPath; -use threadpool::ThreadPool; use crate::{ beatree::{self, AsyncLookup, OverflowPageInfo, ReadTransaction}, io::{CompleteIo, FatPage, IoHandle}, overlay::LiveOverlay, - task::{spawn_task, TaskResult}, + task::{spawn_thread_task, TaskResult}, }; /// A trait for asynchronously loading values from the store. @@ -61,11 +60,10 @@ pub(super) enum DeltaBuilderCommand { Join(Sender<()>, Arc>>>), } -/// Start the reverse delta builder. The thread pool must have at least 2 threads or else the worker -/// will never conclude. +/// Start the reverse delta builder on a thread of its own, which runs until the builder is +/// finalized or dropped. pub(super) fn start( store: impl LoadValueAsync, - tp: &ThreadPool, priors: Arc>>>, ) -> (Sender, Receiver>) { let (command_tx, command_rx) = crossbeam::channel::unbounded(); @@ -88,7 +86,7 @@ pub(super) fn start( } }; - spawn_task(&tp, worker_task, worker_result_tx); + spawn_thread_task("rollback-worker", worker_task, worker_result_tx); (command_tx, worker_result_rx) } diff --git a/nomt/src/task.rs b/nomt/src/task.rs index 9f8ca1f6bb..1a22f5d07c 100644 --- a/nomt/src/task.rs +++ b/nomt/src/task.rs @@ -19,7 +19,23 @@ pub fn spawn_task( }); } -/// Blocks waiting for completion of the task spawned with [`spawn_task`]. +/// Like [`spawn_task`], but on a new thread of its own. For tasks that live as long as something +/// the caller holds (e.g. a session), which would otherwise starve a fixed-size pool. +pub fn spawn_thread_task(name: &str, task: F, tx: crossbeam_channel::Sender>) +where + R: Send + 'static, + F: FnOnce() -> R + Send + 'static, +{ + std::thread::Builder::new() + .name(name.to_string()) + .spawn(move || { + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| task())); + let _ = tx.send(res); + }) + .expect("failed to spawn thread"); +} + +/// Blocks waiting for completion of the task spawned with [`spawn_task`] or [`spawn_thread_task`]. /// It requires the receiver associated to the sender used to spawn the task. /// /// Panics if the sender is dropped. diff --git a/nomt/tests/coexisting_sessions.rs b/nomt/tests/coexisting_sessions.rs new file mode 100644 index 0000000000..ecce8022c2 --- /dev/null +++ b/nomt/tests/coexisting_sessions.rs @@ -0,0 +1,46 @@ +use nomt::{hasher::Blake3Hasher, KeyReadWrite, Nomt, Options, SessionParams}; +use nomt_test_utils::account_path; + +fn open(path: &std::path::Path, configure: impl FnOnce(&mut Options)) -> Nomt { + let mut o = Options::new(); + o.path(path); + o.bitbox_seed([0; 16]); + o.hashtable_buckets(4096); + o.io_workers(1); + o.commit_concurrency(1); + configure(&mut o); + Nomt::open(o).unwrap() +} + +/// Finishes the newest of `n` coexisting sessions and commits it once the others are gone. +fn finish_newest_of(db: &Nomt, n: usize) { + let key = account_path(1); + let mut sessions: Vec<_> = (0..n) + .map(|_| db.begin_session(SessionParams::default())) + .collect(); + let newest = sessions.pop().unwrap(); + newest.warm_up(key); + newest.preserve_prior_value(key); + let finished = newest + .finish(vec![(key, KeyReadWrite::Write(Some(vec![1])))]) + .unwrap(); + drop(sessions); + finished.commit(db).unwrap(); + assert_eq!(db.read(key).unwrap(), Some(vec![1])); +} + +#[test] +fn many_coexisting_sessions_with_rollback() { + // Each live session has a reverse-delta worker running until the session ends. + let dir = tempfile::tempdir().unwrap(); + let db = open(dir.path(), |o| o.rollback(true)); + finish_newest_of(&db, 4); +} + +#[test] +fn many_coexisting_sessions_with_warm_up() { + // Each live session has a warm-up worker running until the session finishes. + let dir = tempfile::tempdir().unwrap(); + let db = open(dir.path(), |o| o.warm_up(true)); + finish_newest_of(&db, 4); +}