diff --git a/nomt/src/beatree/allocator/mod.rs b/nomt/src/beatree/allocator/mod.rs index 967f22730e..e46aa92f7f 100644 --- a/nomt/src/beatree/allocator/mod.rs +++ b/nomt/src/beatree/allocator/mod.rs @@ -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}; @@ -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. @@ -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) } } diff --git a/nomt/src/beatree/leaf_cache.rs b/nomt/src/beatree/leaf_cache.rs index 7915f95655..b5510bdb5c 100644 --- a/nomt/src/beatree/leaf_cache.rs +++ b/nomt/src/beatree/leaf_cache.rs @@ -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}; @@ -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 { @@ -32,15 +33,25 @@ impl LeafCache { .map(Mutex::new) .collect::>(), shard_assigner: RandomState::new(), + metrics, }), } } /// Get a cache entry, updating the LRU state. pub fn get(&self, page_number: PageNumber) -> Option> { - 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. @@ -69,6 +80,7 @@ impl LeafCache { struct Shared { shards: Vec>, shard_assigner: RandomState, + metrics: Metrics, } impl Shared { diff --git a/nomt/src/beatree/mod.rs b/nomt/src/beatree/mod.rs index c231feaee1..08ba44b13c 100644 --- a/nomt/src/beatree/mod.rs +++ b/nomt/src/beatree/mod.rs @@ -13,6 +13,7 @@ use threadpool::ThreadPool; use crate::{ io::{fsyncer::Fsyncer, FatPage, IoHandle, IoPool, PagePool}, + metrics::Metrics, task::{join_task, spawn_task, TaskResult}, }; @@ -74,6 +75,7 @@ struct Shared { /// if there is no sync in progress. secondary_staging: Option>, leaf_cache: leaf_cache::LeafCache, + metrics: Metrics, } struct Sync { @@ -104,6 +106,7 @@ impl Tree { ln_file: Arc, commit_concurrency: usize, leaf_cache_size: usize, + metrics: Metrics, ) -> Result { let ln_freelist_pn = Some(ln_freelist_pn) .map(PageNumber) @@ -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 { @@ -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(), }); @@ -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. @@ -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(); } { @@ -329,6 +343,7 @@ impl Tree { io_handle, sync.tp.clone(), sync.commit_concurrency, + metrics, ) } } diff --git a/nomt/src/beatree/ops/update/mod.rs b/nomt/src/beatree/ops/update/mod.rs index b7ebc1a49f..351390dc1c 100644 --- a/nomt/src/beatree/ops/update/mod.rs +++ b/nomt/src/beatree/ops/update/mod.rs @@ -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; @@ -54,8 +55,9 @@ pub fn update( io_handle: IoHandle, thread_pool: ThreadPool, workers: usize, + metrics: Metrics, ) -> std::io::Result<(SyncData, Index, Receiver>)> { - 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(); diff --git a/nomt/src/beatree/ops/update/tests.rs b/nomt/src/beatree/ops/update/tests.rs index 30ac13582d..61cdf89e6e 100644 --- a/nomt/src/beatree/ops/update/tests.rs +++ b/nomt/src/beatree/ops/update/tests.rs @@ -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}; @@ -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(); @@ -235,11 +237,11 @@ fn exec_leaf_stage( changeset: BTreeMap<[u8; 32], ValueChange>, ) -> (LeafStageOutput, BTreeSet) { 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(); @@ -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); diff --git a/nomt/src/bitbox/mod.rs b/nomt/src/bitbox/mod.rs index d499e3e2d8..6d4c3c3e3f 100644 --- a/nomt/src/bitbox/mod.rs +++ b/nomt/src/bitbox/mod.rs @@ -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}, @@ -113,6 +115,7 @@ pub struct Shared { ht_fd: File, sync_tp: ThreadPool, capacity: usize, + metrics: Metrics, } impl DB { @@ -124,6 +127,7 @@ impl DB { page_pool: PagePool, ht_fd: File, wal_fd: File, + metrics: Metrics, ) -> anyhow::Result { let (store, mut meta_map) = match ht_file::open(num_pages, &page_pool, &ht_fd) { Ok(x) => x, @@ -160,6 +164,7 @@ impl DB { ht_fd, sync_tp: ThreadPool::with_name("bitbox-sync".into(), 2), capacity, + metrics, }), }) } @@ -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) } } @@ -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; @@ -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 { @@ -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; diff --git a/nomt/src/lib.rs b/nomt/src/lib.rs index 1e82e2cf21..5c8124fbbb 100644 --- a/nomt/src/lib.rs +++ b/nomt/src/lib.rs @@ -234,7 +234,7 @@ impl Nomt { 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::(&page_cache, &store); diff --git a/nomt/src/merkle/seek.rs b/nomt/src/merkle/seek.rs index 6b7cbc4f4c..c22107e7b1 100644 --- a/nomt/src/merkle/seek.rs +++ b/nomt/src/merkle/seek.rs @@ -781,7 +781,7 @@ impl Seeker { 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); diff --git a/nomt/src/metrics.rs b/nomt/src/metrics.rs index fa45acdee0..b1f6d99048 100644 --- a/nomt/src/metrics.rs +++ b/nomt/src/metrics.rs @@ -1,11 +1,28 @@ -use std::sync::{ - atomic::{AtomicU64, Ordering}, - Arc, +//! Metrics collection. +//! +//! Counters and timers are striped: every thread adds to its own cache-line-aligned stripe and +//! readers sum the stripes. Threads updating one shared atomic would make its cache line bounce +//! between cores on every update, which costs on the order of a hundred nanoseconds per update +//! under contention, comparable to an in-memory value read. +//! +//! What remains is an uncontended atomic add per counter update, and two clock reads per timed +//! operation (tens of nanoseconds in total). This is negligible next to I/O, but not next to a +//! value read served from memory: with metrics enabled, such reads are a few percent slower. + +use std::{ + sync::{ + atomic::{AtomicU64, AtomicUsize, Ordering}, + Arc, + }, + time::{Duration, Instant}, }; const METRICS_NOT_ENABLED: &str = "Metrics are not enabled"; -/// Metrics collector, if active, it provides Counters and Timers +/// Metrics collector, if active, it provides Counters and Timers. +/// +/// Collection costs an atomic add per counted event, and two clock reads per timed operation. +/// See the module documentation. #[derive(Clone)] pub struct Metrics { metrics: Option>, @@ -14,37 +31,154 @@ pub struct Metrics { /// Metrics that can be collected during execution #[derive(PartialEq, Eq, Hash)] pub enum Metric { - /// Counter of total page requests + /// Counter of merkle page requests served by the page cache. + /// + /// Only requests not already answered by the session overlay reach the page cache. Pages below + /// an elided child are never requested from the page cache: they are reconstructed from + /// beatree leaves, which show up in [`Metric::LeafCacheRequests`] instead. PageRequests, - /// Counter of page requests cache misses over all page requests + /// Counter of page requests cache misses over all page requests. + /// + /// This is not a count of disk reads: a miss on a page whose load is already in flight joins + /// that load, and a miss on a page absent from the hash-table needs no read at all. Disk reads + /// are counted by [`Metric::HtReads`]. PageCacheMisses, - /// Timer used to record average page fetch time + /// Timer used to record average page fetch time: from the first read of a merkle page load + /// from the hash-table, after a page cache miss, until the page is found, including all + /// probes. Loads of pages which turn out not to exist are not recorded, nor are the loads + /// made when opening the database (the root page and page cache prepopulation). PageFetchTime, - /// Timer used to record average value fetch time during reads + /// Timer used to record average value fetch time during reads. + /// + /// Recorded by `Session::read`. The two clock reads around each read add tens of nanoseconds, + /// which is a few percent of a value read served from memory. ValueFetchTime, + /// Counter of beatree leaf cache lookups. Leaves are looked up when reading values, when + /// seeking leaf nodes or reconstructing elided merkle pages, during the beatree update of a + /// commit and when loading prior values for rollback. + LeafCacheRequests, + /// Counter of beatree leaf cache lookups which missed. Every miss leads to a read of the `ln` + /// file, counted by [`Metric::LnReads`]. + LeafCacheMisses, + /// Counter of page reads issued to the hash-table (`ht`) file, which stores merkle pages. + /// A single page load may take several reads when probing the hash-table. This includes the + /// reads made when opening the database, notably page cache prepopulation. + HtReads, + /// Counter of page reads issued to the beatree leaf (`ln`) file, which stores leaves and + /// overflow value pages. + LnReads, } +/// Number of stripes. Threads are assigned to stripes round-robin, so up to this many threads +/// never share a stripe. +const STRIPES: usize = 32; + +/// The slots of a stripe: one per counter, and a count and a sum per timer. +#[derive(Clone, Copy)] +enum Slot { + PageRequests, + PageCacheMisses, + LeafCacheRequests, + LeafCacheMisses, + HtReads, + LnReads, + PageFetchCount, + PageFetchSum, + ValueFetchCount, + ValueFetchSum, +} + +const NUM_SLOTS: usize = Slot::ValueFetchSum as usize + 1; + +/// The slots updated by one group of threads, on cache lines of their own. +#[repr(align(128))] +struct Stripe([AtomicU64; NUM_SLOTS]); + struct ActiveMetrics { - page_requests: AtomicU64, - page_cache_misses: AtomicU64, - page_fetch_time: Timer, - value_fetch_time: Timer, + stripes: Box<[Stripe]>, +} + +impl Metric { + fn counter_slot(&self) -> Slot { + match self { + Metric::PageRequests => Slot::PageRequests, + Metric::PageCacheMisses => Slot::PageCacheMisses, + Metric::LeafCacheRequests => Slot::LeafCacheRequests, + Metric::LeafCacheMisses => Slot::LeafCacheMisses, + Metric::HtReads => Slot::HtReads, + Metric::LnReads => Slot::LnReads, + _ => panic!("Specified metric is not a Counter"), + } + } + + /// The count and sum slots of a timer. + fn timer_slots(&self) -> (Slot, Slot) { + match self { + Metric::PageFetchTime => (Slot::PageFetchCount, Slot::PageFetchSum), + Metric::ValueFetchTime => (Slot::ValueFetchCount, Slot::ValueFetchSum), + _ => panic!("Specified metric is not a Timer"), + } + } +} + +impl ActiveMetrics { + fn new() -> Self { + ActiveMetrics { + stripes: (0..STRIPES) + .map(|_| Stripe(std::array::from_fn(|_| AtomicU64::new(0)))) + .collect(), + } + } + + /// The stripe of the current thread. + fn stripe(&self) -> &Stripe { + static NEXT_STRIPE: AtomicUsize = AtomicUsize::new(0); + thread_local! { + static STRIPE: usize = NEXT_STRIPE.fetch_add(1, Ordering::Relaxed) % STRIPES; + } + &self.stripes[STRIPE.with(|i| *i)] + } + + fn add(&self, slot: Slot) { + self.stripe().0[slot as usize].fetch_add(1, Ordering::Relaxed); + } + + fn add_duration(&self, (count, sum): (Slot, Slot), duration: Duration) { + let stripe = self.stripe(); + stripe.0[count as usize].fetch_add(1, Ordering::Relaxed); + stripe.0[sum as usize].fetch_add(duration.as_nanos() as u64, Ordering::Relaxed); + } + + fn load(&self, slot: Slot) -> u64 { + self.stripes + .iter() + .map(|stripe| stripe.0[slot as usize].load(Ordering::Relaxed)) + .sum() + } + + fn mean(&self, (count, sum): (Slot, Slot)) -> Option { + self.load(sum).checked_div(self.load(count)) + } +} + +/// Records the time passed since its creation when dropped. +struct TimerGuard<'a> { + metrics: &'a ActiveMetrics, + slots: (Slot, Slot), + start: Instant, +} + +impl Drop for TimerGuard<'_> { + fn drop(&mut self) { + self.metrics.add_duration(self.slots, self.start.elapsed()); + } } impl Metrics { /// Returns the Metrics object, active or not based on the specified input pub fn new(active: bool) -> Self { Self { - metrics: if active { - Some(Arc::new(ActiveMetrics { - page_requests: AtomicU64::new(0), - page_cache_misses: AtomicU64::new(0), - page_fetch_time: Timer::new(), - value_fetch_time: Timer::new(), - })) - } else { - None - }, + metrics: active.then(|| Arc::new(ActiveMetrics::new())), } } @@ -53,13 +187,7 @@ impl Metrics { /// panics if the specified [`Metric`] is not a Counter pub fn count(&self, metric: Metric) { if let Some(ref metrics) = self.metrics { - let counter = match metric { - Metric::PageRequests => &metrics.page_requests, - Metric::PageCacheMisses => &metrics.page_cache_misses, - _ => panic!("Specified metric is not a Counter"), - }; - - counter.fetch_add(1, Ordering::Relaxed); + metrics.add(metric.counter_slot()); } } @@ -67,27 +195,38 @@ impl Metrics { /// /// panics if the specified [`Metric`] is not a Timer pub fn record<'a>(&'a self, metric: Metric) -> Option { - self.metrics.as_ref().and_then(|metrics| { - let timer = match metric { - Metric::PageFetchTime => &metrics.page_fetch_time, - Metric::ValueFetchTime => &metrics.value_fetch_time, - _ => panic!("Specified metric is not a Timer"), - }; - - Some(timer.record()) + self.metrics.as_ref().map(|metrics| TimerGuard { + metrics, + slots: metric.timer_slots(), + start: Instant::now(), }) } + /// Record a duration measured by the caller, for operations which do not fit a scope guard, + /// such as asynchronous loads. + /// + /// panics if the specified [`Metric`] is not a Timer + pub fn record_duration(&self, metric: Metric, duration: Duration) { + if let Some(ref metrics) = self.metrics { + metrics.add_duration(metric.timer_slots(), duration); + } + } + + /// Whether metrics are being collected. + pub fn is_active(&self) -> bool { + self.metrics.is_some() + } + /// Print collected metrics to stdout pub fn print(&self) { if let Some(ref metrics) = self.metrics { println!("metrics"); - let tot_page_requests = metrics.page_requests.load(Ordering::Relaxed); + let tot_page_requests = metrics.load(Slot::PageRequests); println!(" page requests {}", tot_page_requests); if tot_page_requests != 0 { - let cache_misses = metrics.page_cache_misses.load(Ordering::Relaxed); + let cache_misses = metrics.load(Slot::PageCacheMisses); let percentage_cache_misses = (cache_misses as f64 / tot_page_requests as f64) * 100.0; @@ -97,11 +236,28 @@ impl Metrics { ); } - if let Some(mean) = metrics.page_fetch_time.mean() { + let leaf_cache_requests = metrics.load(Slot::LeafCacheRequests); + println!(" leaf cache requests {}", leaf_cache_requests); + + if leaf_cache_requests != 0 { + let leaf_cache_misses = metrics.load(Slot::LeafCacheMisses); + let percentage_cache_misses = + (leaf_cache_misses as f64 / leaf_cache_requests as f64) * 100.0; + + println!( + " leaf cache misses {} - {:.2}% of leaf cache requests", + leaf_cache_misses, percentage_cache_misses + ); + } + + println!(" ht page reads {}", metrics.load(Slot::HtReads)); + println!(" ln page reads {}", metrics.load(Slot::LnReads)); + + if let Some(mean) = metrics.mean(Metric::PageFetchTime.timer_slots()) { println!(" page fetch mean {}", pretty_display_ns(mean)); } - if let Some(mean) = metrics.value_fetch_time.mean() { + if let Some(mean) = metrics.mean(Metric::ValueFetchTime.timer_slots()) { println!(" value fetch mean {}", pretty_display_ns(mean)); } } else { @@ -109,42 +265,60 @@ impl Metrics { } } + fn active(&self) -> &ActiveMetrics { + self.metrics.as_deref().expect(METRICS_NOT_ENABLED) + } + /// Counter of total page requests. /// Panics if metrics are not enabled. pub fn get_page_requests(&self) -> u64 { - self.metrics - .as_ref() - .map(|metrics| metrics.page_requests.load(Ordering::Relaxed)) - .expect(METRICS_NOT_ENABLED) + self.active().load(Slot::PageRequests) } /// Counter of page requests cache misses over all page requests. /// Panics if metrics are not enabled. pub fn get_page_cache_misses(&self) -> u64 { - self.metrics - .as_ref() - .map(|metrics| metrics.page_cache_misses.load(Ordering::Relaxed)) - .expect(METRICS_NOT_ENABLED) + self.active().load(Slot::PageCacheMisses) } - /// Average page fetch time. + /// Counter of beatree leaf cache lookups. + /// Panics if metrics are not enabled. + pub fn get_leaf_cache_requests(&self) -> u64 { + self.active().load(Slot::LeafCacheRequests) + } + + /// Counter of beatree leaf cache lookups which missed and had to read the `ln` file. + /// Panics if metrics are not enabled. + pub fn get_leaf_cache_misses(&self) -> u64 { + self.active().load(Slot::LeafCacheMisses) + } + + /// Counter of page reads issued to the hash-table (`ht`) file, which stores merkle pages. + /// Panics if metrics are not enabled. + pub fn get_ht_reads(&self) -> u64 { + self.active().load(Slot::HtReads) + } + + /// Counter of page reads issued to the beatree leaf (`ln`) file, which stores leaves and + /// overflow value pages. + /// Panics if metrics are not enabled. + pub fn get_ln_reads(&self) -> u64 { + self.active().load(Slot::LnReads) + } + + /// Average page fetch time: the time to load a merkle page from the hash-table after a page + /// cache miss, including all probes. See [`Metric::PageFetchTime`]. /// Returns None if there were no requests. /// Panics if metrics are not enabled. pub fn get_page_fetch_time(&self) -> Option { - self.metrics - .as_ref() - .map(|metrics| metrics.page_fetch_time.mean()) - .expect(METRICS_NOT_ENABLED) + self.active().mean(Metric::PageFetchTime.timer_slots()) } /// Average value fetch time during reads. /// Returns None if there were no requests. /// Panics if metrics are not enabled. pub fn get_value_fetch_time(&self) -> Option { - self.metrics - .as_ref() - .map(|metrics| metrics.value_fetch_time.mean()) - .expect(METRICS_NOT_ENABLED) + self.active().mean(Metric::ValueFetchTime.timer_slots()) } } @@ -163,44 +337,31 @@ fn pretty_display_ns(ns: u64) -> String { format!("{val} {unit}") } -struct Timer { - number_of_records: AtomicU64, - sum: AtomicU64, -} - -impl Timer { - fn new() -> Self { - Timer { - number_of_records: AtomicU64::new(0), - sum: AtomicU64::new(0), - } - } - - fn mean(&self) -> Option { - let n = self.number_of_records.load(Ordering::Relaxed); - let sum = self.sum.load(Ordering::Relaxed); - sum.checked_div(n) - } +#[cfg(test)] +mod tests { + use super::{Metric, Metrics, STRIPES}; + use std::time::Duration; - fn record<'a>(&'a self) -> impl Drop + 'a { - struct TimerGuard<'a> { - start: std::time::Instant, - n: &'a AtomicU64, - sum: &'a AtomicU64, - } - - impl Drop for TimerGuard<'_> { - fn drop(&mut self) { - let elapsed = self.start.elapsed().as_nanos() as u64; - self.n.fetch_add(1, Ordering::Relaxed); - self.sum.fetch_add(elapsed, Ordering::Relaxed); + #[test] + fn stripes_sum_across_threads() { + let metrics = Metrics::new(true); + let threads = STRIPES + 3; + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + for _ in 0..1000 { + metrics.count(Metric::LeafCacheRequests); + } + metrics.count(Metric::LnReads); + metrics.record_duration(Metric::PageFetchTime, Duration::from_nanos(10)); + metrics.record_duration(Metric::PageFetchTime, Duration::from_nanos(30)); + }); } - } - - TimerGuard { - start: std::time::Instant::now(), - n: &self.number_of_records, - sum: &self.sum, - } + }); + assert_eq!(metrics.get_leaf_cache_requests(), 1000 * threads as u64); + assert_eq!(metrics.get_ln_reads(), threads as u64); + assert_eq!(metrics.get_leaf_cache_misses(), 0); + assert_eq!(metrics.get_page_fetch_time(), Some(20)); + assert_eq!(metrics.get_value_fetch_time(), None); } } diff --git a/nomt/src/store/mod.rs b/nomt/src/store/mod.rs index a3f986baae..cdfc54c7c7 100644 --- a/nomt/src/store/mod.rs +++ b/nomt/src/store/mod.rs @@ -6,6 +6,7 @@ use crate::{ beatree, bitbox, io::{self, page_pool::FatPage, IoPool, PagePool}, + metrics::Metrics, page_cache::{Page, PageCache}, page_diff::PageDiff, rollback::Rollback, @@ -53,7 +54,7 @@ struct Shared { impl Store { /// Open the store with the provided `Options`. - pub fn open(o: &crate::Options, page_pool: PagePool) -> anyhow::Result { + pub fn open(o: &crate::Options, page_pool: PagePool, metrics: Metrics) -> anyhow::Result { let db_dir_fd; let flock; @@ -159,6 +160,7 @@ impl Store { ln_fd, o.commit_concurrency, o.leaf_cache_size, + metrics.clone(), )?; let pages = bitbox::DB::open( meta.sync_seqn, @@ -167,6 +169,7 @@ impl Store { page_pool.clone(), ht_fd, wal_fd, + metrics, )?; let rollback = o .rollback @@ -453,7 +456,7 @@ fn is_directory_empty(path: &std::path::Path) -> std::io::Result { #[cfg(test)] mod tests { - use super::{PagePool, Store}; + use super::{Metrics, PagePool, Store}; #[test] fn can_crate_in_empty_dir() { @@ -463,7 +466,7 @@ mod tests { options.path(tempdir.path()); let page_pool = PagePool::new(); - let store = Store::open(&options, page_pool.clone()).unwrap(); + let store = Store::open(&options, page_pool.clone(), Metrics::new(false)).unwrap(); assert!(!store.is_poisoned()); } } diff --git a/nomt/src/store/page_loader.rs b/nomt/src/store/page_loader.rs index f24dff4272..b61a51018f 100644 --- a/nomt/src/store/page_loader.rs +++ b/nomt/src/store/page_loader.rs @@ -13,6 +13,12 @@ impl PageLoader { self.inner.start_load(page_id) } + /// Create a new page load whose duration is recorded as a page fetch in the metrics. + /// Use this for loads following a page cache miss. + pub fn start_timed_load(&self, page_id: PageId) -> PageLoad { + self.inner.start_timed_load(page_id) + } + /// Advance the state of the given page load, blocking the current thread. /// /// Panics if the page load needs a completion or if the I/O pool is down. diff --git a/nomt/tests/metrics.rs b/nomt/tests/metrics.rs new file mode 100644 index 0000000000..835f581f0f --- /dev/null +++ b/nomt/tests/metrics.rs @@ -0,0 +1,109 @@ +mod common; + +use common::account_path; +use nomt::{hasher::Blake3Hasher, KeyReadWrite, Nomt, Options, SessionParams, WitnessMode}; +use std::path::{Path, PathBuf}; + +const ACCOUNTS: u64 = 20_000; +const OVERFLOW_ID: u64 = ACCOUNTS; +// Larger than the maximum value stored inline in a leaf, so it spans several overflow pages. +const OVERFLOW_VALUE_LEN: usize = 64 * 1024; + +fn open(path: &Path, prepopulate_page_cache: bool) -> Nomt { + let mut o = Options::new(); + o.path(path); + o.metrics(true); + o.bitbox_seed([0; 16]); + o.hashtable_buckets(64_000); + o.commit_concurrency(1); + o.io_workers(1); + // Small caches so that a cold reopen has to go to disk. + o.page_cache_size(1); + o.leaf_cache_size(1); + o.prepopulate_page_cache(prepopulate_page_cache); + Nomt::open(o).unwrap() +} + +fn commit(nomt: &Nomt, mut actuals: Vec<(nomt::trie::KeyPath, KeyReadWrite)>) { + actuals.sort_by_key(|(k, _)| *k); + let session = + nomt.begin_session(SessionParams::default().witness_mode(WitnessMode::disabled())); + for (key, _) in &actuals { + session.warm_up(*key); + } + session.finish(actuals).unwrap().commit(nomt).unwrap(); +} + +/// Disk reads of the commit path (merkle seek and beatree update) and of value reads must show up +/// in the metrics, not only page cache lookups. +#[test] +fn metrics_count_disk_reads() { + let path = PathBuf::from("test/metrics_count_disk_reads"); + let _ = std::fs::remove_dir_all(&path); + + { + let nomt = open(&path, false); + let mut actuals: Vec<_> = (0..ACCOUNTS) + .map(|id| { + ( + account_path(id), + KeyReadWrite::Write(Some(id.to_le_bytes().to_vec())), + ) + }) + .collect(); + actuals.push(( + account_path(OVERFLOW_ID), + KeyReadWrite::Write(Some(vec![7; OVERFLOW_VALUE_LEN])), + )); + commit(&nomt, actuals); + } + + // Page cache prepopulation reads the hash-table, but is not a page fetch after a cache miss. + { + let nomt = open(&path, true); + let metrics = nomt.metrics(); + assert!(metrics.get_ht_reads() > 1); + assert_eq!(metrics.get_page_fetch_time(), None); + } + + // Reopen with cold caches. + let nomt = open(&path, false); + let metrics = nomt.metrics(); + let ln_reads_at_open = metrics.get_ln_reads(); + + // Update existing keys spread across the tree without reading their values: all disk reads + // here come from the merkle seek (page loads, leaf fetches, elided page reconstruction) and + // from the beatree update. + let actuals: Vec<_> = (0..ACCOUNTS) + .step_by(10) + .map(|id| { + ( + account_path(id), + KeyReadWrite::Write(Some((id + 1).to_le_bytes().to_vec())), + ) + }) + .collect(); + commit(&nomt, actuals); + + assert!(metrics.get_page_requests() > 0); + assert!(metrics.get_page_cache_misses() > 0); + assert!(metrics.get_ht_reads() > 0); + assert!(metrics.get_page_fetch_time().is_some()); + + let leaf_cache_requests = metrics.get_leaf_cache_requests(); + let leaf_cache_misses = metrics.get_leaf_cache_misses(); + assert!(leaf_cache_misses > 0); + assert!(leaf_cache_requests >= leaf_cache_misses); + // Every leaf cache miss reads the leaf from the `ln` file. + assert!(metrics.get_ln_reads() > ln_reads_at_open); + assert!(metrics.get_ln_reads() >= leaf_cache_misses); + + // A blocking value read of an overflow value reads all of its overflow pages. + let ln_reads_before = metrics.get_ln_reads(); + let session = nomt.begin_session(SessionParams::default()); + let value = session.read(account_path(OVERFLOW_ID)).unwrap().unwrap(); + assert_eq!(value.len(), OVERFLOW_VALUE_LEN); + drop(session); + assert!(metrics.get_ln_reads() - ln_reads_before > (OVERFLOW_VALUE_LEN / 4096) as u64); + assert!(metrics.get_value_fetch_time().is_some()); +}