Skip to content
Merged
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
77 changes: 61 additions & 16 deletions grovedb-bulk-append-tree/src/tree/append.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use grovedb_merkle_mountain_range::{
};
use grovedb_storage::StorageContext;

use super::{capacity_for_height, hash::compute_state_root, AppendResult, BulkAppendTree};
use super::{
capacity_for_height, hash::compute_state_root, AppendNoStateRootResult, AppendResult,
BulkAppendTree,
};
use crate::{chunk::serialize_chunk_blob, BulkAppendError};

impl<'db, S: StorageContext<'db>> BulkAppendTree<S> {
Expand All @@ -20,6 +23,8 @@ impl<'db, S: StorageContext<'db>> BulkAppendTree<S> {
total_count: 0,
dense_tree,
mmr_overlay: Vec::new(),
// Empty tree → empty MMR → zero root.
last_mmr_root: Some([0u8; 32]),
})
}

Expand All @@ -44,56 +49,96 @@ impl<'db, S: StorageContext<'db>> BulkAppendTree<S> {
total_count,
dense_tree,
mmr_overlay: Vec::new(),
// Lazy: the restored MMR may not be readable until an append occurs,
// so don't compute the root here. The first append fills the cache.
last_mmr_root: None,
})
}

/// Append a value to the tree.
///
/// Handles dense tree insert, auto-compaction when the buffer fills, and
/// state root computation.
/// state root computation. For batched inserts prefer
/// [`append_many`](Self::append_many) or [`append_no_state_root`](Self::append_no_state_root)
/// — they skip the per-leaf state-root blake3 call.
pub fn append(&mut self, value: &[u8]) -> Result<AppendResult, BulkAppendError> {
let r = self.append_no_state_root(value)?;
let state_root = self.compute_current_state_root()?;
Ok(AppendResult {
state_root,
global_position: r.global_position,
// +1 for the blake3 state-root computation we just did.
hash_count: r.hash_count.saturating_add(1),
compacted: r.compacted,
})
}

/// Append a value without computing the per-leaf state root.
///
/// Equivalent to [`append`](Self::append) minus the final
/// `compute_state_root` blake3 hash. Use inside a batch (typically via
/// [`append_many`](Self::append_many) or
/// [`CommitmentTree::append_many_raw`]) and recover the state root once at
/// the end via [`compute_current_state_root`](Self::compute_current_state_root).
/// Storage mutation is identical to [`append`](Self::append).
///
/// [`CommitmentTree::append_many_raw`]: ../../grovedb_commitment_tree/struct.CommitmentTree.html#method.append_many_raw
pub fn append_no_state_root(
&mut self,
value: &[u8],
) -> Result<AppendNoStateRootResult, BulkAppendError> {
let mut hash_count: u32 = 0;
let global_position = self.total_count;

// 1. Try to insert into the dense tree buffer
// 1. Try to insert into the dense tree buffer.
let try_result = self.dense_tree.try_insert(value).unwrap().map_err(|e| {
BulkAppendError::StorageError(format!("dense tree insert failed: {}", e))
})?;

let (compacted, mmr_root, final_dense_root) = match try_result {
Some((dense_root, _position)) => {
// Inserted successfully, no compaction needed
let compacted = match try_result {
Some((_dense_root, _position)) => {
// Inserted successfully, no compaction needed. The MMR is
// untouched, so its root is unchanged — keep the cache as-is.
// (On the very first append after a lazy open the cache is
// `None`; we don't seed it here because we don't need it —
// the caller will recover the state root via
// `compute_current_state_root` at the end of the batch, which
// populates the cache then.)
hash_count += self.dense_tree.count() as u32 * 2;
let root = self.get_mmr_root()?;
(false, root, dense_root)
false
}
None => {
// Dense tree is full — compact existing entries + new value.
// Must run before incrementing total_count so that
// self.mmr_size() reflects the pre-compaction state.
let (compact_hashes, mmr_root) = self.compact_with_value(value)?;
hash_count += compact_hashes;
(true, mmr_root, [0u8; 32]) // empty tree after reset
// MMR mutated by the compaction — refresh the cached root.
self.last_mmr_root = Some(mmr_root);
true
}
};

self.total_count += 1;

// 2. Compute state root (+1 hash)
let state_root = compute_state_root(&mmr_root, &final_dense_root);
hash_count += 1;

Ok(AppendResult {
state_root,
Ok(AppendNoStateRootResult {
global_position,
hash_count,
compacted,
})
}

/// Compute the current state root without modifying the tree.
///
/// Uses the cached MMR root when available, so this is O(1) on the
/// post-first-append fast path (no overlay clone). Falls back to a one-shot
/// `get_mmr_root` only when the cache is empty (e.g. immediately after a
/// lazy `from_state` with no appends yet).
pub fn compute_current_state_root(&self) -> Result<[u8; 32], BulkAppendError> {
let mmr_root = self.get_mmr_root()?;
let mmr_root = match self.last_mmr_root {
Some(r) => r,
None => self.get_mmr_root()?,
};
let dense_root = self.dense_tree.root_hash().unwrap().map_err(|e| {
BulkAppendError::StorageError(format!("dense tree root_hash failed: {}", e))
})?;
Expand Down
32 changes: 32 additions & 0 deletions grovedb-bulk-append-tree/src/tree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,23 @@ pub struct AppendResult {
pub compacted: bool,
}

/// Result returned by [`BulkAppendTree::append_no_state_root`].
///
/// Same as [`AppendResult`] minus the state root, which the caller computes
/// once at the end of a batch via
/// [`BulkAppendTree::compute_current_state_root`].
#[cfg(feature = "storage")]
#[derive(Debug, Clone, Copy)]
pub struct AppendNoStateRootResult {
/// The 0-based global position of the appended value.
pub global_position: u64,
/// Number of blake3 hash calls performed during this append (excludes the
/// deferred state-root computation).
pub hash_count: u32,
/// Whether compaction (epoch flush) occurred.
pub compacted: bool,
}

/// Compute MMR size from leaf count: `2 * n - popcount(n)`.
///
/// This is a well-known MMR property: the total number of nodes (leaves +
Expand Down Expand Up @@ -75,6 +92,21 @@ pub struct BulkAppendTree<S> {
/// lifetimes (compaction cycles) so that reads can find recently-pushed
/// nodes without a storage round-trip.
pub(crate) mmr_overlay: Vec<(u64, Vec<MmrNode>)>,
/// Cached MMR root, refreshed only when a compaction mutates the MMR.
///
/// The MMR is only touched on compaction (every `epoch_size` appends), so
/// its root is unchanged for the ~`epoch_size - 1` appends in between.
/// Caching it avoids recomputing the root — and cloning the (blob-bearing)
/// `mmr_overlay` — on every append, which would otherwise make bulk
/// appends O(N²) as the overlay grows across compaction cycles.
///
/// `None` means "not yet known" (the state set by [`from_state`], which must
/// stay lazy: the MMR may not be readable until something is appended). It
/// is computed once on the first append after an open, then kept in sync by
/// compaction.
///
/// [`from_state`]: BulkAppendTree::from_state
pub(crate) last_mmr_root: Option<[u8; 32]>,
}

impl<S> BulkAppendTree<S> {
Expand Down
21 changes: 21 additions & 0 deletions grovedb-bulk-append-tree/src/tree/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,27 @@ fn from_state_invalid_height() {
assert!(BulkAppendTree::from_state(0, 17u8, MemStorageContext::new()).is_err());
}

#[test]
fn cached_mmr_root_matches_recomputation_across_compactions() {
// The append fast-path uses a cached MMR root (`last_mmr_root`) instead of
// recomputing it — and cloning the blob-bearing overlay — on every append.
// This guards that the cache never diverges from a fresh recomputation,
// across both compaction and non-compaction appends.
//
// height=2 → epoch_size=4, so 20 appends span 5 compaction cycles.
let mut tree = BulkAppendTree::new(2u8, MemStorageContext::new()).expect("create tree");
for i in 0..20u8 {
tree.append(&[i]).expect("append");
let fresh = tree.get_mmr_root().expect("recompute mmr root");
assert_eq!(
tree.last_mmr_root,
Some(fresh),
"cached MMR root diverged from recomputation after {} append(s)",
i + 1
);
}
}

#[test]
fn single_append() {
let mut tree = BulkAppendTree::new(2u8, MemStorageContext::new()).expect("create tree");
Expand Down
10 changes: 10 additions & 0 deletions grovedb-commitment-tree/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,17 @@ tempfile = { workspace = true }
criterion = { workspace = true }
rand = { workspace = true }
rand_core = "0.6"
# For the `seeding` benchmark: a real RocksDB-backed storage context.
grovedb-storage = { version = "4.0.0", path = "../storage", features = ["rocksdb_storage"] }
grovedb-path = { version = "4.0.0", path = "../path" }

[[bench]]
name = "verification"
harness = false

# Batched commitment-tree seeding throughput. Run with:
# cargo bench -p grovedb-commitment-tree --bench seeding --features server
[[bench]]
name = "seeding"
harness = false
required-features = ["server"]
136 changes: 136 additions & 0 deletions grovedb-commitment-tree/benches/seeding.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
//! Batched commitment-tree seeding throughput benchmark.
//!
//! Pre-populates a real RocksDB-backed [`CommitmentTree`] with `N` random
//! notes via [`CommitmentTree::append_many_raw`] — the batched API that
//! computes the Sinsemilla anchor and the BulkAppendTree state root once at
//! the end of the batch instead of once per leaf. Byte-for-byte equivalent to
//! `N × CommitmentTree::append_raw`, just without the per-leaf depth-32
//! Sinsemilla root walk.
//!
//! Run with:
//! ```text
//! cargo bench -p grovedb-commitment-tree --bench seeding --features server
//! ```
//!
//! The note count defaults to 1,000,000 and can be overridden:
//! ```text
//! SEED_N=200000 cargo bench -p grovedb-commitment-tree --bench seeding --features server
//! ```

#[cfg(feature = "server")]
fn main() {
use std::time::Instant;

use grovedb_commitment_tree::{
ciphertext_payload_size, merkle_hash_from_bytes, CommitmentTree, DashMemo,
};
use grovedb_path::SubtreePath;
use grovedb_storage::{rocksdb_storage::RocksDbStorage, Storage, StorageBatch};
use rand::{rngs::StdRng, Rng, SeedableRng};

let n: u64 = std::env::var("SEED_N")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(1_000_000);
// Production value: 2^11 = 2048 notes per completed chunk.
let chunk_power: u8 = 11;
let payload_len = ciphertext_payload_size::<DashMemo>();
let entry_len = 64 + payload_len; // cmx(32) + rho(32) + payload

// Real on-disk RocksDB in a temp dir.
let tmp = tempfile::TempDir::new().expect("create tempdir");
let storage =
RocksDbStorage::default_rocksdb_with_path(tmp.path()).expect("open rocksdb storage");
let tx = storage.start_transaction();
let batch = StorageBatch::new();
let ct_path = SubtreePath::from(&[b"shielded_notes" as &[u8]]);
let ctx = storage
.get_transactional_storage_context(ct_path, Some(&batch), &tx)
.value;
let mut ct =
CommitmentTree::<_, DashMemo>::new(chunk_power, ctx).expect("create commitment tree");

// Deterministic, lazily-generated note stream — never materialized in full.
// The cmx is rejection-sampled to a valid Pallas field element so the
// batched anchor stays sound (matching what real notes do).
let mut rng = StdRng::seed_from_u64(0xC0FFEE);
let notes = std::iter::from_fn(move || {
let mut cmx = [0u8; 32];
loop {
rng.fill_bytes(&mut cmx);
if merkle_hash_from_bytes(&cmx).is_some() {
break;
}
}
let mut rho = [0u8; 32];
let mut payload = vec![0u8; payload_len];
rng.fill_bytes(&mut rho);
rng.fill_bytes(&mut payload);
Some((cmx, rho, payload))
})
.take(n as usize);

eprintln!(
"Seeding {n} notes via append_many_raw (chunk_power={chunk_power}, payload={payload_len}B, entry={entry_len}B, ~{} MiB of note data)...",
(n as usize * entry_len) / (1024 * 1024)
);

// 1. Batched bulk append — compute + in-memory batch accumulation.
// Sinsemilla anchor + bulk state root are each computed exactly once
// at the end, not per leaf.
let t_seed = Instant::now();
let result = ct
.append_many_raw(notes)
.value
.expect("batched commitment-tree seeding");
// Flush the MMR overlay into the storage batch now that we're done
// appending. Must come before dropping `ct` (which would lose the overlay)
// and before committing the storage batch (which writes to disk).
ct.commit_mmr().expect("commit_mmr");

let seed_elapsed = t_seed.elapsed();

// Release the storage context's borrow of the batch before committing.
drop(ct);

// 2. Flush the batch into the transaction, then commit the transaction to
// disk (the actual RocksDB write).
let t_commit = Instant::now();
storage
.commit_multi_context_batch(batch, Some(&tx))
.value
.expect("commit batch into transaction");
storage
.commit_transaction(tx)
.value
.expect("commit transaction to disk");
let commit_elapsed = t_commit.elapsed();

let total = seed_elapsed + commit_elapsed;
let rate = |d: std::time::Duration| n as f64 / d.as_secs_f64();

eprintln!("---------------------------------------------");
eprintln!("appended : {}", n);
eprintln!("last position : {}", result.global_position);
eprintln!("compacted : {}", result.compacted);
eprintln!(
"seed (compute) : {:.3?} ({:.0} notes/s)",
seed_elapsed,
rate(seed_elapsed)
);
eprintln!("commit (disk) : {:.3?}", commit_elapsed);
eprintln!(
"TOTAL : {:.3?} ({:.0} notes/s)",
total,
rate(total)
);
eprintln!("---------------------------------------------");
}

#[cfg(not(feature = "server"))]
fn main() {
eprintln!(
"The `seeding` benchmark requires the `server` feature.\n\
Run: cargo bench -p grovedb-commitment-tree --bench seeding --features server"
);
}
Loading
Loading