From adafaee584f5193b4be426bfcce606505c57326a Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 23 Nov 2026 15:24:09 +0100 Subject: [PATCH 1/2] merkle: elide the third page level and keep costly elided pages in memory About 90% of the hash-table writes of a commit were third-level pages (bits 18-24), each with ~6 changed nodes: at 30M leaves each holds ~114 leaves, above the elision threshold of 20. Raise PAGE_ELISION_THRESHOLD to 255 so they are elided, and keep elided pages with at least 20 leaves in an in-memory map in the page cache, as of the last commit, so finish does not reconstruct them from leaves: - the page walker reports every elided page it changes, and pages that stop being elided; the merkle output carries them, an overlay keeps them, and the page cache applies them after the store commit succeeds; - seek uses a cached elided page instead of fetching leaves, and caches pages it reconstructs, only when there are no overlays below the session (the cache reflects committed state only). Stored pages carry no leaf counts and are never elided, so this applies to databases grown with the new threshold. Co-Authored-By: Claude Opus 5.5 --- nomt/src/lib.rs | 20 ++++++++--- nomt/src/merkle/mod.rs | 18 ++++++++-- nomt/src/merkle/page_walker.rs | 56 ++++++++++++++++++++++++++++-- nomt/src/merkle/seek.rs | 53 ++++++++++++++++++++++++++-- nomt/src/merkle/worker.rs | 8 +++-- nomt/src/overlay.rs | 21 +++++++++++- nomt/src/page_cache.rs | 63 ++++++++++++++++++++++++++++++++++ 7 files changed, 224 insertions(+), 15 deletions(-) diff --git a/nomt/src/lib.rs b/nomt/src/lib.rs index 1e82e2cf21..02fd79583f 100644 --- a/nomt/src/lib.rs +++ b/nomt/src/lib.rs @@ -768,13 +768,15 @@ impl FinishedSession { .collect(); let values = self.value_transaction.into_iter().collect(); - self.parent_overlay.finish( + let mut overlay = self.parent_overlay.finish( self.prev_root.into_inner(), self.merkle_output.root, updated_pages, values, self.rollback_delta, - ) + ); + overlay.set_elided_pages(self.merkle_output.elided_pages); + overlay } /// Commit this session to disk directly. @@ -800,6 +802,7 @@ impl FinishedSession { shared.last_commit_marker = None; } + let elided_pages = self.merkle_output.elided_pages; nomt.store.commit( self.value_transaction.into_iter(), nomt.page_cache.clone(), @@ -807,7 +810,9 @@ impl FinishedSession { .updated_pages .into_frozen_iter(/* into_overlay */ false), self.rollback_delta, - ) + )?; + nomt.page_cache.update_elided(elided_pages); + Ok(()) } /// Commit this session to disk directly without blocking. @@ -842,6 +847,7 @@ impl FinishedSession { shared.last_commit_marker = None; } + let elided_pages = self.merkle_output.elided_pages; nomt.store.commit( self.value_transaction.into_iter(), nomt.page_cache.clone(), @@ -850,6 +856,7 @@ impl FinishedSession { .into_frozen_iter(/* into_overlay */ false), self.rollback_delta, )?; + nomt.page_cache.update_elided(elided_pages); Ok(None) } @@ -882,6 +889,7 @@ impl Overlay { shared.last_commit_marker = Some(self.mark_committed()); } + let elided_pages = self.elided_pages(); let (page_changes, values, rollback_delta) = self.into_committed_changes(); nomt.store.commit( @@ -889,7 +897,9 @@ impl Overlay { nomt.page_cache.clone(), page_changes, rollback_delta, - ) + )?; + nomt.page_cache.update_elided(elided_pages); + Ok(()) } /// Commit the changes from this overlay to the underlying database without blocking. @@ -924,6 +934,7 @@ impl Overlay { shared.last_commit_marker = Some(self.mark_committed()); } + let elided_pages = self.elided_pages(); let (page_changes, values, rollback_delta) = self.into_committed_changes(); nomt.store.commit( @@ -932,6 +943,7 @@ impl Overlay { page_changes, rollback_delta, )?; + nomt.page_cache.update_elided(elided_pages); Ok(None) } diff --git a/nomt/src/merkle/mod.rs b/nomt/src/merkle/mod.rs index 56a7298d4a..4f099009a8 100644 --- a/nomt/src/merkle/mod.rs +++ b/nomt/src/merkle/mod.rs @@ -26,7 +26,7 @@ use crate::{ beatree::ReadTransaction as BeatreeReadTx, io::PagePool, overlay::LiveOverlay, - page_cache::{Page, PageCache, ShardIndex}, + page_cache::{ElidedPage, Page, PageCache, ShardIndex}, rw_pass_cell::WritePassEnvelope, store::{BucketIndex, DirtyPage, SharedMaybeBucketIndex, Store}, task::{join_task, spawn_thread_task, TaskResult}, @@ -49,8 +49,12 @@ use nomt_core::page_id::MAX_CHILD_INDEX; /// Threshold representing the number of leaves required to be present in the two /// subtrees contained in a page to be stored on disk. /// If this threshold is not reached, the page will not be stored on disk -/// and will be constructed on the fly when needed. -pub const PAGE_ELISION_THRESHOLD: u64 = 20; +/// and will be constructed on the fly when needed. Elided pages costly to reconstruct are kept in +/// the page cache instead (see [`crate::page_cache::PageCache::get_elided`]). +/// +/// At 255, the third level of pages below the root stays elided up to about 60M leaves, which keeps +/// them out of the hash-table writes of every commit. +pub const PAGE_ELISION_THRESHOLD: u64 = 255; /// Bitfield used to note which child pages are elided and thus require on-the-fly reconstruction. #[derive(Debug, PartialEq, Eq)] @@ -442,6 +446,7 @@ impl UpdateHandle { }); let mut updated_pages = Vec::new(); + let mut elided_pages = Vec::new(); let mut path_proof_offset = 0; let mut witnessed_start = 0; @@ -461,6 +466,7 @@ impl UpdateHandle { } updated_pages.push(output.updated_pages); + elided_pages.extend(output.elided_pages); // if the Commit worker collected the witnessed paths // then we need to aggregate them @@ -513,6 +519,7 @@ impl UpdateHandle { Ok(Output { root: new_root.unwrap(), updated_pages: UpdatedPages(updated_pages), + elided_pages, witness: maybe_witness, }) } @@ -524,6 +531,9 @@ pub struct Output { pub root: Node, /// All updated pages from all worker threads. The covered sets of pages are disjoint. pub updated_pages: UpdatedPages, + /// Elided pages changed by the update, and pages that stopped being elided (`None`), to + /// apply to the page cache once the update is committed. + pub elided_pages: Vec<(PageId, Option)>, /// Optional witness pub witness: Option, } @@ -555,6 +565,7 @@ struct WorkerOutput { root: Option, witnessed_paths: Option, usize)>>, updated_pages: Vec, + elided_pages: Vec<(PageId, Option)>, } impl WorkerOutput { @@ -563,6 +574,7 @@ impl WorkerOutput { root: None, witnessed_paths: if witness { Some(Vec::new()) } else { None }, updated_pages: Vec::new(), + elided_pages: Vec::new(), } } } diff --git a/nomt/src/merkle/page_walker.rs b/nomt/src/merkle/page_walker.rs index 18fd6be908..b0337034f4 100644 --- a/nomt/src/merkle/page_walker.rs +++ b/nomt/src/merkle/page_walker.rs @@ -54,7 +54,7 @@ use nomt_core::{ use crate::{ merkle::{page_set::PageOrigin, BucketInfo, ElidedChildren, PAGE_ELISION_THRESHOLD}, - page_cache::{Page, PageMut}, + page_cache::{ElidedPage, Page, PageMut, ELIDED_CACHE_MIN_LEAVES}, page_diff::PageDiff, }; @@ -165,6 +165,8 @@ pub struct PageWalker { child_page_roots: Vec<(TriePosition, Node)>, root: Node, output_pages: Vec, + // Elided pages changed by the walk, and pages that stopped being elided (`None`). + elided_pages: Vec<(PageId, Option)>, // the stack contains pages (ascending) which are descendants of the parent page, if any. stack: Vec, @@ -191,6 +193,7 @@ impl PageWalker { child_page_roots: Vec::new(), root, output_pages: Vec::new(), + elided_pages: Vec::new(), stack: Vec::new(), sibling_stack: Vec::new(), prev_node: None, @@ -460,8 +463,20 @@ impl PageWalker { /// Conclude walking and updating and return an output - either a new root, or a list /// of node changes to apply to the parent page. - pub fn conclude(mut self) -> Output { + #[cfg_attr(not(test), allow(dead_code))] + pub fn conclude(self) -> Output { + self.conclude_with_elided_pages().0 + } + + /// Like [`Self::conclude`], also returning the elided pages changed by the walk and the pages + /// that stopped being elided (`None`). + pub fn conclude_with_elided_pages(mut self) -> (Output, Vec<(PageId, Option)>) { self.compact_up(None); + let elided_pages = std::mem::take(&mut self.elided_pages); + (self.into_output(), elided_pages) + } + + fn into_output(self) -> Output { let updated_pages = self.output_pages; if self.parent_page.is_none() { @@ -769,11 +784,37 @@ impl PageWalker { .elided_children .set_elide(child_index.clone(), true); + let elided = |page: Page| ElidedPage { + diff: reachable_nodes::(&page), + page, + leaves: page_leaves_counter, + children_leaves: children_leaves_counter, + }; + + // Report only pages the page cache keeps, and removals of pages it may hold, so a + // large commit does not copy every small elided page it touches. + let cached = page_leaves_counter + children_leaves_counter + >= ELIDED_CACHE_MIN_LEAVES; + let was_cached = stack_page.page_leaves_counter.unwrap_or(0) + + stack_page.prev_children_leaves_counter.unwrap_or(0) + >= ELIDED_CACHE_MIN_LEAVES; + // If the page was previously resident in memory we need to clear it. // While reconstructed pages do not need this. if stack_page.bucket_info.is_some() { + if cached { + let page = stack_page.page.snapshot(); + self.elided_pages + .push((stack_page.page_id.clone(), Some(elided(page)))); + } stack_page.diff.set_cleared(); push_updated(&mut self.output_pages, stack_page); + } else if cached { + let page_id = stack_page.page_id; + self.elided_pages + .push((page_id, Some(elided(stack_page.page.freeze())))); + } else if was_cached { + self.elided_pages.push((stack_page.page_id, None)); } return; } @@ -794,6 +835,10 @@ impl PageWalker { .elided_children .set_elide(child_index.clone(), false); + if stack_page.bucket_info.is_none() { + // A page that was elided is stored from now on. + self.elided_pages.push((stack_page.page_id.clone(), None)); + } push_updated(&mut self.output_pages, stack_page); } } @@ -824,6 +869,13 @@ fn for_each_reachable( } } +/// A diff marking every node reachable in the page. +fn reachable_nodes(page: &Page) -> PageDiff { + let mut diff = PageDiff::default(); + for_each_reachable::(|index| page.node(index), |index, _| diff.set_changed(index)); + diff +} + /// Count the number of leaves present *only* in the provided page, /// without jumping into child pages. fn count_leaves(page: &PageMut) -> u64 { diff --git a/nomt/src/merkle/seek.rs b/nomt/src/merkle/seek.rs index 6b7cbc4f4c..0527b44ab6 100644 --- a/nomt/src/merkle/seek.rs +++ b/nomt/src/merkle/seek.rs @@ -7,7 +7,7 @@ use crate::{ ValueChange, }, io::{CompleteIo, FatPage, IoHandle}, - page_cache::{Page, PageCache, PageMut}, + page_cache::{ElidedPage, Page, PageCache, PageMut}, store::{BucketIndex, PageLoad, PageLoader}, HashAlgorithm, }; @@ -131,6 +131,7 @@ impl SeekRequest { page: &Page, record_siblings: bool, page_set: &mut PageSet, + page_cache: &PageCache, ) { let RequestState::Seeking = self.state else { panic!("seek past end") @@ -192,6 +193,31 @@ impl SeekRequest { return; } + // Without overlays, the committed state is current, so a cached elided page can be + // used as is. Seeking resumes into it like into a loaded page. + if !overlay.has_ancestors() { + if let Some(elided) = page_cache.get_elided(&child_page_id) { + debug_assert_eq!( + H::hash_internal(&trie::InternalData { + left: elided.page.node(0), + right: elided.page.node(1), + }), + page.node(self.position.node_index()), + "cached elided page {child_page_id:?} is stale", + ); + page_set.insert( + child_page_id, + elided.page, + PageOrigin::Reconstructed { + page_leaves_counter: elided.leaves, + children_leaves_counter: elided.children_leaves, + diff: elided.diff, + }, + ); + return; + } + } + // Begin fetching the beatree leaves required for reconstructing the elided pages. // // NOTE: It could happen that two or more sequential requests end up in the same elided @@ -205,7 +231,7 @@ impl SeekRequest { &self.position, page.clone(), ); - self.continue_leaves_fetch::(page_set, overlay, None); + self.continue_leaves_fetch::(page_set, overlay, page_cache, None); } } @@ -285,6 +311,7 @@ impl SeekRequest { &mut self, page_set: &mut PageSet, overlay: &LiveOverlay, + page_cache: &PageCache, leaf: Option, ) { let RequestState::FetchingLeaves { @@ -393,6 +420,18 @@ impl SeekRequest { if let Some(pages) = maybe_pages { for (page_id, page, diff, page_leaves_counter, children_leaves_counter) in pages { + // Reconstructed from the committed leaves only: keep it for later sessions. + if !overlay.has_ancestors() { + page_cache.insert_elided( + page_id.clone(), + ElidedPage { + page: page.clone(), + diff: diff.clone(), + leaves: page_leaves_counter, + children_leaves: children_leaves_counter, + }, + ); + } page_set.insert( page_id, page, @@ -765,6 +804,7 @@ impl Seeker { &page, self.record_siblings, page_set, + &self.page_cache, ); continue; } @@ -812,6 +852,7 @@ impl Seeker { .continue_leaves_fetch::( page_set, &self.overlay, + &self.page_cache, Some(leaf), ), // PANIC: The state cannot be `RequestState::Seeking`, we would have entered @@ -906,6 +947,7 @@ impl Seeker { &page, self.record_siblings, page_set, + &self.page_cache, ); if !request.is_completed() { @@ -944,7 +986,12 @@ impl Seeker { request.continue_leaf_fetch::(Some(leaf.clone())); } RequestState::FetchingLeaves { .. } => { - request.continue_leaves_fetch::(page_set, &self.overlay, Some(leaf.clone())); + request.continue_leaves_fetch::( + page_set, + &self.overlay, + &self.page_cache, + Some(leaf.clone()), + ); } // PANIC: This is strictly called only when `IoRequest::Leaf` is received, thus // no `RequestState::Seeking` is expected. diff --git a/nomt/src/merkle/worker.rs b/nomt/src/merkle/worker.rs index c1811f3f66..f96bac3593 100644 --- a/nomt/src/merkle/worker.rs +++ b/nomt/src/merkle/worker.rs @@ -259,8 +259,10 @@ fn update( } } + let (root_output, elided_pages) = root_page_updater.conclude_with_elided_pages(); + output.elided_pages.extend(elided_pages); // PANIC: output is always root when no parent page is specified. - match root_page_updater.conclude() { + match root_output { Output::Root(new_root, updates) => { output.updated_pages.extend(updates); output.root = Some(new_root); @@ -530,8 +532,10 @@ impl RangeUpdater { } // 2. conclude. + let (walker_output, elided_pages) = self.page_walker.conclude_with_elided_pages(); + output.elided_pages = elided_pages; // PANIC: walker was configured with a parent page. - let (new_nodes, updates) = match self.page_walker.conclude() { + let (new_nodes, updates) = match walker_output { Output::ChildPageRoots(new_nodes, output_pages) => (new_nodes, output_pages), Output::Root(_, _) => unreachable!(), }; diff --git a/nomt/src/overlay.rs b/nomt/src/overlay.rs index 8cd9c453b9..7b44ab6462 100644 --- a/nomt/src/overlay.rs +++ b/nomt/src/overlay.rs @@ -17,7 +17,7 @@ //! Creating a new overlay is an O(n) operation in the amount of changes relative to the parent, //! both in terms of new changes and outdated ancestors. -use crate::{beatree::ValueChange, store::DirtyPage, Root}; +use crate::{beatree::ValueChange, page_cache::ElidedPage, store::DirtyPage, Root}; use nomt_core::{ page_id::PageId, trie::{KeyPath, Node}, @@ -59,6 +59,17 @@ impl Overlay { /// /// Must be called after marking the overlay committed so dropping the extracted `Data` /// does not mark the overlay as dropped. + /// Record the elided pages changed by this overlay. Only for a newly finished overlay. + pub(super) fn set_elided_pages(&mut self, elided_pages: Vec<(PageId, Option)>) { + // UNWRAP: a newly finished overlay is not shared yet. + Arc::get_mut(&mut self.inner).unwrap().elided_pages = elided_pages; + } + + /// The elided pages changed by this overlay. + pub(super) fn elided_pages(&self) -> Vec<(PageId, Option)> { + self.inner.elided_pages.clone() + } + pub(super) fn into_committed_changes( self, ) -> ( @@ -97,6 +108,8 @@ struct OverlayInner { // ordered by recency. ancestor_data: Vec>, rollback_delta: Option, + // Elided pages changed by this overlay, for the page cache once it is committed. + elided_pages: Vec<(PageId, Option)>, } /// A marker indicating the overlay uniquely, until dropped. Used to enforce commit order. @@ -252,6 +265,11 @@ pub(super) struct LiveOverlay { } impl LiveOverlay { + /// Whether any uncommitted overlay lies below this one. + pub(super) fn has_ancestors(&self) -> bool { + self.parent.is_some() + } + /// Create a new live overlay based on this iterator of ancestors. pub(super) fn new<'a>( live_ancestors: impl IntoIterator, @@ -420,6 +438,7 @@ impl LiveOverlay { seqn: new_seqn, ancestor_data, rollback_delta, + elided_pages: Vec::new(), }), } } diff --git a/nomt/src/page_cache.rs b/nomt/src/page_cache.rs index d061be4436..5a0fea53a7 100644 --- a/nomt/src/page_cache.rs +++ b/nomt/src/page_cache.rs @@ -3,6 +3,7 @@ use crate::{ io::{page_pool::FatPage, PagePool, PAGE_SIZE}, merkle::ElidedChildren, metrics::{Metric, Metrics}, + page_diff::PageDiff, page_region::PageRegion, rw_pass_cell::{Region, RegionContains, RwPassDomain, WritePass}, Options, @@ -59,6 +60,13 @@ impl PageMut { } } + /// A frozen copy of the page. + pub fn snapshot(&self) -> Page { + Page { + inner: Arc::new(self.inner.clone()), + } + } + /// Create a pristine (i.e. logically blank) `PageMut`. /// /// Note that this is not actually guaranteed to be blank, because pages in the pool are not @@ -229,8 +237,29 @@ impl CacheShardLocked { } } +/// An elided page, which is not stored in the hash-table, kept in memory as of the last commit +/// because it is costly to reconstruct from its leaves. +#[derive(Clone)] +pub struct ElidedPage { + pub page: Page, + /// All nodes written in the page. + pub diff: PageDiff, + /// The number of leaves in the page. + pub leaves: u64, + /// The number of leaves in its child pages. + pub children_leaves: u64, +} + +/// Elided pages with at least this many leaves in and below them are kept in memory. Smaller ones +/// are cheap to reconstruct. +pub const ELIDED_CACHE_MIN_LEAVES: u64 = 20; + +type ElidedShard = RwLock>; + struct Shared { shards: Vec, + /// Elided pages, sharded by the child of the root page they descend from. + elided: Vec, root_page: RwLock>, page_rw_pass_domain: RwPassDomain, fixed_levels: usize, @@ -332,6 +361,9 @@ impl PageCache { // One shard per child of the root page. Each shard is a separate merkle update // task on the `commit_concurrency` workers, so they balance the load dynamically. shards: make_shards(NUM_CHILDREN, o.page_cache_size), + elided: (0..NUM_CHILDREN) + .map(|_| RwLock::new(HashMap::with_hasher(FxBuildHasher::default()))) + .collect(), root_page: RwLock::new(root_page_entry), page_rw_pass_domain: domain, metrics: metrics.into().unwrap_or(Metrics::new(false)), @@ -353,6 +385,37 @@ impl PageCache { } } + fn elided_shard(&self, page_id: &PageId) -> &ElidedShard { + // The root page and its children are never elided. + &self.shared.elided[page_id.child_index_at_level(0).to_u8() as usize] + } + + /// Get an elided page as of the last commit. + pub fn get_elided(&self, page_id: &PageId) -> Option { + self.elided_shard(page_id).read().get(page_id).cloned() + } + + /// Keep a page reconstructed from the committed leaves, if it is costly to reconstruct. + pub fn insert_elided(&self, page_id: PageId, elided: ElidedPage) { + if elided.leaves + elided.children_leaves >= ELIDED_CACHE_MIN_LEAVES { + self.elided_shard(&page_id).write().insert(page_id, elided); + } + } + + /// Apply the elided pages changed by a commit: `None` means the page is no longer elided. + pub fn update_elided(&self, updates: Vec<(PageId, Option)>) { + for (page_id, elided) in updates { + match elided { + Some(elided) if elided.leaves + elided.children_leaves >= ELIDED_CACHE_MIN_LEAVES => { + self.elided_shard(&page_id).write().insert(page_id, elided); + } + _ => { + self.elided_shard(&page_id).write().remove(&page_id); + } + } + } + } + /// Query the cache for the page data at the given [`PageId`]. /// /// Returns `None` if not in the cache. From 8c303b01f3d86e7d23a84f8a6e8196e74851034f Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 23 Nov 2026 16:10:39 +0100 Subject: [PATCH 2/2] tests: elided pages kept in memory stay in step with committed state Forty commits over clustered keys in one process keep pages two levels below the root elided with 20-255 leaves, so they are served from the page cache's elided-page map between commits. The root is checked against a fresh database holding the same state. Fails if the walker's last elided pages are not reported (the cached page goes stale). Co-Authored-By: Claude Opus 5.5 --- nomt/tests/elided_cache.rs | 71 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 nomt/tests/elided_cache.rs diff --git a/nomt/tests/elided_cache.rs b/nomt/tests/elided_cache.rs new file mode 100644 index 0000000000..0aa7a9a2b5 --- /dev/null +++ b/nomt/tests/elided_cache.rs @@ -0,0 +1,71 @@ +mod common; + +use common::Test; +use nomt_core::trie::KeyPath; +use std::collections::BTreeMap; + +/// Keys sharing their first 16 bits, so a few hundred of them give pages two levels below the root +/// with 20 to 255 leaves: elided, but kept in the page cache's elided-page map. +fn clustered_key(rng: &mut u64) -> KeyPath { + let mut key = [0u8; 32]; + key[0] = 0x5a; + key[1] = 0xc3; + for byte in key[2..].iter_mut() { + *rng ^= *rng << 13; + *rng ^= *rng >> 7; + *rng ^= *rng << 17; + *byte = *rng as u8; + } + key +} + +/// The root of a fresh database holding `state`, written in one commit. +fn reference_root(name: &str, state: &BTreeMap>) -> nomt::Root { + let mut t = Test::new_with_params(name, 2, 64_000, None, true); + for (key, value) in state { + t.write(*key, Some(value.clone())); + } + t.commit(); + t.root() +} + +/// Many commits in one process update elided pages that are cached in memory between commits. +/// Each must match the committed state, or seeking through them yields a wrong root. +#[test] +fn elided_page_cache_matches_committed_state() { + let mut rng = 0x9e37_79b9_7f4a_7c15u64; + let mut keys = Vec::new(); + let mut state = BTreeMap::new(); + let mut t = Test::new_with_params("elided_cache", 2, 64_000, None, true); + + for round in 0..40u32 { + let mut written = BTreeMap::new(); + for _ in 0..15 { + keys.push(clustered_key(&mut rng)); + } + for i in 0..60 { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + let key = if i < 15 { + keys[keys.len() - 15 + i] + } else { + keys[(rng % keys.len() as u64) as usize] + }; + written.insert(key, round.to_le_bytes().repeat(1 + i % 5)); + } + for (key, value) in &written { + t.write(*key, Some(value.clone())); + } + state.extend(written); + t.commit(); + + if round % 10 == 9 { + assert_eq!( + t.root(), + reference_root("elided_cache_reference", &state), + "root after round {round}" + ); + } + } +}