From 34ce83fea70185f56a5561c80807668e582fb3ef Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Thu, 26 Nov 2026 10:36:39 +0100 Subject: [PATCH 1/3] metrics: count leaf cache use and disk reads per file The metrics only covered the merkle page cache. Merkle pages below an elided child never reach the page cache: they are rebuilt from beatree leaves. Leaf reads made by the seek, by the beatree update of a commit, by rollback and by value reads were not counted anywhere. A node could report zero page cache misses while issuing thousands of reads of the ln file per second. PageFetchTime was defined but never recorded. Add four counters: - LeafCacheRequests and LeafCacheMisses, counted in LeafCache::get, which every leaf lookup goes through. - HtReads, counted when PageLoader::probe submits a read of the hash-table. - LnReads, counted in StoreReader, which only wraps the leaf store and is used for both leaves and overflow pages. Record PageFetchTime in PageLoad, from the first hash-table read until the page is found. PageCacheMisses is not a count of reads: a lookup that misses on a page whose load is in flight joins that load. On a cold reopen in the new test, 2000 misses led to 65 ht reads. Say so in its docs. Co-Authored-By: Claude Opus 5.5 --- nomt/src/beatree/allocator/mod.rs | 18 +++- nomt/src/beatree/leaf_cache.rs | 18 +++- nomt/src/beatree/mod.rs | 21 +++- nomt/src/beatree/ops/update/mod.rs | 4 +- nomt/src/beatree/ops/update/tests.rs | 10 +- nomt/src/bitbox/mod.rs | 16 +++ nomt/src/lib.rs | 2 +- nomt/src/metrics.rs | 149 ++++++++++++++++++++++++--- nomt/src/store/mod.rs | 9 +- nomt/tests/metrics.rs | 100 ++++++++++++++++++ 10 files changed, 314 insertions(+), 33 deletions(-) create mode 100644 nomt/tests/metrics.rs 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..51ed69558b 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,7 @@ impl PageLoader { probe_sequence: ProbeSequence::new(&page_id, &self.meta_map, &self.shared.seed), page_id, state: PageLoadState::Pending, + fetch_timer: None, } } @@ -584,6 +590,10 @@ impl PageLoader { user_data, }; + self.shared.metrics.count(Metric::HtReads); + if load.fetch_timer.is_none() && self.shared.metrics.is_active() { + 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 +605,9 @@ pub struct PageLoad { page_id: PageId, probe_sequence: ProbeSequence, state: PageLoadState, + /// Set when the first read is submitted, if metrics are active. Used to record + /// [`Metric::PageFetchTime`] once the page is found. + fetch_timer: Option<(Instant, Metrics)>, } impl PageLoad { @@ -613,6 +626,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/metrics.rs b/nomt/src/metrics.rs index fa45acdee0..640ae81a56 100644 --- a/nomt/src/metrics.rs +++ b/nomt/src/metrics.rs @@ -1,6 +1,9 @@ -use std::sync::{ - atomic::{AtomicU64, Ordering}, - Arc, +use std::{ + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, + }, + time::Duration, }; const METRICS_NOT_ENABLED: &str = "Metrics are not enabled"; @@ -14,14 +17,37 @@ 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 until the page is found, including all probes. Loads of pages which + /// turn out not to exist are not recorded. PageFetchTime, /// Timer used to record average value fetch time during reads 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. + HtReads, + /// Counter of page reads issued to the beatree leaf (`ln`) file, which stores leaves and + /// overflow value pages. + LnReads, } struct ActiveMetrics { @@ -29,6 +55,10 @@ struct ActiveMetrics { page_cache_misses: AtomicU64, page_fetch_time: Timer, value_fetch_time: Timer, + leaf_cache_requests: AtomicU64, + leaf_cache_misses: AtomicU64, + ht_reads: AtomicU64, + ln_reads: AtomicU64, } impl Metrics { @@ -41,6 +71,10 @@ impl Metrics { page_cache_misses: AtomicU64::new(0), page_fetch_time: Timer::new(), value_fetch_time: Timer::new(), + leaf_cache_requests: AtomicU64::new(0), + leaf_cache_misses: AtomicU64::new(0), + ht_reads: AtomicU64::new(0), + ln_reads: AtomicU64::new(0), })) } else { None @@ -56,6 +90,10 @@ impl Metrics { let counter = match metric { Metric::PageRequests => &metrics.page_requests, Metric::PageCacheMisses => &metrics.page_cache_misses, + Metric::LeafCacheRequests => &metrics.leaf_cache_requests, + Metric::LeafCacheMisses => &metrics.leaf_cache_misses, + Metric::HtReads => &metrics.ht_reads, + Metric::LnReads => &metrics.ln_reads, _ => panic!("Specified metric is not a Counter"), }; @@ -67,15 +105,24 @@ 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"), - }; + self.metrics + .as_ref() + .map(|metrics| metrics.timer(metric).record()) + } + + /// 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.timer(metric).add(duration); + } + } - Some(timer.record()) - }) + /// Whether metrics are being collected. + pub fn is_active(&self) -> bool { + self.metrics.is_some() } /// Print collected metrics to stdout @@ -97,6 +144,29 @@ impl Metrics { ); } + let leaf_cache_requests = metrics.leaf_cache_requests.load(Ordering::Relaxed); + println!(" leaf cache requests {}", leaf_cache_requests); + + if leaf_cache_requests != 0 { + let leaf_cache_misses = metrics.leaf_cache_misses.load(Ordering::Relaxed); + 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.ht_reads.load(Ordering::Relaxed) + ); + println!( + " ln page reads {}", + metrics.ln_reads.load(Ordering::Relaxed) + ); + if let Some(mean) = metrics.page_fetch_time.mean() { println!(" page fetch mean {}", pretty_display_ns(mean)); } @@ -127,7 +197,40 @@ impl Metrics { .expect(METRICS_NOT_ENABLED) } - /// 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.load_counter(|m| &m.leaf_cache_requests) + } + + /// 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.load_counter(|m| &m.leaf_cache_misses) + } + + /// 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.load_counter(|m| &m.ht_reads) + } + + /// 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.load_counter(|m| &m.ln_reads) + } + + fn load_counter(&self, counter: impl FnOnce(&ActiveMetrics) -> &AtomicU64) -> u64 { + self.metrics + .as_ref() + .map(|metrics| counter(metrics).load(Ordering::Relaxed)) + .expect(METRICS_NOT_ENABLED) + } + + /// Average page fetch time: the time to load a merkle page from the hash-table, 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 { @@ -148,6 +251,16 @@ impl Metrics { } } +impl ActiveMetrics { + fn timer(&self, metric: Metric) -> &Timer { + match metric { + Metric::PageFetchTime => &self.page_fetch_time, + Metric::ValueFetchTime => &self.value_fetch_time, + _ => panic!("Specified metric is not a Timer"), + } + } +} + fn pretty_display_ns(ns: u64) -> String { // preserve 3 sig figs at minimum. let (val, unit) = if ns > 100 * 1_000_000_000 { @@ -182,6 +295,12 @@ impl Timer { sum.checked_div(n) } + fn add(&self, duration: Duration) { + self.number_of_records.fetch_add(1, Ordering::Relaxed); + self.sum + .fetch_add(duration.as_nanos() as u64, Ordering::Relaxed); + } + fn record<'a>(&'a self) -> impl Drop + 'a { struct TimerGuard<'a> { start: std::time::Instant, 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/tests/metrics.rs b/nomt/tests/metrics.rs new file mode 100644 index 0000000000..b8e158fb64 --- /dev/null +++ b/nomt/tests/metrics.rs @@ -0,0 +1,100 @@ +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) -> 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); + 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); + 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); + } + + // Reopen with cold caches. + let nomt = open(&path); + 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()); +} From 3eb32c41eb6580d15e84e7237c5ea7671e380b5e Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Thu, 26 Nov 2026 10:40:56 +0100 Subject: [PATCH 2/3] metrics: do not time page loads made when opening the database Page cache prepopulation queues a load for every page in the upper levels at once. Timing those loads as page fetches recorded queueing behind the whole batch: benchtop's default open of a 4M account DB read 53k pages and reported a 90 ms mean page fetch time. Since the timer is a mean over the lifetime of the database, that skews it long after startup. Only time loads started by the merkle seek after a page cache miss. The reads at open still count towards HtReads. Co-Authored-By: Claude Opus 5.5 --- nomt/src/bitbox/mod.rs | 18 ++++++++++++++++-- nomt/src/merkle/seek.rs | 2 +- nomt/src/metrics.rs | 12 +++++++----- nomt/src/store/page_loader.rs | 6 ++++++ nomt/tests/metrics.rs | 15 ++++++++++++--- 5 files changed, 42 insertions(+), 11 deletions(-) diff --git a/nomt/src/bitbox/mod.rs b/nomt/src/bitbox/mod.rs index 51ed69558b..6d4c3c3e3f 100644 --- a/nomt/src/bitbox/mod.rs +++ b/nomt/src/bitbox/mod.rs @@ -556,10 +556,22 @@ 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) + } + } + /// 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. @@ -591,7 +603,7 @@ impl PageLoader { }; self.shared.metrics.count(Metric::HtReads); - if load.fetch_timer.is_none() && self.shared.metrics.is_active() { + 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. @@ -605,7 +617,9 @@ pub struct PageLoad { page_id: PageId, probe_sequence: ProbeSequence, state: PageLoadState, - /// Set when the first read is submitted, if metrics are active. Used to record + /// 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)>, } 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 640ae81a56..55adb03933 100644 --- a/nomt/src/metrics.rs +++ b/nomt/src/metrics.rs @@ -30,8 +30,9 @@ pub enum Metric { /// are counted by [`Metric::HtReads`]. PageCacheMisses, /// Timer used to record average page fetch time: from the first read of a merkle page load - /// from the hash-table until the page is found, including all probes. Loads of pages which - /// turn out not to exist are not recorded. + /// 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 ValueFetchTime, @@ -43,7 +44,8 @@ pub enum Metric { /// 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. + /// 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. @@ -229,8 +231,8 @@ impl Metrics { .expect(METRICS_NOT_ENABLED) } - /// Average page fetch time: the time to load a merkle page from the hash-table, including all - /// probes. See [`Metric::PageFetchTime`]. + /// 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 { 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 index b8e158fb64..835f581f0f 100644 --- a/nomt/tests/metrics.rs +++ b/nomt/tests/metrics.rs @@ -9,7 +9,7 @@ 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) -> Nomt { +fn open(path: &Path, prepopulate_page_cache: bool) -> Nomt { let mut o = Options::new(); o.path(path); o.metrics(true); @@ -20,6 +20,7 @@ fn open(path: &Path) -> Nomt { // 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() } @@ -41,7 +42,7 @@ fn metrics_count_disk_reads() { let _ = std::fs::remove_dir_all(&path); { - let nomt = open(&path); + let nomt = open(&path, false); let mut actuals: Vec<_> = (0..ACCOUNTS) .map(|id| { ( @@ -57,8 +58,16 @@ fn metrics_count_disk_reads() { 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); + let nomt = open(&path, false); let metrics = nomt.metrics(); let ln_reads_at_open = metrics.get_ln_reads(); From 1d96d2608f73321f1b4bd9dd9c7f3b00462134b3 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Thu, 26 Nov 2026 11:17:21 +0100 Subject: [PATCH 3/3] metrics: stripe counters and timers per thread All counters lived in one small struct, so every counter update from any thread made the same cache lines bounce between cores. In a microbenchmark of six threads that each count a leaf lookup and time a read in a loop, an operation took 254 ns with shared atomics and 59 ns with per-thread stripes; 40-50 ns of that is the two clock reads of the timer. Give every thread a cache-line-aligned stripe of all the counters, and sum the stripes when reading. In benchtop, in-memory value reads are 2-7% slower with metrics enabled than without, on master as well, depending on the run. Striping does not change that measurably: at ~2 us per read the clock reads dominate. Document that cost. Co-Authored-By: Claude Opus 5.5 --- nomt/src/metrics.rs | 312 +++++++++++++++++++++++++------------------- 1 file changed, 176 insertions(+), 136 deletions(-) diff --git a/nomt/src/metrics.rs b/nomt/src/metrics.rs index 55adb03933..b1f6d99048 100644 --- a/nomt/src/metrics.rs +++ b/nomt/src/metrics.rs @@ -1,14 +1,28 @@ +//! 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, Ordering}, + atomic::{AtomicU64, AtomicUsize, Ordering}, Arc, }, - time::Duration, + 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>, @@ -34,7 +48,10 @@ pub enum Metric { /// 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 @@ -52,35 +69,116 @@ pub enum Metric { 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, - leaf_cache_requests: AtomicU64, - leaf_cache_misses: AtomicU64, - ht_reads: AtomicU64, - ln_reads: AtomicU64, + 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(), - leaf_cache_requests: AtomicU64::new(0), - leaf_cache_misses: AtomicU64::new(0), - ht_reads: AtomicU64::new(0), - ln_reads: AtomicU64::new(0), - })) - } else { - None - }, + metrics: active.then(|| Arc::new(ActiveMetrics::new())), } } @@ -89,17 +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, - Metric::LeafCacheRequests => &metrics.leaf_cache_requests, - Metric::LeafCacheMisses => &metrics.leaf_cache_misses, - Metric::HtReads => &metrics.ht_reads, - Metric::LnReads => &metrics.ln_reads, - _ => panic!("Specified metric is not a Counter"), - }; - - counter.fetch_add(1, Ordering::Relaxed); + metrics.add(metric.counter_slot()); } } @@ -107,9 +195,11 @@ impl Metrics { /// /// panics if the specified [`Metric`] is not a Timer pub fn record<'a>(&'a self, metric: Metric) -> Option { - self.metrics - .as_ref() - .map(|metrics| metrics.timer(metric).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, @@ -118,7 +208,7 @@ impl Metrics { /// 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.timer(metric).add(duration); + metrics.add_duration(metric.timer_slots(), duration); } } @@ -132,11 +222,11 @@ impl Metrics { 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; @@ -146,11 +236,11 @@ impl Metrics { ); } - let leaf_cache_requests = metrics.leaf_cache_requests.load(Ordering::Relaxed); + 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.leaf_cache_misses.load(Ordering::Relaxed); + let leaf_cache_misses = metrics.load(Slot::LeafCacheMisses); let percentage_cache_misses = (leaf_cache_misses as f64 / leaf_cache_requests as f64) * 100.0; @@ -160,20 +250,14 @@ impl Metrics { ); } - println!( - " ht page reads {}", - metrics.ht_reads.load(Ordering::Relaxed) - ); - println!( - " ln page reads {}", - metrics.ln_reads.load(Ordering::Relaxed) - ); + println!(" ht page reads {}", metrics.load(Slot::HtReads)); + println!(" ln page reads {}", metrics.load(Slot::LnReads)); - if let Some(mean) = metrics.page_fetch_time.mean() { + 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 { @@ -181,54 +265,45 @@ 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) } /// Counter of beatree leaf cache lookups. /// Panics if metrics are not enabled. pub fn get_leaf_cache_requests(&self) -> u64 { - self.load_counter(|m| &m.leaf_cache_requests) + 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.load_counter(|m| &m.leaf_cache_misses) + 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.load_counter(|m| &m.ht_reads) + 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.load_counter(|m| &m.ln_reads) - } - - fn load_counter(&self, counter: impl FnOnce(&ActiveMetrics) -> &AtomicU64) -> u64 { - self.metrics - .as_ref() - .map(|metrics| counter(metrics).load(Ordering::Relaxed)) - .expect(METRICS_NOT_ENABLED) + self.active().load(Slot::LnReads) } /// Average page fetch time: the time to load a merkle page from the hash-table after a page @@ -236,30 +311,14 @@ impl Metrics { /// 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) - } -} - -impl ActiveMetrics { - fn timer(&self, metric: Metric) -> &Timer { - match metric { - Metric::PageFetchTime => &self.page_fetch_time, - Metric::ValueFetchTime => &self.value_fetch_time, - _ => panic!("Specified metric is not a Timer"), - } + self.active().mean(Metric::ValueFetchTime.timer_slots()) } } @@ -278,50 +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) - } - - fn add(&self, duration: Duration) { - self.number_of_records.fetch_add(1, Ordering::Relaxed); - self.sum - .fetch_add(duration.as_nanos() as u64, Ordering::Relaxed); - } - - 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); +#[cfg(test)] +mod tests { + use super::{Metric, Metrics, STRIPES}; + use std::time::Duration; + + #[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); } }