Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 146 additions & 5 deletions nomt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -269,7 +275,11 @@ impl<T: HashAlgorithm> Nomt<T> {
/// This is used for testing for now.
#[doc(hidden)]
pub fn read(&self, path: KeyPath) -> anyhow::Result<Option<Value>> {
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)
}

Expand All @@ -295,7 +305,8 @@ impl<T: HashAlgorithm> Nomt<T> {
/// 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
Expand All @@ -313,7 +324,7 @@ impl<T: HashAlgorithm> Nomt<T> {
// 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 {
Expand Down Expand Up @@ -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<AtomicUsize> = 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<parking_lot::RawRwLock, ()>,
thread_sessions: Arc<AtomicUsize>,
}

impl SessionAccessGuard {
fn acquire(lock: &Arc<RwLock<()>>) -> 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.
Expand All @@ -488,7 +542,7 @@ pub struct Session<T> {
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<ArcRwLockReadGuard<parking_lot::RawRwLock, ()>>,
access_guard: Option<SessionAccessGuard>,
prev_root: Root,
_marker: std::marker::PhantomData<T>,
}
Expand Down Expand Up @@ -1032,4 +1086,91 @@ mod tests {

is_sync::<crate::Session<Blake3Hasher>>();
}

#[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::<Blake3Hasher>::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::<Blake3Hasher>::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]));
}
}
15 changes: 7 additions & 8 deletions nomt/src/merkle/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -220,7 +220,7 @@ impl UpdatePool {
};

let warm_up = if self.do_warm_up {
Some(spawn_warm_up::<H>(&self.worker_tp, params))
Some(spawn_warm_up::<H>(params))
} else {
None
};
Expand Down Expand Up @@ -562,16 +562,15 @@ struct WarmUpHandle {
output_rx: Receiver<TaskResult<std::io::Result<WarmUpOutput>>>,
}

fn spawn_warm_up<H: HashAlgorithm>(
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<H: HashAlgorithm>(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::<H>(params, warmup_rx, finish_rx),
output_tx,
);
Expand Down
7 changes: 1 addition & 6 deletions nomt/src/rollback/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ struct InMemory {
}

struct Shared {
worker_tp: ThreadPool,
sync_tp: ThreadPool,
in_memory: Mutex<InMemory>,
seglog: Mutex<SegmentedLog>,
Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -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),
Expand All @@ -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,
Expand Down
10 changes: 4 additions & 6 deletions nomt/src/rollback/reverse_delta_worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -61,11 +60,10 @@ pub(super) enum DeltaBuilderCommand {
Join(Sender<()>, Arc<DashMap<KeyPath, Option<Vec<u8>>>>),
}

/// 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<DashMap<KeyPath, Option<Vec<u8>>>>,
) -> (Sender<DeltaBuilderCommand>, Receiver<TaskResult<()>>) {
let (command_tx, command_rx) = crossbeam::channel::unbounded();
Expand All @@ -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)
}
Expand Down
18 changes: 17 additions & 1 deletion nomt/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,23 @@ pub fn spawn_task<F, R>(
});
}

/// 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<F, R>(name: &str, task: F, tx: crossbeam_channel::Sender<TaskResult<R>>)
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.
Expand Down
46 changes: 46 additions & 0 deletions nomt/tests/coexisting_sessions.rs
Original file line number Diff line number Diff line change
@@ -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<Blake3Hasher> {
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<Blake3Hasher>, 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);
}
Loading