Unverified Commit dcfb0c1c authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

turbo-persistence: make batch_get callback-oriented

batch_get now reports each key index to a callback, possibly concurrently,
instead of returning an ordered Vec. The backend decodes TaskStorage inside
the callback, so decoding runs in parallel with the reads for large
batches, and writes the results into its restore entries directly.

This replaces the separate parallel decode step from #100453
(decode_task_storage_batch, PARALLEL_DECODE_THRESHOLD, batch_lookup_raw and
the batch_lookup bench). The batch lookup round-trip test now covers the
callback API on both sides of batch_get's parallel cutoff, including a
malformed value.

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent a72565ab
......@@ -555,8 +555,11 @@ fn bench_read_batch_get(c: &mut Criterion) {
.collect::<Vec<_>>()
},
|keys| {
let result = db.batch_get(0, &keys).unwrap();
black_box(result)
db.batch_get(0, &keys, |index, value| {
black_box((index, value));
Ok(())
})
.unwrap()
},
BatchSize::NumBatches(1),
);
......@@ -585,8 +588,11 @@ fn bench_read_batch_get(c: &mut Criterion) {
.collect::<Vec<_>>()
},
|keys| {
let result = db.batch_get(0, &keys).unwrap();
black_box(result)
db.batch_get(0, &keys, |index, value| {
black_box((index, value));
Ok(())
})
.unwrap()
},
BatchSize::NumBatches(1),
);
......@@ -914,11 +920,23 @@ fn bench_family_sharding(c: &mut Criterion) {
});
group.bench_function("batch_get/hit_64", |b| {
let (_, db) = &*db;
b.iter(|| black_box(db.batch_get(2, black_box(&batch_hits)).unwrap()))
b.iter(|| {
db.batch_get(2, black_box(&batch_hits), |index, value| {
black_box((index, value));
Ok(())
})
.unwrap()
})
});
group.bench_function("batch_get/miss_64", |b| {
let (_, db) = &*db;
b.iter(|| black_box(db.batch_get(2, black_box(&batch_misses)).unwrap()))
b.iter(|| {
db.batch_get(2, black_box(&batch_misses), |index, value| {
black_box((index, value));
Ok(())
})
.unwrap()
})
});
group.finish();
}
......
use std::cell::UnsafeCell;
/// A mutably borrowed slice whose elements can be written from multiple threads, as long as each
/// element is written at most once while the slice is shared.
pub(crate) struct ConcurrentSlice<'l, T> {
data: &'l [UnsafeCell<T>],
}
// SAFETY: Through a shared `ConcurrentSlice`, other threads move `T` values into the slice and drop
// the values they replace, which requires `T: Send`. It never hands out references to elements, so
// it doesn't require `T: Sync`. Callers of `write` guarantee that no element is accessed by two
// threads. Distinct elements are distinct memory locations, so writes from different threads to
// different elements never race or tear, even when `T` is a single byte. This is the same
// guarantee that makes sending the halves of `split_at_mut` to different threads sound.
unsafe impl<T: Send> Send for ConcurrentSlice<'_, T> {}
// SAFETY: See above.
unsafe impl<T: Send> Sync for ConcurrentSlice<'_, T> {}
impl<'l, T> ConcurrentSlice<'l, T> {
pub(crate) fn new(slice: &'l mut [T]) -> Self {
let len = slice.len();
// SAFETY: `UnsafeCell<T>` has the same memory layout as `T` (it is `#[repr(transparent)]`),
// and the pointer comes from a mutable borrow of `len` elements that lasts for `'l`, so no
// other access to the elements exists while `data` is alive.
let data =
unsafe { std::slice::from_raw_parts(slice.as_mut_ptr().cast::<UnsafeCell<T>>(), len) };
Self { data }
}
/// Replaces the element at `index` with `value`, dropping the previous value. Panics if
/// `index` is out of bounds.
///
/// # Safety
///
/// Each `index` must be written at most once while `self` is shared, so no two threads access
/// the same element.
pub(crate) unsafe fn write(&self, index: usize, value: T) {
let cell = &self.data[index];
// SAFETY: The caller guarantees that no other access to this element happens concurrently.
unsafe { *cell.get() = value };
}
}
#[cfg(test)]
mod tests {
use crate::concurrent_slice::ConcurrentSlice;
#[test]
fn writes_from_multiple_threads() {
const LEN: usize = 64;
// The previous values are boxed, so leaking or double-dropping them is detected by Miri.
let mut values: Vec<Option<Box<usize>>> = vec![Some(Box::new(usize::MAX)); LEN];
let writer = ConcurrentSlice::new(&mut values);
std::thread::scope(|scope| {
for thread in 0..4 {
let writer = &writer;
scope.spawn(move || {
for index in (thread..LEN).step_by(4) {
// SAFETY: Each thread writes a distinct residue class of indices.
unsafe { writer.write(index, Some(Box::new(index))) };
}
});
}
});
for (index, value) in values.iter().enumerate() {
assert_eq!(value.as_deref(), Some(&index));
}
}
#[test]
fn writes_adjacent_bytes_from_multiple_threads() {
const LEN: usize = 64;
let mut values = [0u8; LEN];
let writer = ConcurrentSlice::new(&mut values);
std::thread::scope(|scope| {
for thread in 0..4 {
let writer = &writer;
scope.spawn(move || {
// Adjacent bytes are written by different threads.
for index in (thread..LEN).step_by(4) {
// SAFETY: Each thread writes a distinct residue class of indices.
unsafe { writer.write(index, index as u8 + 1) };
}
});
}
});
for (index, &value) in values.iter().enumerate() {
assert_eq!(value, index as u8 + 1);
}
}
#[test]
#[should_panic]
fn write_out_of_bounds_panics() {
let mut values = [0u32; 4];
let writer = ConcurrentSlice::new(&mut values);
// SAFETY: No other write happens.
unsafe { writer.write(4, 1) };
}
}
......@@ -39,7 +39,6 @@ use crate::{
arc_bytes::ArcBytes,
compaction::selector::{Compactable, MergeJob, plan_compaction},
compression::{Compression, checksum_block, decompress_into_arc},
concurrent_slice::ConcurrentSlice,
constants::{
DATA_THRESHOLD_PER_COMPACTED_FILE, KEY_BLOCK_AVG_SIZE, KEY_BLOCK_CACHE_SIZE,
MAX_ENTRIES_PER_COMPACTED_FILE, VALUE_BLOCK_AVG_SIZE, VALUE_BLOCK_CACHE_SIZE,
......@@ -2442,15 +2441,26 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
Ok(output)
}
/// Looks up many keys of a [`FamilyKind::SingleValue`] family at once. The result has one entry
/// per key, in the order of `keys`.
/// Looks up many keys of a [`FamilyKind::SingleValue`] family at once.
///
/// Calls `on_result` with the index of the key in `keys` and its value, or `None` if the key
/// is missing or deleted. When this returns `Ok`, `on_result` was called exactly once for every
/// index, including each occurrence of a duplicate key. The calls happen in no particular order
/// and may run concurrently on other threads.
///
/// If a read fails or `on_result` returns an error, the error is returned. Other calls may have
/// happened by then, and some indices may never be reported.
///
/// `on_result` runs while the database holds an internal read lock, so it must not call back
/// into this database.
///
/// Panics if there are more than `u32::MAX` keys.
pub fn batch_get<K: QueryKey + Sync>(
&self,
family: usize,
keys: &[K],
) -> Result<Vec<Option<ArcBytes>>> {
on_result: impl Fn(usize, Option<ArcBytes>) -> Result<()> + Sync,
) -> Result<()> {
debug_assert!(family < FAMILIES, "Family index out of bounds");
if self.config.family_configs[family].kind != FamilyKind::SingleValue {
// This is an error in our caller so just panic
......@@ -2501,15 +2511,14 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
inner.shard_indices[family].bits(),
target_chunk_count,
);
let mut results: Vec<Option<ArcBytes>> = vec![None; keys.len()];
let results_writer = ConcurrentSlice::new(&mut results);
let on_result = &on_result;
let lookup_chunk = |chunk: &mut BatchGetChunk<'_>| {
self.batch_get_chunk(
inner,
family,
keys,
chunk,
&results_writer,
on_result,
key_block_cache,
value_block_cache,
)
......@@ -2531,11 +2540,12 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
span.record("result_size", counts.result_size);
#[cfg(feature = "stats")]
self.record_batch_get_stats(counts);
Ok(results)
Ok(())
}
/// Looks up the keys of a chunk for [`Self::batch_get`]. Values found (including blobs) are
/// written to `results` at the index of their key.
/// Looks up the keys of a chunk for [`Self::batch_get`] and reports each of them to
/// `on_result` once: found values (including blobs) as soon as they are read, and missing or
/// deleted keys as `None`.
#[allow(clippy::too_many_arguments)]
fn batch_get_chunk<K: QueryKey>(
&self,
......@@ -2543,7 +2553,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
family: usize,
keys: &[K],
chunk: &mut BatchGetChunk<'_>,
results: &ConcurrentSlice<'_, Option<ArcBytes>>,
on_result: &impl Fn(usize, Option<ArcBytes>) -> Result<()>,
key_block_cache: &BlockCache,
value_block_cache: &BlockCache,
) -> Result<()> {
......@@ -2565,7 +2575,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
let value = match value {
LookupValue::KeyDeleted => {
counts.deleted += 1;
return Ok(());
return on_result(index as usize, None);
}
LookupValue::KeyValueDeleted { .. } => {
// Key-value tombstones are only written to MultiValue families, and
......@@ -2594,11 +2604,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
}
};
counts.result_size += value.len();
// SAFETY: Every key index occurs in exactly one cell, every cell belongs to exactly one
// chunk, and `batch_lookup_entry` reports each cell at most once since it is marked as
// resolved. So every index is written at most once.
unsafe { results.write(index as usize, Some(value)) };
Ok(())
on_result(index as usize, Some(value))
};
let shard_files = inner.shard_indices[family].shard(*shard);
#[cfg(feature = "stats")]
......@@ -2636,6 +2642,14 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
// `on_found` borrows `counts`.
drop(on_found);
counts.not_found += cells.len() - resolved_count;
if resolved_count < cells.len() {
for (position, &(_, index)) in cells.iter().enumerate() {
// `batch_get` has at most `u32::MAX` keys, so positions fit in a `u32`.
if !resolved.contains(position as u32) {
on_result(index as usize, None)?;
}
}
}
#[cfg(feature = "stats")]
{
counts.range_misses += lookup_counts.range_misses;
......
......@@ -15,7 +15,6 @@ mod collector;
mod collector_entry;
mod compaction;
mod compression;
mod concurrent_slice;
mod constants;
mod db;
mod key;
......
#[cfg(not(miri))]
use std::time::Instant;
use std::{fs, path::Path};
use std::{fs, path::Path, sync::OnceLock};
use anyhow::Result;
#[cfg(not(miri))]
......@@ -12,10 +12,11 @@ use rstest::rstest;
#[cfg(miri)]
use crate::parallel_scheduler::SerialScheduler as RayonParallelScheduler;
use crate::{
AccessMode, Compression, DbConfig, FamilyConfig, FamilyKind,
AccessMode, ArcBytes, Compression, DbConfig, FamilyConfig, FamilyKind, QueryKey,
constants::MAX_INLINE_VALUE_SIZE,
db::{CompactConfig, TurboPersistence, read_current_version},
lookup_entry::IterValue,
parallel_scheduler::ParallelScheduler as ParallelSchedulerTrait,
static_sorted_file::{StaticSortedFileIter, StaticSortedFileMetaData},
};
#[cfg(not(miri))]
......@@ -173,6 +174,32 @@ fn open_db_with_config<const F: usize>(
)
}
/// Collects the results of [`TurboPersistence::batch_get`] in the order of `keys`, asserting that
/// every index is reported exactly once.
fn batch_get_vec<S: ParallelSchedulerTrait, const F: usize, K: QueryKey + Sync>(
db: &TurboPersistence<S, F>,
family: usize,
keys: &[K],
) -> Result<Vec<Option<ArcBytes>>> {
let results: Vec<OnceLock<Option<ArcBytes>>> = keys.iter().map(|_| OnceLock::new()).collect();
db.batch_get(family, keys, |index, value| {
assert!(
results[index].set(value).is_ok(),
"index {index} was reported more than once"
);
Ok(())
})?;
Ok(results
.into_iter()
.enumerate()
.map(|(index, result)| {
result
.into_inner()
.unwrap_or_else(|| panic!("index {index} was never reported"))
})
.collect())
}
fn multi_value_config_with_mmap(mmap: bool) -> DbConfig<1> {
DbConfig {
family_configs: [FamilyConfig {
......@@ -902,7 +929,7 @@ fn batch_get_basic(#[case] mmap: bool) -> Result<()> {
// Test batch_get with mixed existing and non-existing keys
let keys_to_fetch = vec![vec![10u8], vec![20u8], vec![200u8], vec![50u8], vec![255u8]];
let results = db.batch_get(0, &keys_to_fetch)?;
let results = batch_get_vec(&db, 0, &keys_to_fetch)?;
assert_eq!(results.len(), 5);
assert_eq!(results[0].as_deref(), Some(&[10u8][..]));
......@@ -933,7 +960,7 @@ fn batch_get_all_existing(#[case] mmap: bool) -> Result<()> {
// Fetch all existing keys
let keys_to_fetch: Vec<Vec<u8>> = (0..50u8).map(|i| vec![i]).collect();
let results = db.batch_get(0, &keys_to_fetch)?;
let results = batch_get_vec(&db, 0, &keys_to_fetch)?;
assert_eq!(results.len(), 50);
for (i, result) in results.iter().enumerate() {
......@@ -962,7 +989,7 @@ fn batch_get_none_existing(#[case] mmap: bool) -> Result<()> {
// Fetch non-existing keys
let keys_to_fetch: Vec<Vec<u8>> = (100..110u8).map(|i| vec![i]).collect();
let results = db.batch_get(0, &keys_to_fetch)?;
let results = batch_get_vec(&db, 0, &keys_to_fetch)?;
assert_eq!(results.len(), 10);
for result in results.iter() {
......@@ -989,7 +1016,7 @@ fn batch_get_empty(#[case] mmap: bool) -> Result<()> {
// Fetch with empty key list
let keys_to_fetch: Vec<Vec<u8>> = vec![];
let results = db.batch_get(0, &keys_to_fetch)?;
let results = batch_get_vec(&db, 0, &keys_to_fetch)?;
assert_eq!(results.len(), 0);
......@@ -1020,7 +1047,7 @@ fn batch_get_duplicate_keys(#[case] mmap: bool) -> Result<()> {
vec![99u8], // non-existing
vec![42u8],
];
let results = db.batch_get(0, &keys_to_fetch)?;
let results = batch_get_vec(&db, 0, &keys_to_fetch)?;
assert_eq!(results.len(), 5);
assert_eq!(results[0].as_deref(), Some(&[100u8][..]));
......@@ -1058,7 +1085,7 @@ fn batch_get_large_batch(#[case] mmap: bool) -> Result<()> {
.filter(|i| i % 10 == 0)
.map(|i| i.to_be_bytes().to_vec())
.collect();
let results = db.batch_get(0, &keys_to_fetch)?;
let results = batch_get_vec(&db, 0, &keys_to_fetch)?;
assert_eq!(results.len(), 100);
for (idx, i) in (0..1000u32).filter(|i| i % 10 == 0).enumerate() {
......@@ -1106,7 +1133,7 @@ fn batch_get_different_sizes(#[case] mmap: bool) -> Result<()> {
vec![5u8],
vec![6u8], // non-existing
];
let results = db.batch_get(0, &keys_to_fetch)?;
let results = batch_get_vec(&db, 0, &keys_to_fetch)?;
assert_eq!(results.len(), 7);
assert_eq!(results[0].as_deref(), Some(&[][..]));
......@@ -1156,7 +1183,7 @@ fn batch_get_across_families(#[case] mmap: bool) -> Result<()> {
// Fetch from each family separately
for family in 0..4usize {
let keys_to_fetch: Vec<Vec<u8>> = (0..20u8).map(|i| vec![i]).collect();
let results = db.batch_get(family, &keys_to_fetch)?;
let results = batch_get_vec(&db, family, &keys_to_fetch)?;
assert_eq!(results.len(), 20);
for (i, result) in results.iter().enumerate() {
......@@ -1176,8 +1203,8 @@ fn batch_get_across_families(#[case] mmap: bool) -> Result<()> {
// Verify family isolation - keys from family 0 shouldn't be in family 1
let keys_to_fetch: Vec<Vec<u8>> = (0..20u8).map(|i| vec![i]).collect();
let results_f0 = db.batch_get(0, &keys_to_fetch)?;
let results_f1 = db.batch_get(1, &keys_to_fetch)?;
let results_f0 = batch_get_vec(&db, 0, &keys_to_fetch)?;
let results_f1 = batch_get_vec(&db, 1, &keys_to_fetch)?;
// Same keys, but different values per family
assert_ne!(results_f0[0].as_deref(), results_f1[0].as_deref());
......@@ -1232,13 +1259,13 @@ fn batch_get_after_compaction(#[case] mmap: bool) -> Result<()> {
// Fetch before compaction
let keys_to_fetch: Vec<Vec<u8>> = (0..100u8).map(|i| vec![i]).collect();
let results_before = db.batch_get(0, &keys_to_fetch)?;
let results_before = batch_get_vec(&db, 0, &keys_to_fetch)?;
// Compact database using zstd to cover recompression with a non-default codec.
db.full_compact()?;
// Fetch after compaction
let results_after = db.batch_get(0, &keys_to_fetch)?;
let results_after = batch_get_vec(&db, 0, &keys_to_fetch)?;
// Results should be identical
assert_eq!(results_before.len(), results_after.len());
......@@ -1280,7 +1307,7 @@ fn batch_get_with_overwrites(#[case] mmap: bool) -> Result<()> {
// Fetch all keys
let keys_to_fetch: Vec<Vec<u8>> = (0..50u8).map(|i| vec![i]).collect();
let results = db.batch_get(0, &keys_to_fetch)?;
let results = batch_get_vec(&db, 0, &keys_to_fetch)?;
assert_eq!(results.len(), 50);
// First 25 should have new values
......@@ -1331,7 +1358,7 @@ fn batch_get_comparison_with_get(#[case] mmap: bool) -> Result<()> {
.collect();
// Get results using batch_get
let batch_results = db.batch_get(0, &keys_to_fetch)?;
let batch_results = batch_get_vec(&db, 0, &keys_to_fetch)?;
// Get results using individual get calls
let mut individual_results = Vec::new();
......@@ -1381,7 +1408,7 @@ fn batch_get_after_restore(#[case] mmap: bool) -> Result<()> {
let db = open_db::<16>(path, mmap)?;
let keys_to_fetch: Vec<Vec<u8>> = (0..100u8).step_by(5).map(|i| vec![i]).collect();
let results = db.batch_get(0, &keys_to_fetch)?;
let results = batch_get_vec(&db, 0, &keys_to_fetch)?;
assert_eq!(results.len(), 20);
for (idx, i) in (0..100u8).step_by(5).enumerate() {
......@@ -3362,7 +3389,7 @@ fn batch_get_large_batches(#[case] mmap: bool) -> Result<()> {
assert_eq!(keys.len(), batch_size);
#[cfg(feature = "stats")]
let before = db.statistics();
let results = db.batch_get(0, &keys)?;
let results = batch_get_vec(&db, 0, &keys)?;
assert_eq!(results.len(), batch_size);
#[cfg(feature = "stats")]
{
......@@ -3387,7 +3414,7 @@ fn batch_get_large_batches(#[case] mmap: bool) -> Result<()> {
// Duplicates of a key have the same hash, so they are adjacent and span several chunks.
let mut keys = vec![3u32.to_be_bytes().to_vec(); 3000];
keys.extend(vec![11u32.to_be_bytes().to_vec(); 600]);
let results = db.batch_get(0, &keys)?;
let results = batch_get_vec(&db, 0, &keys)?;
assert_eq!(results.len(), keys.len());
let (hits, deleted) = results.split_at(3000);
assert!(
......@@ -3399,3 +3426,127 @@ fn batch_get_large_batches(#[case] mmap: bool) -> Result<()> {
db.shutdown();
Ok(())
}
/// Opens a database with `KEYS` keys of 4 bytes over two commits: values of 8 bytes, overwrites of
/// every 7th key and tombstones for every 11th key.
fn open_callback_test_db(
path: &std::path::Path,
mmap: bool,
) -> Result<TurboPersistence<RayonParallelScheduler, 1>> {
let db = open_db::<1>(path, mmap)?;
let batch = db.write_batch()?;
for key in 0..CALLBACK_TEST_KEYS {
batch.put(
0,
key.to_be_bytes().to_vec(),
callback_test_value(key, 1).into(),
)?;
}
db.commit_write_batch(batch)?;
let batch = db.write_batch()?;
for key in 0..CALLBACK_TEST_KEYS {
if key.is_multiple_of(11) {
batch.delete(0, key.to_be_bytes().to_vec())?;
} else if key.is_multiple_of(7) {
batch.put(
0,
key.to_be_bytes().to_vec(),
callback_test_value(key, 2).into(),
)?;
}
}
db.commit_write_batch(batch)?;
Ok(db)
}
const CALLBACK_TEST_KEYS: u32 = 3_000;
fn callback_test_value(key: u32, version: u8) -> Vec<u8> {
let mut value = vec![version; 8];
value[..4].copy_from_slice(&key.to_le_bytes());
value
}
/// Batch sizes below and above the parallel threshold. Miri runs only the small one.
fn callback_test_batch_sizes() -> &'static [u32] {
if cfg!(miri) { &[100] } else { &[100, 2_500] }
}
/// Keys spread over the key space, with misses (keys >= `CALLBACK_TEST_KEYS`) and duplicates.
fn callback_test_keys(batch_size: u32) -> Vec<[u8; 4]> {
(0..batch_size)
.map(|i| {
(i.wrapping_mul(7919) % (CALLBACK_TEST_KEYS + CALLBACK_TEST_KEYS / 10)).to_be_bytes()
})
.chain([0u32, 0, 7, 7, CALLBACK_TEST_KEYS].map(u32::to_be_bytes))
.collect()
}
#[rstest]
#[case::mmap(true)]
#[case::file(false)]
fn batch_get_callback_once_per_index(#[case] mmap: bool) -> Result<()> {
use std::sync::atomic::{AtomicU32, Ordering};
let tempdir = tempfile::tempdir()?;
let db = open_callback_test_db(tempdir.path(), mmap)?;
for &batch_size in callback_test_batch_sizes() {
let keys = callback_test_keys(batch_size);
let calls: Vec<AtomicU32> = keys.iter().map(|_| AtomicU32::new(0)).collect();
let values: Vec<OnceLock<Option<ArcBytes>>> =
keys.iter().map(|_| OnceLock::new()).collect();
db.batch_get(0, &keys, |index, value| {
calls[index].fetch_add(1, Ordering::Relaxed);
let _ = values[index].set(value);
Ok(())
})?;
for (index, key) in keys.iter().enumerate() {
assert_eq!(
calls[index].load(Ordering::Relaxed),
1,
"index {index} of a batch of {} keys",
keys.len()
);
assert_eq!(
values[index].get().unwrap().as_deref(),
db.get(0, key)?.as_deref(),
"index {index} of a batch of {} keys",
keys.len()
);
}
}
db.shutdown();
Ok(())
}
#[rstest]
#[case::mmap(true)]
#[case::file(false)]
fn batch_get_callback_error_propagates(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let db = open_callback_test_db(tempdir.path(), mmap)?;
for &batch_size in callback_test_batch_sizes() {
let keys = callback_test_keys(batch_size);
// Fail on a found key and, separately, on a missing key (the last key is out of range).
let found = keys
.iter()
.position(|key| db.get(0, key).unwrap().is_some())
.unwrap();
let missing = keys.len() - 1;
for failing in [found, missing] {
let result = db.batch_get(0, &keys, |index, _| {
if index == failing {
anyhow::bail!("injected failure at index {index}");
}
Ok(())
});
let error = result.expect_err("the callback error must be returned");
assert!(
format!("{error:#}").contains(&format!("injected failure at index {failing}")),
"unexpected error: {error:#}"
);
}
}
db.shutdown();
Ok(())
}
//! Benchmarks sequential vs parallel decoding of a `batch_lookup_data` batch, used to pick
//! `PARALLEL_DECODE_THRESHOLD`.
//!
//! Only decoding is timed: the raw bytes are read from a real persisted database once during setup,
//! so disk I/O does not hide the scheduling overhead of the parallel path.
//!
//! Gated behind `TURBOPACK_BENCH_BATCH_LOOKUP` because the setup builds and persists a task graph.
//! Run with:
//!
//! ```bash
//! TURBOPACK_BENCH_BATCH_LOOKUP=1 cargo bench -p turbo-tasks-backend --bench mod -- batch_lookup
//! ```
use std::{
hint::black_box,
time::{Duration, Instant},
};
use anyhow::Result;
use criterion::{BenchmarkId, Criterion, Throughput};
use turbo_tasks::{TaskId, TurboTasks, Vc};
use turbo_tasks_backend::{
BackendOptions, BackingStorageOptions, GitVersionInfo, StorageMode, TurboTasksBackend,
private::{
ArcBytes, PARALLEL_DECODE_THRESHOLD, SpecificTaskDataCategory, batch_lookup_raw,
decode_task_storage_batch,
},
};
/// Batch sizes to measure. Must not exceed the number of persisted tasks.
const SIZES: &[usize] = &[2, 8, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192];
/// Leaves of the persisted tree. Together with the interior nodes this is more than the largest
/// batch size.
const LEAVES: u32 = 16384;
const BRANCHING: u32 = 4;
fn enabled() -> bool {
!matches!(
std::env::var("TURBOPACK_BENCH_BATCH_LOOKUP")
.ok()
.as_deref(),
None | Some("") | Some("no") | Some("false")
)
}
const VERSION_INFO: GitVersionInfo = GitVersionInfo {
describe: "bench-unversioned",
dirty: false,
};
const STORAGE_OPTIONS: BackingStorageOptions = BackingStorageOptions {
is_ci: false,
is_short_session: true,
skip_compaction: true,
};
#[turbo_tasks::function]
fn leaf(index: u32) -> Vc<u32> {
Vc::cell(index.wrapping_mul(1_000_003))
}
#[turbo_tasks::function]
async fn node(index: u32, span: u32) -> Result<Vc<u32>> {
if span <= 1 {
return Ok(leaf(index));
}
let child_span = span.div_ceil(BRANCHING);
let mut sum = 0u32;
let mut start = index;
while start < index + span {
let this_span = child_span.min(index + span - start);
sum = sum.wrapping_add(*node(start, this_span).await?);
start += this_span;
}
Ok(Vc::cell(sum))
}
#[turbo_tasks::function(operation, root)]
fn root() -> Vc<u32> {
node(0, LEAVES)
}
/// Builds and persists a task graph, then reads the raw bytes of every persisted task for both
/// categories.
fn setup(rt: &tokio::runtime::Runtime) -> (Vec<ArcBytes>, Vec<ArcBytes>, tempfile::TempDir) {
let parent = std::path::PathBuf::from(format!("{}/.cache", env!("CARGO_TARGET_TMPDIR")));
std::fs::create_dir_all(&parent).unwrap();
let dir = tempfile::Builder::new()
.prefix("batch-lookup-bench-")
.tempdir_in(&parent)
.unwrap();
rt.block_on(async {
// `TurboTasks::new` needs the runtime context.
let tt = TurboTasks::new(TurboTasksBackend::new(
BackendOptions {
storage_mode: Some(StorageMode::ReadWriteOnShutdown),
..Default::default()
},
turbo_tasks_backend::turbo_backing_storage(dir.path(), &VERSION_INFO, STORAGE_OPTIONS)
.unwrap()
.0,
));
turbo_tasks::run_once(tt.clone(), async move {
root().read_strongly_consistent().await?;
anyhow::Ok(())
})
.await
.unwrap();
tt.stop_and_wait().await;
});
let (meta, data) = rt.block_on(async {
let (storage, _) =
turbo_tasks_backend::turbo_backing_storage(dir.path(), &VERSION_INFO, STORAGE_OPTIONS)
.unwrap();
// Persistent task ids are allocated densely from 1. Over-fetch and drop the misses.
let task_ids: Vec<TaskId> = (1..=LEAVES * 4)
.map(|id| TaskId::try_from(id).unwrap())
.collect();
let fetch = |category| -> Vec<ArcBytes> {
batch_lookup_raw(&storage, &task_ids, category)
.unwrap()
.into_iter()
.flatten()
.collect()
};
(
fetch(SpecificTaskDataCategory::Meta),
fetch(SpecificTaskDataCategory::Data),
)
});
let max = *SIZES.iter().max().unwrap();
assert!(
meta.len() >= max && data.len() >= max,
"not enough persisted tasks: meta={}, data={}, need {max}",
meta.len(),
data.len()
);
(meta, data, dir)
}
/// Times `iters` decodes of `bytes[..size]` on a runtime worker thread, which is where
/// `batch_lookup_data` runs in practice. Only the decode call is timed, not dropping the decoded
/// storages (which in practice are moved into the in-memory storage).
fn time_decode(
rt: &tokio::runtime::Runtime,
bytes: &[ArcBytes],
size: usize,
category: SpecificTaskDataCategory,
threshold: usize,
iters: u64,
) -> Duration {
let input: Vec<Option<ArcBytes>> = bytes[..size].iter().cloned().map(Some).collect();
rt.block_on(async move {
tokio::spawn(async move {
let mut total = Duration::ZERO;
for _ in 0..iters {
let start = Instant::now();
let decoded =
decode_task_storage_batch(black_box(&input), category, threshold).unwrap();
total += start.elapsed();
drop(black_box(decoded));
}
total
})
.await
.unwrap()
})
}
pub fn batch_lookup(c: &mut Criterion) {
if !enabled() {
return;
}
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
let (meta, data, _dir) = setup(&rt);
for (name, category, bytes) in [
("meta", SpecificTaskDataCategory::Meta, &meta),
("data", SpecificTaskDataCategory::Data, &data),
] {
let mut group = c.benchmark_group(format!("turbo_tasks_backend_batch_lookup/{name}"));
group.measurement_time(Duration::from_secs(2));
group.warm_up_time(Duration::from_secs(1));
for &size in SIZES {
group.throughput(Throughput::Elements(size as u64));
for (mode, threshold) in [
("sequential", usize::MAX),
("parallel", 0),
("default", PARALLEL_DECODE_THRESHOLD),
] {
group.bench_with_input(BenchmarkId::new(mode, size), &size, |b, &size| {
b.iter_custom(|iters| time_decode(&rt, bytes, size, category, threshold, iters))
});
}
}
group.finish();
}
}
......@@ -3,7 +3,6 @@
use criterion::{Criterion, criterion_group, criterion_main};
pub(crate) mod batch_lookup;
pub(crate) mod cell_fan_out;
pub(crate) mod collectibles;
pub(crate) mod gc;
......@@ -16,7 +15,6 @@ criterion_group!(
name = turbo_tasks_backend_stress;
config = Criterion::default();
targets = stress::fibonacci, scope_stress::scope_stress, overhead::overhead, gc::gc,
cell_fan_out::cell_fan_out, state_fan_out::state_fan_out, collectibles::collectibles,
batch_lookup::batch_lookup
cell_fan_out::cell_fan_out, state_fan_out::state_fan_out, collectibles::collectibles
);
criterion_main!(turbo_tasks_backend_stress);
......@@ -10,7 +10,7 @@ mod update_collectible;
use std::{
fmt::{Debug, Display, Formatter},
ops::DerefMut,
sync::Arc,
sync::{Arc, OnceLock},
};
use anyhow::{Context, Result};
......@@ -266,13 +266,16 @@ impl<'e> ExecuteContext<'e> {
.with_context(|| format!("Failed to restore {category:?} for {task_id}"))
}
/// Batched [`Self::restore_task_data`]: one entry per id, `None` where the requested
/// category has no disk key.
/// Batched [`Self::restore_task_data`]. Calls `on_result` with the index of each id and its
/// storage, or `None` where the requested category has no disk key. See
/// [`TurboBackingStorage::batch_lookup_data`](crate::kv_backing_storage::TurboBackingStorage::batch_lookup_data)
/// for how `on_result` is called.
fn restore_task_data_batch(
&self,
task_ids: &[TaskId],
category: SpecificTaskDataCategory,
) -> Result<Vec<Option<TaskStorage>>> {
on_result: impl Fn(usize, Option<TaskStorage>) -> Result<()> + Sync,
) -> Result<()> {
debug_assert!(task_ids.len() > 1, "Use restore_task_data for single task");
debug_assert!(
self.backend.should_restore(),
......@@ -282,7 +285,7 @@ impl<'e> ExecuteContext<'e> {
restore_lookup_counts::record(true);
self.backend
.backing_storage
.batch_lookup_data(task_ids, category)
.batch_lookup_data(task_ids, category, on_result)
.with_context(|| {
format!(
"Failed to restore {category:?} for batch of {} tasks",
......@@ -507,8 +510,8 @@ impl<'e> ExecuteContext<'e> {
.map(|(id, category)| TaskRestoreEntry {
task_id: id,
category,
data_restore_result: None,
meta_restore_result: None,
data_restore_result: OnceLock::new(),
meta_restore_result: OnceLock::new(),
wait_data: false,
wait_meta: false,
task_type: None,
......@@ -572,64 +575,64 @@ impl<'e> ExecuteContext<'e> {
}
// --- Phase 1b: Batch I/O for tasks we claimed ---
// Data I/O
match tasks_to_restore_for_data.len() {
0 => {}
1 => {
let task_id = tasks_to_restore_for_data[0];
let idx = tasks_to_restore_for_data_indices[0];
tasks[idx].data_restore_result =
Some(self.restore_task_data(task_id, SpecificTaskDataCategory::Data));
}
_ => {
match self.restore_task_data_batch(
&tasks_to_restore_for_data,
SpecificTaskDataCategory::Data,
) {
Ok(data) => {
for (item, &idx) in data.into_iter().zip(&tasks_to_restore_for_data_indices)
{
tasks[idx].data_restore_result = Some(Ok(item));
}
}
Err(e) => {
// Batch failure: distribute the error to each affected task
let msg = format!("{e:?}");
for &idx in &tasks_to_restore_for_data_indices {
tasks[idx].data_restore_result =
Some(Err(anyhow::anyhow!("Batch data restore failed: {msg}")));
}
}
for (category, task_ids, indices) in [
(
SpecificTaskDataCategory::Data,
&tasks_to_restore_for_data,
&tasks_to_restore_for_data_indices,
),
(
SpecificTaskDataCategory::Meta,
&tasks_to_restore_for_meta,
&tasks_to_restore_for_meta_indices,
),
] {
match task_ids.len() {
0 => {}
1 => {
let result = self.restore_task_data(task_ids[0], category);
*tasks[indices[0]].restore_result_mut(category) = OnceLock::from(result);
}
}
}
// Meta I/O
match tasks_to_restore_for_meta.len() {
0 => {}
1 => {
let task_id = tasks_to_restore_for_meta[0];
let idx = tasks_to_restore_for_meta_indices[0];
tasks[idx].meta_restore_result =
Some(self.restore_task_data(task_id, SpecificTaskDataCategory::Meta));
}
_ => {
match self.restore_task_data_batch(
&tasks_to_restore_for_meta,
SpecificTaskDataCategory::Meta,
) {
Ok(data) => {
for (item, &idx) in data.into_iter().zip(&tasks_to_restore_for_meta_indices)
{
tasks[idx].meta_restore_result = Some(Ok(item));
_ => {
// Each result is stored in its entry as soon as it is decoded, possibly
// concurrently. Every index is reported at most once.
let batch_result = {
let tasks = &tasks;
self.restore_task_data_batch(task_ids, category, |i, storage| {
if tasks[indices[i]]
.restore_result(category)
.set(Ok(storage))
.is_err()
{
anyhow::bail!("task {} was restored twice", task_ids[i]);
}
Ok(())
})
};
match batch_result {
Ok(()) => {
for (&task_id, &idx) in task_ids.iter().zip(indices) {
let result = tasks[idx].restore_result_mut(category);
if result.get().is_none() {
// Unreachable: `batch_get` reports every index.
*result = OnceLock::from(Err(anyhow::anyhow!(
"Batch {category:?} restore returned no result for \
{task_id}"
)));
}
}
}
}
Err(e) => {
let msg = format!("{e:?}");
for &idx in &tasks_to_restore_for_meta_indices {
tasks[idx].meta_restore_result =
Some(Err(anyhow::anyhow!("Batch meta restore failed: {msg}")));
Err(e) => {
// Batch failure: distribute the error to each affected task, replacing
// any result stored before the failure.
let msg = format!("{e:?}");
for &idx in indices {
*tasks[idx].restore_result_mut(category) =
OnceLock::from(Err(anyhow::anyhow!(
"Batch {} restore failed: {msg}",
category_name(category.into())
)));
}
}
}
}
......@@ -646,7 +649,9 @@ impl<'e> ExecuteContext<'e> {
// Tasks that exist nowhere, reported once waiters are unblocked.
let mut missing_tasks: Vec<TaskId> = Vec::new();
for entry in &mut tasks {
if entry.data_restore_result.is_none() && entry.meta_restore_result.is_none() {
if entry.data_restore_result.get().is_none()
&& entry.meta_restore_result.get().is_none()
{
continue;
}
entry.self_restored = true;
......@@ -656,11 +661,11 @@ impl<'e> ExecuteContext<'e> {
self.task_lock_counter.acquire();
let mut task = self.backend.storage.access_entry_mut(task_id);
let has_error = matches!(entry.data_restore_result, Some(Err(_)))
|| matches!(entry.meta_restore_result, Some(Err(_)));
let has_error = matches!(entry.data_restore_result.get(), Some(Err(_)))
|| matches!(entry.meta_restore_result.get(), Some(Err(_)));
let missing = !has_error
&& (matches!(entry.data_restore_result, Some(Ok(None)))
|| matches!(entry.meta_restore_result, Some(Ok(None))));
&& (matches!(entry.data_restore_result.get(), Some(Ok(None)))
|| matches!(entry.meta_restore_result.get(), Some(Ok(None))));
if missing {
// No missing category may be published as restored, even if another category
// was present on disk or a peer is still restoring it. Clear every claim before
......@@ -681,8 +686,8 @@ impl<'e> ExecuteContext<'e> {
self.task_lock_counter.release();
continue;
} else {
let claimed_data = entry.data_restore_result.is_some();
let claimed_meta = entry.meta_restore_result.is_some();
let claimed_data = entry.data_restore_result.get().is_some();
let claimed_meta = entry.meta_restore_result.get().is_some();
if let Some(result) = entry.data_restore_result.take() {
match apply_restore_result(&mut task, result, SpecificTaskDataCategory::Data) {
Ok(()) => {
......@@ -833,12 +838,14 @@ fn category_name(category: TaskDataCategory) -> &'static str {
struct TaskRestoreEntry {
task_id: TaskId,
category: TaskDataCategory,
/// Result of restoring the data category (set in Phase 1b, consumed in Phase 1c). The inner
/// `Option` is `None` when the task was not present on disk.
data_restore_result: Option<Result<Option<TaskStorage>>>,
/// Result of restoring the meta category (set in Phase 1b, consumed in Phase 1c). The inner
/// `Option` is `None` when the task was not present on disk.
meta_restore_result: Option<Result<Option<TaskStorage>>>,
/// Result of restoring the data category (set in Phase 1b, possibly concurrently by a batched
/// read, and consumed in Phase 1c). The inner `Option` is `None` when the task was not present
/// on disk.
data_restore_result: OnceLock<Result<Option<TaskStorage>>>,
/// Result of restoring the meta category (set in Phase 1b, possibly concurrently by a batched
/// read, and consumed in Phase 1c). The inner `Option` is `None` when the task was not present
/// on disk.
meta_restore_result: OnceLock<Result<Option<TaskStorage>>>,
/// Another thread claimed the data restore; we must wait in Phase 3.
wait_data: bool,
/// Another thread claimed the meta restore; we must wait in Phase 3.
......@@ -851,6 +858,28 @@ struct TaskRestoreEntry {
failed: bool,
}
impl TaskRestoreEntry {
fn restore_result(
&self,
category: SpecificTaskDataCategory,
) -> &OnceLock<Result<Option<TaskStorage>>> {
match category {
SpecificTaskDataCategory::Data => &self.data_restore_result,
SpecificTaskDataCategory::Meta => &self.meta_restore_result,
}
}
fn restore_result_mut(
&mut self,
category: SpecificTaskDataCategory,
) -> &mut OnceLock<Result<Option<TaskStorage>>> {
match category {
SpecificTaskDataCategory::Data => &mut self.data_restore_result,
SpecificTaskDataCategory::Meta => &mut self.meta_restore_result,
}
}
}
/// Outcome of [`ExecuteContext::restore_task`].
struct RestoreOutcome {
/// A requested category was absent on disk; the task is invalid under MustExist/AllowMissing.
......
......@@ -92,8 +92,15 @@ impl TurboKeyValueDatabase {
self.db.get(key_space as usize, &key)
}
pub fn batch_get(&self, key_space: KeySpace, keys: &[&[u8]]) -> Result<Vec<Option<ArcBytes>>> {
self.db.batch_get(key_space as usize, keys)
/// Looks up many keys at once. See [`TurboPersistence::batch_get`] for how `on_result` is
/// called.
pub fn batch_get(
&self,
key_space: KeySpace,
keys: &[&[u8]],
on_result: impl Fn(usize, Option<ArcBytes>) -> Result<()> + Sync,
) -> Result<()> {
self.db.batch_get(key_space as usize, keys, on_result)
}
/// Looks up a key and returns all matching values.
......
......@@ -8,7 +8,7 @@ use std::{
use anyhow::{Context, Result};
use smallvec::SmallVec;
use turbo_bincode::{new_turbo_bincode_decoder, turbo_bincode_decode, turbo_bincode_encode};
use turbo_persistence::{ArcBytes, CommitStats};
use turbo_persistence::CommitStats;
use turbo_tasks::{
DynTaskInputs, RawVc, TaskId,
macro_helpers::NativeFunction,
......@@ -423,29 +423,35 @@ impl TurboBackingStorage {
Ok(Some(storage))
}
/// Batched [`Self::lookup_data`]: one entry per id, in order, `None` where the database had no
/// key. Decoding is parallelized for large batches, see [`PARALLEL_DECODE_THRESHOLD`].
/// Looks up and decodes the `category` of many tasks. Calls `on_result` with the index of the
/// task in `task_ids` and its decoded storage, or `None` if the category has no key on disk.
///
/// When this returns `Ok`, `on_result` was called exactly once for every index. The calls
/// happen in no particular order and may run concurrently on other threads, so decoding
/// runs in parallel for large batches. A read, decode or `on_result` error aborts the
/// batch.
pub(crate) fn batch_lookup_data(
&self,
task_ids: &[TaskId],
category: SpecificTaskDataCategory,
) -> Result<Vec<Option<TaskStorage>>> {
let bytes = self.batch_lookup_raw(task_ids, category)?;
decode_task_storage_batch(&bytes, category, PARALLEL_DECODE_THRESHOLD)
}
/// Reads the raw (still encoded) bytes of `category` for every id, in order.
pub(crate) fn batch_lookup_raw(
&self,
task_ids: &[TaskId],
category: SpecificTaskDataCategory,
) -> Result<Vec<Option<ArcBytes>>> {
on_result: impl Fn(usize, Option<TaskStorage>) -> Result<()> + Sync,
) -> Result<()> {
let inner = &*self.inner;
let int_keys: Vec<_> = task_ids.iter().map(|&id| IntKey::new(*id)).collect();
let keys = int_keys.iter().map(|k| k.as_ref()).collect::<Vec<_>>();
inner
.database
.batch_get(category.key_space(), &keys)
.batch_get(category.key_space(), &keys, |index, opt_bytes| {
let Some(bytes) = opt_bytes else {
return on_result(index, None);
};
let mut storage = TaskStorage::new();
let mut decoder = new_turbo_bincode_decoder(bytes.borrow());
storage
.decode(category, &mut decoder)
.map_err(|e| anyhow::anyhow!("Failed to decode {category:?}: {e:?}"))?;
on_result(index, Some(storage))
})
.with_context(|| {
format!(
"Looking up typed data for {} tasks from database failed",
......@@ -467,44 +473,6 @@ impl TurboBackingStorage {
}
}
/// The batch size from which `TurboBackingStorage::batch_lookup_data` decodes in parallel.
///
/// Below this, the overhead of distributing the work across threads outweighs the decoding cost.
/// On an 8 vCPU machine, the `batch_lookup` benchmark found Meta still slower in parallel at 1024
/// tasks, while both Meta and Data were consistently faster at 2048 tasks and beyond. Re-run with:
///
/// ```bash
/// TURBOPACK_BENCH_BATCH_LOOKUP=1 cargo bench -p turbo-tasks-backend --bench mod -- batch_lookup
/// ```
pub const PARALLEL_DECODE_THRESHOLD: usize = 2048;
/// Decodes a batch of raw [`TaskStorage`] bytes for `category`, preserving order and `None`s.
///
/// Decodes in parallel when `bytes.len() >= parallel_threshold`. Fails if any entry fails to
/// decode.
pub fn decode_task_storage_batch(
bytes: &[Option<ArcBytes>],
category: SpecificTaskDataCategory,
parallel_threshold: usize,
) -> Result<Vec<Option<TaskStorage>>> {
let decode = |opt_bytes: &Option<ArcBytes>| -> Result<Option<TaskStorage>> {
let Some(bytes) = opt_bytes else {
return Ok(None);
};
let mut storage = TaskStorage::new();
let mut decoder = new_turbo_bincode_decoder(Borrow::<[u8]>::borrow(bytes));
storage
.decode(category, &mut decoder)
.map_err(|e| anyhow::anyhow!("Failed to decode {category:?}: {e:?}"))?;
Ok(Some(storage))
};
if bytes.len() >= parallel_threshold {
parallel::map_collect::<_, _, Result<Vec<_>>>(bytes, decode)
} else {
bytes.iter().map(decode).collect()
}
}
fn get_next_free_task_id(batch: &TurboWriteBatch<'_>) -> Result<u32, anyhow::Error> {
Ok(
match batch.get(KeySpace::Infra, InfraKey::NextFreeTaskId.key().as_ref())? {
......@@ -663,64 +631,20 @@ mod tests {
.collect()
}
/// Sequential and parallel decoding must produce the same results, in order, with `None`s
/// preserved, and both must fail on malformed bytes.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_decode_task_storage_batch_sequential_matches_parallel() {
const SEQUENTIAL: usize = usize::MAX;
const PARALLEL: usize = 0;
for category in [
SpecificTaskDataCategory::Meta,
SpecificTaskDataCategory::Data,
] {
let expected: Vec<Option<Vec<u8>>> = (0..200u32)
.map(|i| (i % 7 != 3).then(|| encoded_task_storage(i * 10 + 1, category)))
.collect();
assert_ne!(expected[0], expected[1], "inputs must be distinct");
let to_bytes = || -> Vec<Option<ArcBytes>> {
expected
.iter()
.map(|bytes| {
bytes
.as_ref()
.map(|b| ArcBytes::from(b.clone().into_boxed_slice()))
})
.collect()
};
for threshold in [SEQUENTIAL, PARALLEL] {
let decoded = decode_task_storage_batch(&to_bytes(), category, threshold).unwrap();
assert_eq!(
reencode(&decoded, category),
expected,
"{category:?} threshold={threshold}"
);
assert!(
decode_task_storage_batch(&[], category, threshold)
.unwrap()
.is_empty()
);
let mut malformed = to_bytes();
malformed[150] = Some(ArcBytes::from(vec![0xff; 3].into_boxed_slice()));
assert!(
decode_task_storage_batch(&malformed, category, threshold).is_err(),
"{category:?} threshold={threshold} must fail on malformed bytes"
);
}
}
}
/// The production batch lookup preserves request order, duplicates and missing entries on
/// both sides of the parallel cutoff.
/// Reports every requested index exactly once, with request order, duplicates and missing
/// entries resolved correctly, on both sides of turbo-persistence's parallel `batch_get`
/// cutoff. A value that fails to decode fails the whole lookup.
// Default worker count like the other database tests here: under the WASI test host, file
// descriptors are per thread, so committing SST files from extra runtime workers fails.
#[tokio::test(flavor = "multi_thread")]
async fn test_batch_lookup_data_roundtrip_at_parallel_threshold() -> Result<()> {
/// turbo-persistence's `batch_get` runs in parallel above this many keys.
const PARALLEL_BATCH_GET_THRESHOLD: usize = 2048;
const MALFORMED_ID: u32 = 999_997;
let tempdir = test_temp_dir()?;
let db = TurboKeyValueDatabase::new(tempdir.path().to_path_buf(), TEST_STORAGE_OPTIONS)?;
let stored_ids: Vec<TaskId> = (1..=(PARALLEL_DECODE_THRESHOLD as u32 + 64))
let stored_ids: Vec<TaskId> = (1..=(PARALLEL_BATCH_GET_THRESHOLD as u32 + 64))
.map(|id| TaskId::try_from(id).unwrap())
.collect();
let batch = db.write_batch()?;
......@@ -737,6 +661,11 @@ mod tests {
WriteBuffer::Borrowed(&value),
)?;
}
batch.put(
category.key_space(),
WriteBuffer::Borrowed(IntKey::new(MALFORMED_ID).as_ref()),
WriteBuffer::Borrowed(&[0xff; 3]),
)?;
}
batch.commit()?;
let storage = TurboBackingStorage::new_in_memory(db);
......@@ -745,7 +674,10 @@ mod tests {
SpecificTaskDataCategory::Meta,
SpecificTaskDataCategory::Data,
] {
for len in [PARALLEL_DECODE_THRESHOLD - 1, PARALLEL_DECODE_THRESHOLD] {
for len in [
PARALLEL_BATCH_GET_THRESHOLD,
PARALLEL_BATCH_GET_THRESHOLD + 1,
] {
let mut requested = stored_ids[..len - 3].to_vec();
requested.reverse();
requested.insert(len / 2, TaskId::try_from(999_999).unwrap());
......@@ -760,12 +692,38 @@ mod tests {
.then(|| encoded_task_storage(**task_id * 10, category))
})
.collect();
let decoded = storage.batch_lookup_data(&requested, category)?;
let slots: Vec<std::sync::OnceLock<Option<TaskStorage>>> =
(0..len).map(|_| std::sync::OnceLock::new()).collect();
storage.batch_lookup_data(&requested, category, |index, storage| {
assert!(
slots[index].set(storage).is_ok(),
"{category:?} len={len}: index {index} reported twice"
);
Ok(())
})?;
let decoded: Vec<Option<TaskStorage>> = slots
.into_iter()
.enumerate()
.map(|(index, slot)| {
slot.into_inner().unwrap_or_else(|| {
panic!("{category:?} len={len}: index {index} never reported")
})
})
.collect();
assert_eq!(
reencode(&decoded, category),
expected,
"{category:?} len={len}"
);
let mut malformed = requested.clone();
malformed[len / 3] = TaskId::try_from(MALFORMED_ID).unwrap();
assert!(
storage
.batch_lookup_data(&malformed, category, |_, _| Ok(()))
.is_err(),
"{category:?} len={len} must fail on malformed bytes"
);
}
}
......
......@@ -105,26 +105,3 @@ pub fn compact_database(
db.shutdown();
Ok(())
}
/// Internals exposed for benchmarks only. Not a stable API.
#[doc(hidden)]
pub mod private {
use anyhow::Result;
pub use turbo_persistence::ArcBytes;
use turbo_tasks::TaskId;
use crate::kv_backing_storage::TurboBackingStorage;
pub use crate::{
backend::{SpecificTaskDataCategory, storage_schema::TaskStorage},
kv_backing_storage::{PARALLEL_DECODE_THRESHOLD, decode_task_storage_batch},
};
/// See `TurboBackingStorage::batch_lookup_raw`.
pub fn batch_lookup_raw(
storage: &TurboBackingStorage,
task_ids: &[TaskId],
category: SpecificTaskDataCategory,
) -> Result<Vec<Option<ArcBytes>>> {
storage.batch_lookup_raw(task_ids, category)
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment