From 54be76ec20554a885a8084bbc772e652635ee46f Mon Sep 17 00:00:00 2001 From: augustin Date: Thu, 26 Nov 2026 12:24:13 +0100 Subject: [PATCH 1/2] Share sparse registry pages across local SDK scans --- .../src/compact_query.rs | 74 ++++++++--- .../src/compact_query/indexed_tokens.rs | 10 +- .../src/compact_query/registry_cache.rs | 116 ++++++++++++++++++ .../source/blockzilla-source-local/src/lib.rs | 4 + crates/source/blockzilla-source/src/lib.rs | 12 ++ 5 files changed, 198 insertions(+), 18 deletions(-) create mode 100644 crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query/registry_cache.rs 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 93127664..42259463 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 @@ -6,6 +6,9 @@ //! `OrderedBlockPublisher`. mod indexed_tokens; +mod registry_cache; + +use registry_cache::{RegistryPageResolver, SharedRegistryPages}; use std::{ cell::Cell, @@ -143,7 +146,8 @@ impl CompactV2RegistryReadPolicy { pub enum CompactV2ParallelRegistryMode { /// One complete immutable registry is shared across all workers. SharedFull, - /// Each used worker has its own bounded eight-chunk LRU cache. + /// Each worker uses a bounded cache. Sources with cheap positional reads + /// also share smaller pages across workers. SparseWorkerCache, /// Indexed token output resolves keys through one bounded consumer cache. SparseConsumerCache, @@ -166,9 +170,7 @@ pub struct CompactV2ParallelRegistryReceipt { pub prefetch_read_calls: u64, /// Source bytes used by the one-pass complete-registry prefetch. pub prefetch_read_bytes: u64, - /// Exact shared payload for `SharedFull`; a checked worst-case retained - /// worker-cache payload for `SparseWorkerCache`, or one consumer cache for - /// `SparseConsumerCache`. + /// Maximum retained registry payload across the shared and local caches. pub resident_bound_bytes: u64, } @@ -696,6 +698,10 @@ impl CompactV2InstructionSource { let (shared_registry, mut registry_receipt) = self .parallel_registry_for_scan(start, end, request, requested_transactions, config) .map_err(source_error)?; + let registry_pages = shared_registry + .is_none() + .then(|| SharedRegistryPages::for_scan(&self.reader, request)) + .flatten(); let read_signatures = request.include_primary_signatures; let mut signature_scan = ContiguousSignatureScan::new(&self.reader, start..end, read_signatures); @@ -718,6 +724,8 @@ impl CompactV2InstructionSource { |_| { let mut worker = ParallelProjectionWorker::new(shared_registry.clone()); worker.context.query_keys = Arc::clone(&query_keys); + worker.context.registry_pages = + registry_pages.clone().map(RegistryPageResolver::new); Ok::<_, CompactV2ParallelScanError>(worker) }, |worker, _row_number, block| { @@ -910,16 +918,20 @@ impl CompactV2InstructionSource { registry_receipt.mode, CompactV2ParallelRegistryMode::SparseWorkerCache ) { - registry_receipt.resident_bound_bytes = u64::try_from(pipeline.effective_workers) - .ok() - .and_then(|workers| { - workers.checked_mul(COMPACT_V2_QUERY_REGISTRY_RETAINED_KEY_BYTES as u64) - }) - .ok_or_else(|| { - source_error(CompactV2InstructionSourceError::Invalid( - "sparse registry resident bound overflow".into(), - )) - })?; + registry_receipt.resident_bound_bytes = if let Some(pages) = registry_pages { + pages.retained_key_bytes(pipeline.effective_workers) + } else { + u64::try_from(pipeline.effective_workers) + .ok() + .and_then(|workers| { + workers.checked_mul(COMPACT_V2_QUERY_REGISTRY_RETAINED_KEY_BYTES as u64) + }) + .ok_or_else(|| { + source_error(CompactV2InstructionSourceError::Invalid( + "sparse registry resident bound overflow".into(), + )) + })? + }; } let signature_io = signature_scan.finish().map_err(source_error)?; @@ -3255,6 +3267,7 @@ struct ExactContext { output_pool: blockzilla_model::projection_pool::ProjectionPool, query_keys: Arc, shared_registry: Option>, + registry_pages: Option, registry_chunks: HashMap>, registry_lru: VecDeque, vote_hashes_loaded: bool, @@ -3309,6 +3322,7 @@ impl ExactContext { fn retain_shared_registry(&mut self, registry: Arc) { self.registry_chunks.clear(); self.registry_lru.clear(); + self.registry_pages = None; self.shared_registry = Some(registry); } @@ -3375,6 +3389,9 @@ impl ExactContext { )) }); } + if let Some(pages) = &mut self.registry_pages { + return pages.resolve(reader, id, &mut self.io); + } let zero_based = usize::try_from(id - 1).map_err(|_| { CompactV2InstructionSourceError::Invalid("registry ID exceeds address space".into()) })?; @@ -7852,6 +7869,35 @@ pub(crate) mod tests { ); } + #[test] + fn parallel_local_projection_shares_registry_reads_and_preserves_output() { + let fixture = indexer_fixture(12); + let local = crate::PinnedLocalRangeSource::new(fixture.directory.path()); + let reader = open_trusted_test_reader(local); + let registry_bytes = u64::from(reader.registry_entries()) * REGISTRY_KEY_BYTES as u64; + let mut source = CompactV2InstructionSource::new(reader, FIRST_SLOT).unwrap(); + let mut reference = + CompactV2InstructionSource::new(fixture.trusted_reader(), FIRST_SLOT).unwrap(); + let request = ScanRequest::token_balances_only().allow_unverified_source(); + let config = CompactV2ParallelScanConfig { + max_full_registry_bytes: 0, + ..CompactV2ParallelScanConfig::new(4) + }; + + let (expected, baseline) = plain_scan_bytes(&mut reference, &request, config); + let baseline = baseline.unwrap(); + let (output, receipt) = plain_scan_bytes(&mut source, &request, config); + let receipt = receipt.unwrap(); + assert_eq!(output, expected); + assert!( + baseline.scan.io.source_read_bytes.unwrap() > fixture.compressed_bytes + registry_bytes + ); + assert_eq!( + receipt.scan.io.source_read_bytes, + Some(fixture.compressed_bytes + registry_bytes) + ); + } + #[test] fn parallel_scans_keep_a_loaded_registry_for_later_scans() { let fixture = indexer_fixture(12); diff --git a/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query/indexed_tokens.rs b/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query/indexed_tokens.rs index 060fd02a..6a0479aa 100644 --- a/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query/indexed_tokens.rs +++ b/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query/indexed_tokens.rs @@ -225,6 +225,7 @@ impl CompactV2InstructionSource { let (shared_registry, mut registry_receipt) = self .parallel_registry_for_scan(start, end, request, requested_transactions, config) .map_err(source_error)?; + let mut context = ExactContext::with_shared_registry(shared_registry); if matches!( registry_receipt.mode, CompactV2ParallelRegistryMode::SparseWorkerCache @@ -232,12 +233,13 @@ impl CompactV2InstructionSource { registry_receipt.mode = CompactV2ParallelRegistryMode::SparseConsumerCache; registry_receipt.resident_bound_bytes = COMPACT_V2_QUERY_REGISTRY_RETAINED_KEY_BYTES as u64; + if let Some(pages) = SharedRegistryPages::for_scan(&self.reader, request) { + registry_receipt.resident_bound_bytes = pages.retained_key_bytes(1); + context.registry_pages = Some(RegistryPageResolver::new(pages)); + } } let reader = &self.reader; - let mut resolver = ConsumerResolver { - reader, - context: ExactContext::with_shared_registry(shared_registry), - }; + let mut resolver = ConsumerResolver { reader, context }; let projected_bytes_current = AtomicU64::new(0); let max_projected_block_bytes = AtomicU64::new(0); let max_projected_batch_bytes = AtomicU64::new(0); 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 new file mode 100644 index 00000000..74a5f013 --- /dev/null +++ b/crates/compact-v2/blockzilla-compact-v2-reader/src/compact_query/registry_cache.rs @@ -0,0 +1,116 @@ +//! Sparse registry pages shared by projections of the same pinned generation. + +use super::{ + ArchiveReader, CompactV2InstructionSourceError, CompactV2InstructionSourceResult, ContextIo, + REGISTRY_KEY_BYTES, RangeSource, ScanRequest, request_needs_registry, +}; +use std::sync::{Arc, Mutex}; + +const KEYS_PER_PAGE: usize = 512; +const RECENT_PAGES: usize = 16; +const MAX_SHARED_PAGES: usize = 1024; +const PAGE_BYTES: usize = KEYS_PER_PAGE * REGISTRY_KEY_BYTES; + +#[derive(Debug)] +struct RegistryPage { + number: usize, + keys: Vec<[u8; REGISTRY_KEY_BYTES]>, +} + +/// One bounded cache per scan. A slot lock covers its first read so simultaneous +/// misses for one page use one positional read. Separate slots read in parallel. +#[derive(Debug)] +pub(super) struct SharedRegistryPages { + slots: Box<[Mutex>>]>, +} + +impl SharedRegistryPages { + pub(super) fn for_scan( + reader: &ArchiveReader, + request: &ScanRequest, + ) -> Option> { + if !request_needs_registry(request) + || !reader.source().prefers_small_ranges() + || reader.registry_entries() == 0 + { + return None; + } + let pages = (reader.registry_entries() as usize).div_ceil(KEYS_PER_PAGE); + let slots = (0..pages.min(MAX_SHARED_PAGES)) + .map(|_| Mutex::new(None)) + .collect(); + Some(Arc::new(Self { slots })) + } + + pub(super) fn retained_key_bytes(&self, resolvers: usize) -> u64 { + // Recent pages can outlive eviction from the shared slots. + ((self.slots.len() + resolvers * RECENT_PAGES) * PAGE_BYTES) as u64 + } + + fn page( + &self, + reader: &ArchiveReader, + number: usize, + io: &mut ContextIo, + ) -> CompactV2InstructionSourceResult> { + let mut slot = self.slots[number % self.slots.len()].lock().map_err(|_| { + CompactV2InstructionSourceError::Invalid("registry page cache is poisoned".into()) + })?; + if let Some(page) = slot.as_ref().filter(|page| page.number == number) { + return Ok(Arc::clone(page)); + } + // 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]); + 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(), + )?; + io.record(keys.len() * REGISTRY_KEY_BYTES)?; + let page = Arc::new(RegistryPage { number, keys }); + *slot = Some(Arc::clone(&page)); + Ok(page) + } +} + +/// Each resolver keeps its most recent page references locally. Cache hits +/// here need no locks and never copy a page between workers. +#[derive(Debug)] +pub(super) struct RegistryPageResolver { + shared: Arc, + recent: [Option>; RECENT_PAGES], +} + +impl RegistryPageResolver { + pub(super) fn new(shared: Arc) -> Self { + Self { + shared, + recent: Default::default(), + } + } + + pub(super) fn resolve( + &mut self, + reader: &ArchiveReader, + id: u32, + io: &mut ContextIo, + ) -> CompactV2InstructionSourceResult<[u8; REGISTRY_KEY_BYTES]> { + let key = (id - 1) as usize; + let number = key / KEYS_PER_PAGE; + let slot = &mut self.recent[number % RECENT_PAGES]; + if let Some(page) = slot.as_ref().filter(|page| page.number == number) { + return Ok(page.keys[key % KEYS_PER_PAGE]); + } + let page = self.shared.page(reader, number, io)?; + let resolved = page.keys[key % KEYS_PER_PAGE]; + *slot = Some(page); + Ok(resolved) + } +} diff --git a/crates/source/blockzilla-source-local/src/lib.rs b/crates/source/blockzilla-source-local/src/lib.rs index 28b00040..1939e28b 100644 --- a/crates/source/blockzilla-source-local/src/lib.rs +++ b/crates/source/blockzilla-source-local/src/lib.rs @@ -545,6 +545,10 @@ impl RangeSource for PinnedLocalRangeSource { self.read_concurrency } + fn prefers_small_ranges(&self) -> bool { + true + } + fn size(&self, object: &str) -> SourceResult> { Ok(self.pinned_file(object)?.map(|file| file.identity.size)) } diff --git a/crates/source/blockzilla-source/src/lib.rs b/crates/source/blockzilla-source/src/lib.rs index f4e19de0..842730c5 100644 --- a/crates/source/blockzilla-source/src/lib.rs +++ b/crates/source/blockzilla-source/src/lib.rs @@ -21,6 +21,14 @@ pub trait RangeSource: Send + Sync { 1 } + /// Whether small positional reads have low overhead on this source. + /// + /// Readers can use smaller cache pages when this is true. The default + /// suits sources where round trips make larger ranges preferable. + fn prefers_small_ranges(&self) -> bool { + false + } + /// Return `None` only when the object does not exist. fn size(&self, object: &str) -> SourceResult>; @@ -88,6 +96,10 @@ impl RangeSource for Arc { (**self).recommended_read_concurrency() } + fn prefers_small_ranges(&self) -> bool { + (**self).prefers_small_ranges() + } + fn size(&self, object: &str) -> SourceResult> { (**self).size(object) } From 29b564dcaf093e3e37b05fa198b1742c80948dae Mon Sep 17 00:00:00 2001 From: augustin Date: Thu, 26 Nov 2026 12:33:41 +0100 Subject: [PATCH 2/2] Use five8 for fixed-width archive key and signature reads --- blockzilla/cli/Cargo.toml | 2 +- blockzilla/cli/src/archive_v2/direct_agave.rs | 5 +-- blockzilla/cli/src/dump_tokens.rs | 16 ++++--- blockzilla/get-block/src/transaction_rpc.rs | 44 ++++++++----------- .../src/worker/foundation_first/finalized.rs | 22 +++++----- .../src/worker/foundation_first/recent.rs | 13 +++--- 6 files changed, 47 insertions(+), 55 deletions(-) diff --git a/blockzilla/cli/Cargo.toml b/blockzilla/cli/Cargo.toml index 2f236151..cca25a24 100644 --- a/blockzilla/cli/Cargo.toml +++ b/blockzilla/cli/Cargo.toml @@ -37,7 +37,6 @@ blockzilla-program-logs = { path = "../../crates/parser/blockzilla-program-logs" blockzilla-registry = { path = "../../crates/compact-v2/blockzilla-registry", default-features = false, version = "0.2.0" } anyhow = "1.0.104" bincode = "1.3.3" -bs58 = "0.5.1" # Allocation-free base58 and integer text for the token dump rows. five8 = "1.0.0" itoa = "1.0.18" @@ -58,6 +57,7 @@ wincode = { version = "=0.6.1", features = ["derive"] } zstd = "0.14.0" [dev-dependencies] +bs58 = "0.5.1" tempfile = "3.27.0" [lints] diff --git a/blockzilla/cli/src/archive_v2/direct_agave.rs b/blockzilla/cli/src/archive_v2/direct_agave.rs index 8d15bc05..cf110aad 100644 --- a/blockzilla/cli/src/archive_v2/direct_agave.rs +++ b/blockzilla/cli/src/archive_v2/direct_agave.rs @@ -100,10 +100,7 @@ fn validate(r: &Receipt) -> Result<()> { "unsupported Agave source revision" ); for value in [&r.genesis_hash, &r.node_identity] { - ensure!( - bs58::decode(value).into_vec()?.len() == 32, - "invalid source identity" - ); + five8::decode_32(value, &mut [0; 32]).context("invalid source identity")?; } ensure!( (1..=4096).contains(&r.blocks.len()) && r.start_slot < r.end_slot_exclusive, diff --git a/blockzilla/cli/src/dump_tokens.rs b/blockzilla/cli/src/dump_tokens.rs index fa28ccfe..86863a93 100644 --- a/blockzilla/cli/src/dump_tokens.rs +++ b/blockzilla/cli/src/dump_tokens.rs @@ -25,11 +25,12 @@ pub(crate) struct DumpTokensArgs { } fn parse_mint(value: &str) -> Result<[u8; 32], String> { - bs58::decode(value) - .into_vec() - .map_err(|error| format!("Invalid base58 mint: {error}"))? - .try_into() - .map_err(|_| "A mint must decode to exactly 32 bytes".into()) + let mut mint = [0; 32]; + five8::decode_32(value, &mut mint).map_err(|error| match error { + five8::DecodeError::InvalidChar(_) => format!("Invalid base58 mint: {error}"), + _ => "A mint must decode to exactly 32 bytes".into(), + })?; + Ok(mint) } /// Output buffer for standard output. The sink flushes once per accepted @@ -391,6 +392,11 @@ mod tests { fn mint_parser_requires_exact_public_key_length() { assert!(parse_mint("bad!").is_err()); assert!(parse_mint("1").is_err()); + assert!(parse_mint(&"1".repeat(33)).is_err()); + assert_eq!( + parse_mint(&bs58::encode([255; 32]).into_string()).unwrap(), + [255; 32] + ); assert_eq!( parse_mint("11111111111111111111111111111111").unwrap(), [0; 32] diff --git a/blockzilla/get-block/src/transaction_rpc.rs b/blockzilla/get-block/src/transaction_rpc.rs index 9cc3e010..f73d4c0f 100644 --- a/blockzilla/get-block/src/transaction_rpc.rs +++ b/blockzilla/get-block/src/transaction_rpc.rs @@ -455,7 +455,10 @@ pub fn encode_transaction( let mut output = Vec::new(); push_short_len(&mut output, signatures.len())?; for signature in signatures { - append_base58(&mut output, signature, 64)?; + let text = signature.as_str().ok_or_else(invalid_base58)?; + let mut bytes = [0; 64]; + five8::decode_64(text, &mut bytes).map_err(|_| invalid_base58())?; + output.extend_from_slice(&bytes); } if version.as_u64() == Some(0) { output.push(0x80); @@ -486,13 +489,11 @@ pub fn encode_transaction( .ok_or_else(invalid)?; push_short_len(&mut output, keys.len())?; for key in keys { - append_base58(&mut output, key, 32)?; + output.extend_from_slice(&decode_base58_key(key)?); } - append_base58( - &mut output, + output.extend_from_slice(&decode_base58_key( message.get("recentBlockhash").ok_or_else(invalid)?, - 32, - )?; + )?); let instructions = message .get("instructions") .and_then(Value::as_array) @@ -528,11 +529,9 @@ pub fn encode_transaction( .ok_or_else(invalid)?; push_short_len(&mut output, lookups.len())?; for lookup in lookups { - append_base58( - &mut output, + output.extend_from_slice(&decode_base58_key( lookup.get("accountKey").ok_or_else(invalid)?, - 32, - )?; + )?); append_indices( &mut output, lookup.get("writableIndexes").ok_or_else(invalid)?, @@ -549,22 +548,15 @@ pub fn encode_transaction( Ok(output) } -fn append_base58( - output: &mut Vec, - value: &Value, - length: usize, -) -> Result<(), TransactionRpcError> { - let invalid = || TransactionRpcError::unavailable("archive contains an invalid base58 value"); - let value = value - .as_str() - .filter(|value| value.len() <= 88) - .ok_or_else(invalid)?; - let bytes = bs58::decode(value).into_vec().map_err(|_| invalid())?; - if bytes.len() != length { - return Err(invalid()); - } - output.extend(bytes); - Ok(()) +fn invalid_base58() -> TransactionRpcError { + TransactionRpcError::unavailable("archive contains an invalid base58 value") +} + +fn decode_base58_key(value: &Value) -> Result<[u8; 32], TransactionRpcError> { + let text = value.as_str().ok_or_else(invalid_base58)?; + let mut bytes = [0; 32]; + five8::decode_32(text, &mut bytes).map_err(|_| invalid_base58())?; + Ok(bytes) } fn append_indices(output: &mut Vec, value: &Value) -> Result<(), TransactionRpcError> { diff --git a/blockzilla/get-block/src/worker/foundation_first/finalized.rs b/blockzilla/get-block/src/worker/foundation_first/finalized.rs index e060b66c..b7adfbe9 100644 --- a/blockzilla/get-block/src/worker/foundation_first/finalized.rs +++ b/blockzilla/get-block/src/worker/foundation_first/finalized.rs @@ -58,12 +58,12 @@ pub(crate) struct LedgerCompactMetadata { impl LedgerCompactMetadata { pub(crate) fn hashes(&self) -> std::result::Result<([u8; 32], [u8; 32]), String> { let hash = |text: &str| -> std::result::Result<[u8; 32], String> { - let bytes: [u8; 32] = bs58::decode(text) - .into_vec() - .map_err(|_| "invalid ledger block hash")? - .try_into() - .map_err(|_| "invalid ledger block hash length")?; - if bytes == [0; 32] || bs58::encode(bytes).into_string() != text { + let mut bytes = [0; 32]; + five8::decode_32(text, &mut bytes).map_err(|error| match error { + five8::DecodeError::InvalidChar(_) => "invalid ledger block hash", + _ => "invalid ledger block hash length", + })?; + if bytes == [0; 32] { return Err("noncanonical ledger block hash".into()); } Ok(bytes) @@ -184,11 +184,11 @@ fn validate_metadata( expected_source: &RecentSource, sha: &[u8; 32], ) -> std::result::Result<(), String> { - let expected_hash: [u8; 32] = bs58::decode(&metadata.blockhash) - .into_vec() - .map_err(|_| "invalid finalized blockhash")? - .try_into() - .map_err(|_| "invalid finalized blockhash length")?; + let mut expected_hash = [0; 32]; + five8::decode_32(&metadata.blockhash, &mut expected_hash).map_err(|error| match error { + five8::DecodeError::InvalidChar(_) => "invalid finalized blockhash", + _ => "invalid finalized blockhash length", + })?; metadata.validate( &RecentRequest { slot, diff --git a/blockzilla/get-block/src/worker/foundation_first/recent.rs b/blockzilla/get-block/src/worker/foundation_first/recent.rs index fe99dae5..ebd19ed4 100644 --- a/blockzilla/get-block/src/worker/foundation_first/recent.rs +++ b/blockzilla/get-block/src/worker/foundation_first/recent.rs @@ -451,14 +451,11 @@ fn cursor_parts(cursor: &str) -> std::result::Result<(&str, u64, &str), String> } fn hash(text: &str) -> std::result::Result<[u8; 32], String> { - let bytes: [u8; 32] = bs58::decode(text) - .into_vec() - .map_err(|_| "invalid compact block hash")? - .try_into() - .map_err(|_| "compact block hash must have 32 bytes")?; - if base58_32(&bytes) != text { - return Err("compact block hash is not canonical".into()); - } + let mut bytes = [0; 32]; + five8::decode_32(text, &mut bytes).map_err(|error| match error { + five8::DecodeError::InvalidChar(_) => "invalid compact block hash", + _ => "compact block hash must have 32 bytes", + })?; Ok(bytes) }