Skip to content
Open
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
18 changes: 15 additions & 3 deletions nomt/src/beatree/allocator/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use crate::io::{self, page_pool::FatPage, IoCommand, IoKind, PagePool, PAGE_SIZE};
use crate::{
io::{self, page_pool::FatPage, IoCommand, IoKind, PagePool, PAGE_SIZE},
metrics::{Metric, Metrics},
};

use crossbeam_channel::{Receiver, Sender};
use parking_lot::{ArcMutexGuard, Mutex};
Expand Down Expand Up @@ -128,16 +131,23 @@ impl Store {

/// A convenience wrapper around a [`Store`]. This wraps the page pool, along with
/// the store.
///
/// This is only used for the leaf store: every read counts towards [`Metric::LnReads`].
#[derive(Clone)]
pub struct StoreReader {
store: Store,
page_pool: PagePool,
metrics: Metrics,
}

impl StoreReader {
/// Create a new [`StoreReader`].
pub fn new(store: Store, page_pool: PagePool) -> Self {
StoreReader { store, page_pool }
pub fn new(store: Store, page_pool: PagePool, metrics: Metrics) -> Self {
StoreReader {
store,
page_pool,
metrics,
}
}

/// Get a reference to the page pool.
Expand All @@ -147,11 +157,13 @@ impl StoreReader {

/// Reads the page with the specified page number. Blocks the current thread.
pub fn query(&self, pn: PageNumber) -> FatPage {
self.metrics.count(Metric::LnReads);
self.store.query(&self.page_pool, pn)
}

/// Create an I/O command for querying a page by number.
pub fn io_command(&self, pn: PageNumber, user_data: u64) -> IoCommand {
self.metrics.count(Metric::LnReads);
self.store.io_command(&self.page_pool, pn, user_data)
}
}
Expand Down
18 changes: 15 additions & 3 deletions nomt/src/beatree/leaf_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use crate::{
beatree::{allocator::PageNumber, leaf::node::LeafNode},
io::PAGE_SIZE,
metrics::{Metric, Metrics},
};
use lru::LruCache;
use parking_lot::{Mutex, MutexGuard};
Expand All @@ -19,7 +20,7 @@ pub struct LeafCache {
impl LeafCache {
/// Create a new cache with the given number of shards and the maximum number of items
/// to hold. `shards` must be non-zero.
pub fn new(shards: usize, leaf_cache_size: usize) -> Self {
pub fn new(shards: usize, leaf_cache_size: usize, metrics: Metrics) -> Self {
let max_items = (leaf_cache_size * 1024 * 1024) / PAGE_SIZE;
let items_per_shard = max_items / shards;
LeafCache {
Expand All @@ -32,15 +33,25 @@ impl LeafCache {
.map(Mutex::new)
.collect::<Vec<_>>(),
shard_assigner: RandomState::new(),
metrics,
}),
}
}

/// Get a cache entry, updating the LRU state.
pub fn get(&self, page_number: PageNumber) -> Option<Arc<LeafNode>> {
let mut shard = self.inner.shard_for(page_number);
let leaf = self
.inner
.shard_for(page_number)
.cache
.get(&page_number)
.cloned();

shard.cache.get(&page_number).map(|x| x.clone())
self.inner.metrics.count(Metric::LeafCacheRequests);
if leaf.is_none() {
self.inner.metrics.count(Metric::LeafCacheMisses);
}
leaf
}

/// Insert a cache entry. This does not evict anything.
Expand Down Expand Up @@ -69,6 +80,7 @@ impl LeafCache {
struct Shared {
shards: Vec<Mutex<Shard>>,
shard_assigner: RandomState,
metrics: Metrics,
}

impl Shared {
Expand Down
21 changes: 18 additions & 3 deletions nomt/src/beatree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use threadpool::ThreadPool;

use crate::{
io::{fsyncer::Fsyncer, FatPage, IoHandle, IoPool, PagePool},
metrics::Metrics,
task::{join_task, spawn_task, TaskResult},
};

Expand Down Expand Up @@ -74,6 +75,7 @@ struct Shared {
/// if there is no sync in progress.
secondary_staging: Option<OrdMap<Key, ValueChange>>,
leaf_cache: leaf_cache::LeafCache,
metrics: Metrics,
}

struct Sync {
Expand Down Expand Up @@ -104,6 +106,7 @@ impl Tree {
ln_file: Arc<File>,
commit_concurrency: usize,
leaf_cache_size: usize,
metrics: Metrics,
) -> Result<Tree> {
let ln_freelist_pn = Some(ln_freelist_pn)
.map(PageNumber)
Expand Down Expand Up @@ -131,12 +134,17 @@ impl Tree {
io_handle: io_pool.make_handle(),
page_pool: io_pool.page_pool().clone(),
bbn_index: index,
leaf_store_rd: StoreReader::new(leaf_store.clone(), io_pool.page_pool().clone()),
leaf_store_rd: StoreReader::new(
leaf_store.clone(),
io_pool.page_pool().clone(),
metrics.clone(),
),
leaf_store,
bbn_store,
primary_staging: OrdMap::new(),
secondary_staging: None,
leaf_cache: leaf_cache::LeafCache::new(32, leaf_cache_size),
leaf_cache: leaf_cache::LeafCache::new(32, leaf_cache_size, metrics.clone()),
metrics,
};

let sync = Sync {
Expand Down Expand Up @@ -211,7 +219,11 @@ impl Tree {
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_store: StoreReader::new(
shared.leaf_store.clone(),
shared.page_pool.clone(),
shared.metrics.clone(),
),
leaf_cache: shared.leaf_cache.clone(),
read_counter: self.read_transaction_counter.clone(),
});
Expand Down Expand Up @@ -255,6 +267,7 @@ impl Tree {
let leaf_store;
let bbn_store;
let io_handle;
let metrics;
{
// Wait for all outstanding read transactions to conclude. This ensures they won't
// be invalidated by any destructive changes.
Expand Down Expand Up @@ -299,6 +312,7 @@ impl Tree {
leaf_store = shared.leaf_store.clone();
bbn_store = shared.bbn_store.clone();
io_handle = shared.io_handle.clone();
metrics = shared.metrics.clone();
}

{
Expand Down Expand Up @@ -329,6 +343,7 @@ impl Tree {
io_handle,
sync.tp.clone(),
sync.commit_concurrency,
metrics,
)
}
}
Expand Down
4 changes: 3 additions & 1 deletion nomt/src/beatree/ops/update/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::beatree::{
Key, SyncData, ValueChange,
};
use crate::io::{IoHandle, PagePool};
use crate::metrics::Metrics;
use crate::task::{spawn_task, TaskResult};

mod branch_ops;
Expand Down Expand Up @@ -54,8 +55,9 @@ pub fn update(
io_handle: IoHandle,
thread_pool: ThreadPool,
workers: usize,
metrics: Metrics,
) -> std::io::Result<(SyncData, Index, Receiver<TaskResult<()>>)> {
let leaf_reader = StoreReader::new(leaf_store.clone(), page_pool.clone());
let leaf_reader = StoreReader::new(leaf_store.clone(), page_pool.clone(), metrics);
let (leaf_writer, leaf_finisher) = leaf_store.start_sync();
let (bbn_writer, bbn_finisher) = bbn_store.start_sync();

Expand Down
10 changes: 6 additions & 4 deletions nomt/src/beatree/ops/update/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use crate::{
Index, ValueChange,
},
io::{start_test_io_pool, IoPool, PagePool},
metrics::Metrics,
};
use lazy_static::lazy_static;
use quickcheck::{Arbitrary, Gen, QuickCheck, TestResult};
Expand Down Expand Up @@ -133,13 +134,14 @@ fn init_beatree() -> TreeData {
.map(|(k, v)| (k, ValueChange::Insert(v)))
.collect(),
Index::default(),
LeafCache::new(1, 1024),
LeafCache::new(1, 1024, Metrics::new(false)),
leaf_store,
bbn_store,
PAGE_POOL.clone(),
IO_POOL.make_handle(),
THREAD_POOL.clone(),
1,
Metrics::new(false),
)
.unwrap();

Expand Down Expand Up @@ -235,11 +237,11 @@ fn exec_leaf_stage(
changeset: BTreeMap<[u8; 32], ValueChange>,
) -> (LeafStageOutput, BTreeSet<PageNumber>) {
let leaf_store = TREE_DATA.leaf_store();
let leaf_reader = StoreReader::new(leaf_store.clone(), PAGE_POOL.clone());
let leaf_reader = StoreReader::new(leaf_store.clone(), PAGE_POOL.clone(), Metrics::new(false));
let (leaf_writer, leaf_finisher) = leaf_store.start_sync();

let bbn_index = &TREE_DATA.bbn_index;
let leaf_cache = LeafCache::new(commit_concurrency, 1024);
let leaf_cache = LeafCache::new(commit_concurrency, 1024, Metrics::new(false));
let leaf_page_numbers = leaf_page_numbers(&bbn_index, changeset.keys().cloned());

let io_handle = IO_POOL.make_handle();
Expand Down Expand Up @@ -278,7 +280,7 @@ fn is_valid_leaf_stage_output(
}

let leaf_store = TREE_DATA.leaf_store();
let leaf_reader = StoreReader::new(leaf_store.clone(), PAGE_POOL.clone());
let leaf_reader = StoreReader::new(leaf_store.clone(), PAGE_POOL.clone(), Metrics::new(false));

for page_number in output.freed_pages {
used_page_numbers.remove(&page_number);
Expand Down
30 changes: 30 additions & 0 deletions nomt/src/bitbox/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ use std::{
atomic::{AtomicU64, AtomicUsize, Ordering},
Arc,
},
time::Instant,
};
use threadpool::ThreadPool;

use crate::{
io::{self, page_pool::FatPage, IoCommand, IoHandle, IoKind, PagePool, PAGE_SIZE},
metrics::{Metric, Metrics},
page_cache::{Page, PageCache},
store::{BucketInfo, DirtyPage},
task::{join_task, spawn_task, TaskResult},
Expand Down Expand Up @@ -113,6 +115,7 @@ pub struct Shared {
ht_fd: File,
sync_tp: ThreadPool,
capacity: usize,
metrics: Metrics,
}

impl DB {
Expand All @@ -124,6 +127,7 @@ impl DB {
page_pool: PagePool,
ht_fd: File,
wal_fd: File,
metrics: Metrics,
) -> anyhow::Result<Self> {
let (store, mut meta_map) = match ht_file::open(num_pages, &page_pool, &ht_fd) {
Ok(x) => x,
Expand Down Expand Up @@ -160,6 +164,7 @@ impl DB {
ht_fd,
sync_tp: ThreadPool::with_name("bitbox-sync".into(), 2),
capacity,
metrics,
}),
})
}
Expand Down Expand Up @@ -551,6 +556,19 @@ impl PageLoader {
probe_sequence: ProbeSequence::new(&page_id, &self.meta_map, &self.shared.seed),
page_id,
state: PageLoadState::Pending,
record_fetch_time: false,
fetch_timer: None,
}
}

/// Create a new page load whose duration is recorded as [`Metric::PageFetchTime`].
///
/// This is meant for loads following a page cache miss. Bulk loads at startup are not timed:
/// they are all queued at once and would dominate the mean.
pub fn start_timed_load(&self, page_id: PageId) -> PageLoad {
PageLoad {
record_fetch_time: self.shared.metrics.is_active(),
..self.start_load(page_id)
}
}

Expand Down Expand Up @@ -584,6 +602,10 @@ impl PageLoader {
user_data,
};

self.shared.metrics.count(Metric::HtReads);
if load.record_fetch_time && load.fetch_timer.is_none() {
load.fetch_timer = Some((Instant::now(), self.shared.metrics.clone()));
}
// UNWRAP: I/O pool is not expected to hangup.
io_handle.send(command).unwrap();
load.state = PageLoadState::Submitted;
Expand All @@ -595,6 +617,11 @@ pub struct PageLoad {
page_id: PageId,
probe_sequence: ProbeSequence,
state: PageLoadState,
/// Whether to record [`Metric::PageFetchTime`]. Only set if metrics are active.
record_fetch_time: bool,
/// Set when the first read is submitted, if `record_fetch_time`. Used to record
/// [`Metric::PageFetchTime`] once the page is found.
fetch_timer: Option<(Instant, Metrics)>,
}

impl PageLoad {
Expand All @@ -613,6 +640,9 @@ impl PageLoad {
pub fn try_complete(&mut self, page: FatPage) -> Option<(FatPage, BucketIndex)> {
assert!(self.needs_completion());
if page[PAGE_SIZE - 32..] == self.page_id.encode() {
if let Some((start, metrics)) = self.fetch_timer.take() {
metrics.record_duration(Metric::PageFetchTime, start.elapsed());
}
Some((page, BucketIndex(self.probe_sequence.bucket())))
} else {
self.state = PageLoadState::Pending;
Expand Down
2 changes: 1 addition & 1 deletion nomt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ impl<T: HashAlgorithm> Nomt<T> {
let metrics = Metrics::new(o.metrics);

let page_pool = PagePool::new();
let store = Store::open(&o, page_pool.clone())?;
let store = Store::open(&o, page_pool.clone(), metrics.clone())?;
let root_page = store.load_page(ROOT_PAGE_ID)?;
let page_cache = PageCache::new(root_page, &o, metrics.clone());
let root = compute_root_node::<T>(&page_cache, &store);
Expand Down
2 changes: 1 addition & 1 deletion nomt/src/merkle/seek.rs
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,7 @@ impl<H: HashAlgorithm> Seeker<H> {

request.note_io();

let load = self.page_loader.start_load(page_id.clone());
let load = self.page_loader.start_timed_load(page_id.clone());
vacant_entry.insert(vec![request_index]);
let slab_index = self.io_slab.insert(IoRequest::Merkle(load));
self.submit_idle_page_load(slab_index);
Expand Down
Loading