From d27e504a80c27ff81f23db4e705daa91cd9222b1 Mon Sep 17 00:00:00 2001 From: augustin Date: Thu, 26 Nov 2026 14:24:43 +0100 Subject: [PATCH] Reuse token balance buffers and registry page allocations --- .../blockzilla-model/src/projection_pool.rs | 61 +++++++++++++++++-- .../src/compact_query.rs | 60 +++++++++++++++--- .../src/compact_query/registry_cache.rs | 25 +++++--- 3 files changed, 126 insertions(+), 20 deletions(-) diff --git a/crates/blockzilla-model/src/projection_pool.rs b/crates/blockzilla-model/src/projection_pool.rs index 31b5ae98..b7d6fc79 100644 --- a/crates/blockzilla-model/src/projection_pool.rs +++ b/crates/blockzilla-model/src/projection_pool.rs @@ -3,11 +3,15 @@ use crate::{CanonicalBlock, RecordedTokenBalance, ResolvedInstruction}; const MAX_RETAINED_BYTES: usize = 8 << 20; const MAX_BUFFERS: usize = 16_384; +// Token metadata can contain 256 rows per side. The final class also holds +// larger buffers supplied by callers of the public projection API. +const BALANCE_SIZE_CLASSES: usize = 10; #[derive(Debug, Default)] pub struct ProjectionPool { instructions: Vec>, - balances: Vec>, + balances: [Vec>; BALANCE_SIZE_CLASSES], + balance_buffers: usize, data: Vec>, accounts: Vec>, bytes: usize, @@ -22,6 +26,26 @@ mod tests { TransactionHeader, }; + #[test] + fn balance_buffer_reuse_skips_an_undersized_buffer() { + let mut pool = ProjectionPool::default(); + let small = Vec::with_capacity(4); + let large = Vec::with_capacity(32); + let small_ptr = small.as_ptr(); + let large_ptr = large.as_ptr(); + pool.bytes = (small.capacity() + large.capacity()) * size_of::(); + pool.balance_buffers = 2; + pool.balances[balance_size_class(small.capacity())].push(small); + pool.balances[balance_size_class(large.capacity())].push(large); + + let larger_request = pool.balances_with_capacity(25).unwrap(); + let smaller_request = pool.balances_with_capacity(3).unwrap(); + assert_eq!(larger_request.as_ptr(), large_ptr); + assert_eq!(smaller_request.as_ptr(), small_ptr); + assert_eq!(pool.bytes, 0); + assert_eq!(pool.balance_buffers, 0); + } + #[test] fn retains_nested_buffers_without_retaining_old_values() { let mut pool = ProjectionPool::default(); @@ -102,9 +126,30 @@ impl ProjectionPool { } pub fn balances(&mut self) -> Vec { - let value = self.balances.pop().unwrap_or_default(); + self.take_balance_buffer(0).unwrap_or_default() + } + + /// Prefer a recycled buffer that fits the complete transaction. This + /// avoids growing a small buffer while a larger one waits in the pool. + pub fn balances_with_capacity( + &mut self, + minimum_capacity: usize, + ) -> Result, std::collections::TryReserveError> { + let capacity = minimum_capacity + .checked_next_power_of_two() + .unwrap_or(minimum_capacity); + let mut value = self + .take_balance_buffer(balance_size_class(capacity)) + .unwrap_or_default(); + value.try_reserve_exact(capacity)?; + Ok(value) + } + + fn take_balance_buffer(&mut self, first_class: usize) -> Option> { + let value = self.balances[first_class..].iter_mut().find_map(Vec::pop)?; + self.balance_buffers -= 1; self.bytes -= value.capacity() * size_of::(); - value + Some(value) } pub fn recycle_block(&mut self, block: &mut CanonicalBlock) { @@ -141,11 +186,17 @@ impl ProjectionPool { let bytes = transaction.token_balances.capacity() * size_of::(); if bytes != 0 && bytes <= MAX_RETAINED_BYTES.saturating_sub(self.bytes) - && self.balances.len() < MAX_BUFFERS + && self.balance_buffers < MAX_BUFFERS { self.bytes += bytes; - self.balances.push(transaction.token_balances); + self.balance_buffers += 1; + let class = balance_size_class(transaction.token_balances.capacity()); + self.balances[class].push(transaction.token_balances); } } } } + +fn balance_size_class(capacity: usize) -> usize { + (capacity.max(1).ilog2() as usize).min(BALANCE_SIZE_CLASSES - 1) +} diff --git a/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query.rs b/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query.rs index 42259463..ae7058d9 100644 --- a/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query.rs +++ b/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query.rs @@ -1751,16 +1751,18 @@ impl CompactV2InstructionSource { let output = match &mut output { Some(output) => output, slot @ None => { - let mut buffer = context.output_pool.balances(); - if matches!(requirement, TokenBalanceRequirement::All) { - buffer - .try_reserve(pre.len().saturating_add(post.len())) + let buffer = if matches!(requirement, TokenBalanceRequirement::All) { + context + .output_pool + .balances_with_capacity(pre.len() + post.len()) .map_err(|_| { CompactV2InstructionSourceError::Invalid( "failed to reserve projected token balances".into(), ) - })?; - } + })? + } else { + context.output_pool.balances() + }; slot.insert(buffer) } }; @@ -7869,6 +7871,48 @@ pub(crate) mod tests { ); } + #[test] + fn registry_page_replacement_preserves_other_workers_keys() { + // The two pages map to the same shared slot and per-worker recent slot. + let second_page = 1024 * 512; + let mut registry = vec![[0; REGISTRY_KEY_BYTES]; second_page + 1]; + registry[0] = [1; REGISTRY_KEY_BYTES]; + registry[second_page] = [2; REGISTRY_KEY_BYTES]; + let fixture = Fixture::build(registry, vec![Vec::new()], None); + let reader = + open_trusted_test_reader(crate::PinnedLocalRangeSource::new(fixture.directory.path())); + let request = ScanRequest::token_balances_only(); + let pages = SharedRegistryPages::for_scan(&reader, &request).unwrap(); + let mut first = RegistryPageResolver::new(Arc::clone(&pages)); + let mut second = RegistryPageResolver::new(pages); + let mut io = ContextIo::default(); + let first_id = 1; + let second_id = second_page as u32 + 1; + assert_eq!( + first.resolve(&reader, first_id, &mut io).unwrap(), + [1; REGISTRY_KEY_BYTES] + ); + assert_eq!( + second.resolve(&reader, first_id, &mut io).unwrap(), + [1; REGISTRY_KEY_BYTES] + ); + assert_eq!(io.calls, 1); + assert_eq!( + first.resolve(&reader, second_id, &mut io).unwrap(), + [2; REGISTRY_KEY_BYTES] + ); + assert_eq!( + second.resolve(&reader, first_id, &mut io).unwrap(), + [1; REGISTRY_KEY_BYTES] + ); + assert_eq!(io.calls, 2); + assert_eq!( + first.resolve(&reader, first_id, &mut io).unwrap(), + [1; REGISTRY_KEY_BYTES] + ); + assert_eq!(io.calls, 3); + } + #[test] fn parallel_local_projection_shares_registry_reads_and_preserves_output() { let fixture = indexer_fixture(12); @@ -7889,8 +7933,10 @@ pub(crate) mod tests { let (output, receipt) = plain_scan_bytes(&mut source, &request, config); let receipt = receipt.unwrap(); assert_eq!(output, expected); + // One worker can handle all token-bearing blocks in this small fixture. assert!( - baseline.scan.io.source_read_bytes.unwrap() > fixture.compressed_bytes + registry_bytes + baseline.scan.io.source_read_bytes.unwrap() + >= fixture.compressed_bytes + registry_bytes ); assert_eq!( receipt.scan.io.source_read_bytes, diff --git a/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query/registry_cache.rs b/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query/registry_cache.rs index 74a5f013..8f92057d 100644 --- a/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query/registry_cache.rs +++ b/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query/registry_cache.rs @@ -62,19 +62,26 @@ impl SharedRegistryPages { // The caller validated the ID against this reader's registry length. let first_key = number * KEYS_PER_PAGE; let count = (reader.registry_entries() as usize - first_key).min(KEYS_PER_PAGE); - let mut keys = slot - .take() - .and_then(Arc::into_inner) - .map_or_else(Vec::new, |page| page.keys); - keys.resize(count, [0; REGISTRY_KEY_BYTES]); + // A partial read must leave the slot empty. The removed page can be + // filled in place only when no other resolver holds a reference. + let mut recycled = slot.take(); + if recycled.as_mut().and_then(Arc::get_mut).is_none() { + recycled = Some(Arc::new(RegistryPage { + number, + keys: Vec::new(), + })); + } + let mut page = recycled.expect("page supplied"); + let page_data = Arc::get_mut(&mut page).expect("page is uniquely owned"); + page_data.keys.resize(count, [0; REGISTRY_KEY_BYTES]); let offset = first_key as u64 * REGISTRY_KEY_BYTES as u64; reader.source().read_range_into_slice( crate::manifest::REGISTRY_FILE, offset, - keys.as_flattened_mut(), + page_data.keys.as_flattened_mut(), )?; - io.record(keys.len() * REGISTRY_KEY_BYTES)?; - let page = Arc::new(RegistryPage { number, keys }); + io.record(page_data.keys.len() * REGISTRY_KEY_BYTES)?; + page_data.number = number; *slot = Some(Arc::clone(&page)); Ok(page) } @@ -108,6 +115,8 @@ impl RegistryPageResolver { if let Some(page) = slot.as_ref().filter(|page| page.number == number) { return Ok(page.keys[key % KEYS_PER_PAGE]); } + // Give the shared cache a chance to reuse this worker's old page. + *slot = None; let page = self.shared.page(reader, number, io)?; let resolved = page.keys[key % KEYS_PER_PAGE]; *slot = Some(page);