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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions nomt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -800,14 +802,17 @@ 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(),
self.merkle_output
.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.
Expand Down Expand Up @@ -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(),
Expand All @@ -850,6 +856,7 @@ impl FinishedSession {
.into_frozen_iter(/* into_overlay */ false),
self.rollback_delta,
)?;
nomt.page_cache.update_elided(elided_pages);

Ok(None)
}
Expand Down Expand Up @@ -882,14 +889,17 @@ 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(
values,
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.
Expand Down Expand Up @@ -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(
Expand All @@ -932,6 +943,7 @@ impl Overlay {
page_changes,
rollback_delta,
)?;
nomt.page_cache.update_elided(elided_pages);

Ok(None)
}
Expand Down
18 changes: 15 additions & 3 deletions nomt/src/merkle/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand All @@ -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)]
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -513,6 +519,7 @@ impl UpdateHandle {
Ok(Output {
root: new_root.unwrap(),
updated_pages: UpdatedPages(updated_pages),
elided_pages,
witness: maybe_witness,
})
}
Expand All @@ -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<ElidedPage>)>,
/// Optional witness
pub witness: Option<Witness>,
}
Expand Down Expand Up @@ -555,6 +565,7 @@ struct WorkerOutput {
root: Option<Node>,
witnessed_paths: Option<Vec<(WitnessedPath, Option<trie::LeafData>, usize)>>,
updated_pages: Vec<UpdatedPage>,
elided_pages: Vec<(PageId, Option<ElidedPage>)>,
}

impl WorkerOutput {
Expand All @@ -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(),
}
}
}
Expand Down
56 changes: 54 additions & 2 deletions nomt/src/merkle/page_walker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};

Expand Down Expand Up @@ -165,6 +165,8 @@ pub struct PageWalker<H> {
child_page_roots: Vec<(TriePosition, Node)>,
root: Node,
output_pages: Vec<UpdatedPage>,
// Elided pages changed by the walk, and pages that stopped being elided (`None`).
elided_pages: Vec<(PageId, Option<ElidedPage>)>,

// the stack contains pages (ascending) which are descendants of the parent page, if any.
stack: Vec<StackPage>,
Expand All @@ -191,6 +193,7 @@ impl<H: NodeHasher> PageWalker<H> {
child_page_roots: Vec::new(),
root,
output_pages: Vec::new(),
elided_pages: Vec::new(),
stack: Vec::new(),
sibling_stack: Vec::new(),
prev_node: None,
Expand Down Expand Up @@ -460,8 +463,20 @@ impl<H: NodeHasher> PageWalker<H> {

/// 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<ElidedPage>)>) {
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() {
Expand Down Expand Up @@ -769,11 +784,37 @@ impl<H: NodeHasher> PageWalker<H> {
.elided_children
.set_elide(child_index.clone(), true);

let elided = |page: Page| ElidedPage {
diff: reachable_nodes::<H>(&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;
}
Expand All @@ -794,6 +835,10 @@ impl<H: NodeHasher> PageWalker<H> {
.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);
}
}
Expand Down Expand Up @@ -824,6 +869,13 @@ fn for_each_reachable<H: NodeHasher>(
}
}

/// A diff marking every node reachable in the page.
fn reachable_nodes<H: NodeHasher>(page: &Page) -> PageDiff {
let mut diff = PageDiff::default();
for_each_reachable::<H>(|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<H: NodeHasher>(page: &PageMut) -> u64 {
Expand Down
53 changes: 50 additions & 3 deletions nomt/src/merkle/seek.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand All @@ -205,7 +231,7 @@ impl SeekRequest {
&self.position,
page.clone(),
);
self.continue_leaves_fetch::<H>(page_set, overlay, None);
self.continue_leaves_fetch::<H>(page_set, overlay, page_cache, None);
}
}

Expand Down Expand Up @@ -285,6 +311,7 @@ impl SeekRequest {
&mut self,
page_set: &mut PageSet,
overlay: &LiveOverlay,
page_cache: &PageCache,
leaf: Option<LeafNodeRef>,
) {
let RequestState::FetchingLeaves {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -765,6 +804,7 @@ impl<H: HashAlgorithm> Seeker<H> {
&page,
self.record_siblings,
page_set,
&self.page_cache,
);
continue;
}
Expand Down Expand Up @@ -812,6 +852,7 @@ impl<H: HashAlgorithm> Seeker<H> {
.continue_leaves_fetch::<H>(
page_set,
&self.overlay,
&self.page_cache,
Some(leaf),
),
// PANIC: The state cannot be `RequestState::Seeking`, we would have entered
Expand Down Expand Up @@ -906,6 +947,7 @@ impl<H: HashAlgorithm> Seeker<H> {
&page,
self.record_siblings,
page_set,
&self.page_cache,
);

if !request.is_completed() {
Expand Down Expand Up @@ -944,7 +986,12 @@ impl<H: HashAlgorithm> Seeker<H> {
request.continue_leaf_fetch::<H>(Some(leaf.clone()));
}
RequestState::FetchingLeaves { .. } => {
request.continue_leaves_fetch::<H>(page_set, &self.overlay, Some(leaf.clone()));
request.continue_leaves_fetch::<H>(
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.
Expand Down
Loading
Loading