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
61 changes: 56 additions & 5 deletions crates/blockzilla-model/src/projection_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<ResolvedInstruction>>,
balances: Vec<Vec<RecordedTokenBalance>>,
balances: [Vec<Vec<RecordedTokenBalance>>; BALANCE_SIZE_CLASSES],
balance_buffers: usize,
data: Vec<Vec<u8>>,
accounts: Vec<Vec<[u8; 32]>>,
bytes: usize,
Expand All @@ -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::<RecordedTokenBalance>();
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();
Expand Down Expand Up @@ -102,9 +126,30 @@ impl ProjectionPool {
}

pub fn balances(&mut self) -> Vec<RecordedTokenBalance> {
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<Vec<RecordedTokenBalance>, 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<Vec<RecordedTokenBalance>> {
let value = self.balances[first_class..].iter_mut().find_map(Vec::pop)?;
self.balance_buffers -= 1;
self.bytes -= value.capacity() * size_of::<RecordedTokenBalance>();
value
Some(value)
}

pub fn recycle_block(&mut self, block: &mut CanonicalBlock) {
Expand Down Expand Up @@ -141,11 +186,17 @@ impl ProjectionPool {
let bytes = transaction.token_balances.capacity() * size_of::<RecordedTokenBalance>();
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)
}
Original file line number Diff line number Diff line change
Expand Up @@ -1751,16 +1751,18 @@ impl<S: RangeSource> CompactV2InstructionSource<S> {
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)
}
};
Expand Down Expand Up @@ -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);
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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);
Expand Down