Commit d8ef88ee authored by Luke Sandberg's avatar Luke Sandberg

streaming reads

parent ed631bbc
......@@ -35,6 +35,43 @@ export declare class ExternalObject<T> {
[K: symbol]: T
}
}
/**
* Called by worker after WASM instantiation to register a dispatch callback.
*
* The `ops` object must have these methods:
* - transform(programPtr, programLen, unresolvedMark, commentsProxy) → number
* - getDiag() → number
* - readBuf(ptr, len) → Buffer
* - writeBuf(ptr, data: Buffer) → void
* - alloc(size) → number
* - free(ptr, size) → number
*
* A TSFN is created targeting this worker's event loop. When Rust needs to
* call a WASM export, it posts to this TSFN, which runs the appropriate
* method on `ops` and sends the result back via a sync channel.
*/
export declare function wasmWorkerRegisterCallback(
runtimeId: number,
instanceId: number,
ops: object
): void
/**
* Called by worker when WASM hits a host function import.
* Runs the Func closure synchronously on the worker thread and returns the result.
*
* The worker provides a `memoryAccessor` object with methods to read/write WASM memory:
* - readBuf(ptr, len) → Buffer
* - writeBuf(ptr, data: Buffer) → void
* - alloc(size) → number
* - free(ptr, size) → number
*/
export declare function wasmWorkerDispatchHostFn(
runtimeId: number,
instanceId: number,
fnIndex: number,
args: Array<number>,
memoryAccessor: object
): unknown
export declare function registerWorkerScheduler(
creator: (arg: NapiWorkerCreation) => any,
terminator: (arg: NapiWorkerTermination) => any
......
......@@ -1206,7 +1206,7 @@ fn bench_static_sorted_file_lookup(c: &mut Criterion) {
},
|(key, hash)| {
let result = sst
.lookup::<_, false>(hash, &key, key_block_cache, value_block_cache)
.lookup::<_, _, _, false>(hash, &key, key_block_cache, value_block_cache)
.unwrap();
black_box(result)
},
......@@ -1225,7 +1225,7 @@ fn bench_static_sorted_file_lookup(c: &mut Criterion) {
|i| keys[i as usize % keys.len()],
|(key, hash)| {
let result = sst
.lookup::<_, false>(hash, &key, key_block_cache, value_block_cache)
.lookup::<_, _, _, false>(hash, &key, key_block_cache, value_block_cache)
.unwrap();
black_box(result)
},
......@@ -1251,7 +1251,7 @@ fn bench_static_sorted_file_lookup(c: &mut Criterion) {
},
|(key, hash)| {
let result = sst
.lookup::<_, false>(hash, &key, key_block_cache, value_block_cache)
.lookup::<_, _, _, false>(hash, &key, key_block_cache, value_block_cache)
.unwrap();
black_box(result)
},
......@@ -1284,7 +1284,7 @@ fn bench_static_sorted_file_lookup(c: &mut Criterion) {
},
|(key, hash)| {
let result = sst
.lookup::<_, false>(*hash, &key, key_block_cache, value_block_cache)
.lookup::<_, _, _, false>(*hash, &key, key_block_cache, value_block_cache)
.unwrap();
black_box(result)
},
......
......@@ -106,6 +106,49 @@ struct TrackedStats {
miss_global: std::sync::atomic::AtomicU64,
}
/// A compact bitset for tracking which batch-lookup cells have been resolved.
///
/// Uses `u64` words (1 bit per cell) rather than `Vec<bool>` (1 byte per cell) for an 8x
/// reduction in memory and better cache behaviour on large batches.
pub struct FoundBitset {
words: Box<[u64]>,
len: usize,
}
impl FoundBitset {
pub(crate) fn new(len: usize) -> Self {
let words = vec![0u64; len.div_ceil(64)].into_boxed_slice();
Self { words, len }
}
#[inline]
pub(crate) fn get(&self, index: usize) -> bool {
debug_assert!(index < self.len);
(self.words[index / 64] >> (index % 64)) & 1 == 1
}
#[inline]
pub(crate) fn set(&mut self, index: usize) {
debug_assert!(index < self.len);
self.words[index / 64] |= 1u64 << (index % 64);
}
/// Returns the number of bits that are NOT set (i.e. not yet found).
pub(crate) fn count_unset(&self) -> usize {
let set: usize = self.words.iter().map(|w| w.count_ones() as usize).sum();
self.len - set
}
pub(crate) fn len(&self) -> usize {
self.len
}
/// Iterates over all indices, yielding `(index, is_set)`.
pub(crate) fn iter(&self) -> impl Iterator<Item = bool> + '_ {
(0..self.len).map(|i| self.get(i))
}
}
/// TurboPersistence is a persistent key-value store. It is limited to a single writer at a time
/// using a single write batch. It allows for concurrent reads.
pub struct TurboPersistence<S: ParallelScheduler, const FAMILIES: usize> {
......@@ -1561,15 +1604,39 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
Ok(output)
}
/// Looks up multiple keys in batch and collects results into a `Vec`.
///
/// For large batches where memory pressure matters, prefer
/// [`batch_get_with`][Self::batch_get_with] which calls a callback per entry without
/// accumulating all decoded bytes simultaneously.
pub fn batch_get<K: QueryKey>(
&self,
family: usize,
keys: &[K],
) -> Result<Vec<Option<ArcBytes>>> {
let mut results = vec![None; keys.len()];
self.batch_get_with(family, keys, |index, opt_bytes| {
results[index] = opt_bytes.map(|b| ArcBytes::from(b.to_vec().into_boxed_slice()));
Ok(())
})?;
Ok(results)
}
/// Looks up multiple keys in batch, calling `callback(index, Option<&[u8]>)` for each entry
/// immediately after it is resolved rather than accumulating all results into a `Vec`.
///
/// This keeps at most one decompressed value block live at a time, significantly reducing
/// peak memory when the batch is large. The callback receives the 0-based key index and the
/// value bytes (`None` for not-found or deleted). Callback errors propagate immediately.
pub fn batch_get_with<K: QueryKey>(
&self,
family: usize,
keys: &[K],
mut callback: impl FnMut(usize, Option<&[u8]>) -> Result<()>,
) -> 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
panic!("only single valued tables can be queried with `batch_get'")
panic!("only single valued tables can be queried with `batch_get_with'")
}
let span = tracing::trace_span!(
"database batch read",
......@@ -1580,22 +1647,38 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
result_size = tracing::field::Empty
)
.entered();
let mut cells: Vec<(u64, usize, Option<LookupValue>)> = Vec::with_capacity(keys.len());
let mut empty_cells = keys.len();
let mut cells: Vec<(u64, usize)> = Vec::with_capacity(keys.len());
for (index, key) in keys.iter().enumerate() {
let hash = hash_key(key);
cells.push((hash, index, None));
cells.push((hash, index));
}
cells.sort_by_key(|(hash, _, _)| *hash);
cells.sort_by_key(|(hash, _)| *hash);
let mut found = FoundBitset::new(cells.len());
let inner = self.inner.read();
let mut not_found = 0;
let mut deleted = 0;
let mut result_size = 0;
let mut read_blob = |seq| self.read_blob(seq);
// Wrap the callback to track stats (deleted/result_size) for found keys.
// not_found is tracked separately in the post-loop over cells.
let mut stats_callback = |index: usize, opt_bytes: Option<&[u8]>| -> Result<()> {
if let Some(bytes) = opt_bytes {
result_size += bytes.len();
} else {
deleted += 1;
}
callback(index, opt_bytes)
};
for meta in inner.meta_files.iter().rev() {
let _result = meta.batch_lookup(
let (all_found, _result) = meta.batch_lookup_with(
family as u32,
keys,
&mut cells,
&mut empty_cells,
&cells,
&mut found,
&self.key_block_cache,
&self.value_block_cache,
&mut read_blob,
&mut stats_callback,
)?;
#[cfg(feature = "stats")]
......@@ -1627,49 +1710,25 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
}
}
if empty_cells == 0 {
if all_found {
break;
}
}
let mut deleted = 0;
let mut not_found = 0;
let mut result_size = 0;
let mut results = vec![None; keys.len()];
for (hash, index, result) in cells {
if let Some(result) = result {
inner.accessed_key_hashes[family].insert(hash);
let result = match result {
LookupValue::Deleted => {
#[cfg(feature = "stats")]
self.stats.hits_deleted.fetch_add(1, Ordering::Relaxed);
deleted += 1;
None
}
LookupValue::Slice { value } => {
#[cfg(feature = "stats")]
self.stats.hits_small.fetch_add(1, Ordering::Relaxed);
result_size += value.len();
Some(value)
}
LookupValue::Blob { sequence_number } => {
#[cfg(feature = "stats")]
self.stats.hits_blob.fetch_add(1, Ordering::Relaxed);
let blob = self.read_blob(sequence_number)?;
result_size += blob.len();
Some(blob)
}
};
results[index] = result;
// Record accessed hashes for found keys, and fire callback for not-found keys.
for ((hash, index), is_found) in cells.iter().zip(found.iter()) {
if is_found {
inner.accessed_key_hashes[family].insert(*hash);
} else {
#[cfg(feature = "stats")]
self.stats.miss_global.fetch_add(1, Ordering::Relaxed);
not_found += 1;
callback(*index, None)?;
}
}
span.record("not_found", not_found);
span.record("deleted", deleted);
span.record("result_size", result_size);
Ok(results)
Ok(())
}
/// Returns database statistics.
......
......@@ -14,10 +14,13 @@ use smallvec::SmallVec;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Ref, big_endian as be};
use crate::{
QueryKey,
ArcBytes, QueryKey,
db::FoundBitset,
lookup_entry::LookupValue,
mmap_helper::advise_mmap_for_persistence,
static_sorted_file::{BlockCache, SstLookupResult, StaticSortedFile, StaticSortedFileMetaData},
static_sorted_file::{
BlockCache, LayeredBlockCache, SstLookupResult, StaticSortedFile, StaticSortedFileMetaData,
},
};
bitfield! {
......@@ -459,7 +462,7 @@ impl MetaFile {
continue;
}
let result = entry.sst(self)?.lookup::<K, FIND_ALL>(
let result = entry.sst(self)?.lookup::<K, _, _, FIND_ALL>(
key_hash,
key,
key_block_cache,
......@@ -498,33 +501,60 @@ impl MetaFile {
Ok(miss_result)
}
pub fn batch_lookup<K: QueryKey>(
/// Looks up multiple keys in batch, calling `callback(key_index, Option<&[u8]>)` for each
/// found key immediately after resolution. This avoids keeping every decompressed value block
/// alive across all SST file iterations.
///
/// `cells` is `(hash, key_index)` sorted by hash. `found` is a parallel bitset — bit `i`
/// is set once `cells[i]` has been resolved (either by this call or a prior one on the same
/// batch). On return, bits are set for every cell resolved by this call.
///
/// Returns `true` if all cells are now resolved (caller can stop iterating meta files).
/// `read_blob` is called to obtain the bytes for large blob values.
pub fn batch_lookup_with<K: QueryKey>(
&self,
key_family: u32,
keys: &[K],
cells: &mut [(u64, usize, Option<LookupValue>)],
empty_cells: &mut usize,
cells: &[(u64, usize)],
found: &mut FoundBitset,
key_block_cache: &BlockCache,
value_block_cache: &BlockCache,
) -> Result<MetaBatchLookupResult> {
read_blob: &mut impl FnMut(u32) -> Result<ArcBytes>,
callback: &mut impl FnMut(usize, Option<&[u8]>) -> Result<()>,
) -> Result<(bool, MetaBatchLookupResult)> {
debug_assert_eq!(
cells.len(),
found.len(),
"cells and found must have the same length"
);
if key_family != self.family {
#[cfg(feature = "stats")]
return Ok(MetaBatchLookupResult {
return Ok((
false,
MetaBatchLookupResult {
family_miss: true,
..Default::default()
});
},
));
#[cfg(not(feature = "stats"))]
return Ok(MetaBatchLookupResult {});
return Ok((false, MetaBatchLookupResult {}));
}
debug_assert!(
cells.is_sorted_by_key(|(hash, _, _)| *hash),
cells.is_sorted_by_key(|(hash, _)| *hash),
"Cells must be sorted by key hash"
);
#[allow(unused_mut, reason = "It's used when stats are enabled")]
let mut lookup_result = MetaBatchLookupResult::default();
let mut empty_cells = found.count_unset();
// Local single-entry caches layered on top of the global block caches.
// Sequential keys in a batch often hit the same key or value block; keeping
// the most recently used block locally avoids re-reading it if the global
// cache evicts it under concurrent pressure.
let mut local_key_cache = LayeredBlockCache::new(key_block_cache);
let mut local_value_cache = LayeredBlockCache::new(value_block_cache);
for entry in self.entries.iter().rev() {
let start_index = cells
.binary_search_by(|(hash, _, _)| hash.cmp(&entry.min_hash).then(Ordering::Greater))
.binary_search_by(|(hash, _)| hash.cmp(&entry.min_hash).then(Ordering::Greater))
.err()
.unwrap();
if start_index >= cells.len() {
......@@ -535,7 +565,7 @@ impl MetaFile {
continue;
}
let end_index = cells
.binary_search_by(|(hash, _, _)| hash.cmp(&entry.max_hash).then(Ordering::Less))
.binary_search_by(|(hash, _)| hash.cmp(&entry.max_hash).then(Ordering::Less))
.err()
.unwrap()
.checked_sub(1);
......@@ -553,12 +583,13 @@ impl MetaFile {
}
continue;
}
for (hash, index, result) in &mut cells[start_index..=end_index] {
for (cell_pos, (hash, index)) in cells[start_index..=end_index].iter().enumerate() {
let cell_pos = start_index + cell_pos;
debug_assert!(
*hash >= entry.min_hash && *hash <= entry.max_hash,
"Key hash out of range"
);
if result.is_some() {
if found.get(cell_pos) {
continue;
}
if !entry.amqf.contains_fingerprint(*hash) {
......@@ -568,11 +599,11 @@ impl MetaFile {
}
continue;
}
let sst_result = entry.sst(self)?.lookup::<_, false>(
let sst_result = entry.sst(self)?.lookup::<_, _, _, false>(
*hash,
&keys[*index],
key_block_cache,
value_block_cache,
&mut local_key_cache,
&mut local_value_cache,
)?;
if let SstLookupResult::Found(mut values) = sst_result {
// find_all=false guarantees exactly one result
......@@ -580,14 +611,39 @@ impl MetaFile {
let Some(value) = values.pop() else {
unreachable!()
};
*result = Some(value);
*empty_cells -= 1;
// Resolve and callback immediately — the ArcBytes is dropped before the
// next iteration so we never hold more than one decompressed block at a time.
let opt_bytes: Option<&[u8]> = match &value {
LookupValue::Deleted => None,
LookupValue::Slice { value } => Some(value),
LookupValue::Blob { sequence_number } => {
// Blob resolution: read_blob is called inline. The blob ArcBytes
// must outlive the callback call, so we bind it here.
let blob = read_blob(*sequence_number)?;
found.set(cell_pos);
empty_cells -= 1;
#[cfg(feature = "stats")]
{
lookup_result.hits += 1;
}
callback(*index, Some(&*blob))?;
// blob dropped here
if empty_cells == 0 {
return Ok((true, lookup_result));
}
continue;
}
};
found.set(cell_pos);
empty_cells -= 1;
#[cfg(feature = "stats")]
{
lookup_result.hits += 1;
}
if *empty_cells == 0 {
return Ok(lookup_result);
callback(*index, opt_bytes)?;
// value (ArcBytes) dropped here
if empty_cells == 0 {
return Ok((true, lookup_result));
}
} else {
#[cfg(feature = "stats")]
......@@ -597,6 +653,6 @@ impl MetaFile {
}
}
}
Ok(lookup_result)
Ok((false, lookup_result))
}
}
......@@ -96,19 +96,30 @@ pub type BlockCache =
/// blocks). Generic over the byte type so it works for both the lookup path
/// (`ArcBytes` with `BlockCache`) and the iteration path (`RcBytes` with a
/// single-entry `Option` cache).
trait ValueBlockCache<B: SharedBytes> {
pub trait ValueBlockCache<B: SharedBytes> {
fn get_or_read(
self,
&mut self,
mmap: &B::MmapHandle,
meta: &StaticSortedFileMetaData,
block_index: u16,
) -> Result<B>;
}
impl<B: SharedBytes, V: ValueBlockCache<B>> ValueBlockCache<B> for &mut V {
fn get_or_read(
&mut self,
mmap: &B::MmapHandle,
meta: &StaticSortedFileMetaData,
block_index: u16,
) -> Result<B> {
(**self).get_or_read(mmap, meta, block_index)
}
}
/// Lookup-path: concurrent `BlockCache`.
impl ValueBlockCache<ArcBytes> for &BlockCache {
fn get_or_read(
self,
&mut self,
mmap: &Arc<Mmap>,
meta: &StaticSortedFileMetaData,
block_index: u16,
......@@ -130,7 +141,7 @@ impl ValueBlockCache<ArcBytes> for &BlockCache {
/// Iteration-path: lightweight single-entry cache for sequential reads.
impl ValueBlockCache<RcBytes> for &mut Option<(u16, RcBytes)> {
fn get_or_read(
self,
&mut self,
mmap: &Rc<Mmap>,
meta: &StaticSortedFileMetaData,
block_index: u16,
......@@ -141,7 +152,52 @@ impl ValueBlockCache<RcBytes> for &mut Option<(u16, RcBytes)> {
return Ok(block.clone());
}
let block: RcBytes = read_block_generic(mmap, meta, block_index)?;
*self = Some((block_index, block.clone()));
**self = Some((block_index, block.clone()));
Ok(block)
}
}
/// Batch-lookup-path: layered cache that checks a local single-entry cache first, then
/// falls back to the global `BlockCache`. Used in `batch_lookup_with` to prevent
/// concurrent eviction of just-read blocks between consecutive key lookups in a batch.
/// Sequential keys in the same batch often hit the same key or value block, so keeping
/// the most recently read block locally avoids redundant decompression.
pub struct LayeredBlockCache<'a> {
/// `(sequence_number, block_index)` — must include sequence number since the same block
/// index can refer to different data in different SST files.
local: Option<((u32, u16), ArcBytes)>,
global: &'a BlockCache,
}
impl<'a> LayeredBlockCache<'a> {
pub fn new(global: &'a BlockCache) -> Self {
Self {
local: None,
global,
}
}
}
impl ValueBlockCache<ArcBytes> for &mut LayeredBlockCache<'_> {
fn get_or_read(
&mut self,
mmap: &Arc<Mmap>,
meta: &StaticSortedFileMetaData,
block_index: u16,
) -> Result<ArcBytes> {
let key = (meta.sequence_number, block_index);
if let Some((cached_key, block)) = self.local.as_ref()
&& *cached_key == key
{
return Ok(block.clone());
}
let block = <&BlockCache as ValueBlockCache<ArcBytes>>::get_or_read(
&mut self.global,
mmap,
meta,
block_index,
)?;
self.local = Some((key, block.clone()));
Ok(block)
}
}
......@@ -204,41 +260,46 @@ impl StaticSortedFile {
/// If `FIND_ALL` is false, returns after finding the first match.
/// If `FIND_ALL` is true, returns all entries with the same key (useful for
/// keyspaces where keys are hashes and collisions are possible).
pub fn lookup<K: QueryKey, const FIND_ALL: bool>(
pub fn lookup<
K: QueryKey,
KC: ValueBlockCache<ArcBytes>,
VC: ValueBlockCache<ArcBytes>,
const FIND_ALL: bool,
>(
&self,
key_hash: u64,
key: &K,
key_block_cache: &BlockCache,
value_block_cache: &BlockCache,
mut key_block_cache: KC,
mut value_block_cache: VC,
) -> Result<SstLookupResult> {
// There is exactly one index block per file (always the last block).
// Read it first, then dispatch directly to the key block it points to.
let index_block_index = self.meta.block_count - 1;
let index_block = self.get_key_block(index_block_index, key_block_cache)?;
let index_block = self.get_key_block(index_block_index, &mut key_block_cache)?;
let key_block_index = self.lookup_index_block(&index_block, key_hash)?;
let key_block_arc = self.get_key_block(key_block_index, key_block_cache)?;
let key_block_arc = self.get_key_block(key_block_index, &mut key_block_cache)?;
let block_type = be::read_u8(&key_block_arc);
match block_type {
BLOCK_TYPE_KEY_WITH_HASH | BLOCK_TYPE_KEY_NO_HASH => {
let has_hash = block_type == BLOCK_TYPE_KEY_WITH_HASH;
self.lookup_key_block::<K, FIND_ALL>(
self.lookup_key_block::<K, _, FIND_ALL>(
key_block_arc,
key_hash,
key,
has_hash,
value_block_cache,
&mut value_block_cache,
)
}
BLOCK_TYPE_FIXED_KEY_WITH_HASH | BLOCK_TYPE_FIXED_KEY_NO_HASH => {
let has_hash = block_type == BLOCK_TYPE_FIXED_KEY_WITH_HASH;
self.lookup_fixed_key_block::<K, FIND_ALL>(
self.lookup_fixed_key_block::<K, _, FIND_ALL>(
key_block_arc,
key_hash,
key,
has_hash,
value_block_cache,
&mut value_block_cache,
)
}
_ => {
......@@ -273,13 +334,13 @@ impl StaticSortedFile {
///
/// If `FIND_ALL` is false, returns after finding the first match.
/// If `FIND_ALL` is true, collects all entries with the same key.
fn lookup_key_block<K: QueryKey, const FIND_ALL: bool>(
fn lookup_key_block<K: QueryKey, VC: ValueBlockCache<ArcBytes>, const FIND_ALL: bool>(
&self,
block: ArcBytes,
key_hash: u64,
key: &K,
has_hash: bool,
value_block_cache: &BlockCache,
value_block_cache: &mut VC,
) -> Result<SstLookupResult> {
let hash_len: u8 = if has_hash { 8 } else { 0 };
ensure!(block.len() >= 4, "key block too short");
......@@ -292,7 +353,7 @@ impl StaticSortedFile {
let offsets = &data[..entry_count * 4];
let entries = &data[entry_count * 4..];
self.lookup_block_inner::<K, FIND_ALL>(
self.lookup_block_inner::<K, VC, FIND_ALL>(
&block,
entry_count,
key_hash,
......@@ -306,13 +367,13 @@ impl StaticSortedFile {
///
/// Fixed-size key blocks store entries at predictable offsets (no offset table),
/// enabling direct indexing during binary search.
fn lookup_fixed_key_block<K: QueryKey, const FIND_ALL: bool>(
fn lookup_fixed_key_block<K: QueryKey, VC: ValueBlockCache<ArcBytes>, const FIND_ALL: bool>(
&self,
block: ArcBytes,
key_hash: u64,
key: &K,
has_hash: bool,
value_block_cache: &BlockCache,
value_block_cache: &mut VC,
) -> Result<SstLookupResult> {
let hash_len: u8 = if has_hash { 8 } else { 0 };
ensure!(block.len() >= 6, "fixed key block too short");
......@@ -327,7 +388,7 @@ impl StaticSortedFile {
"fixed key block for {entry_count} entries must is the wrong size"
);
self.lookup_block_inner::<K, FIND_ALL>(
self.lookup_block_inner::<K, VC, FIND_ALL>(
&block,
entry_count,
key_hash,
......@@ -345,13 +406,13 @@ impl StaticSortedFile {
///
/// The `get_entry` closure abstracts over the difference between variable-size
/// key blocks (offset table lookup) and fixed-size key blocks (stride-based indexing).
fn lookup_block_inner<'a, K: QueryKey, const FIND_ALL: bool>(
fn lookup_block_inner<'a, K: QueryKey, VC: ValueBlockCache<ArcBytes>, const FIND_ALL: bool>(
&self,
block: &ArcBytes,
entry_count: usize,
key_hash: u64,
key: &K,
value_block_cache: &BlockCache,
value_block_cache: &mut VC,
get_entry: impl Fn(usize) -> Result<GetKeyEntryResult<'a>>,
) -> Result<SstLookupResult> {
let mut l = 0;
......@@ -426,12 +487,12 @@ impl StaticSortedFile {
}
/// Handles a key match by looking up the value.
fn handle_key_match(
fn handle_key_match<VC: ValueBlockCache<ArcBytes>>(
&self,
ty: u8,
val: &[u8],
key_block_arc: &ArcBytes,
value_block_cache: &BlockCache,
value_block_cache: &mut VC,
) -> Result<LookupValue> {
handle_key_match_generic(
&self.mmap,
......@@ -444,30 +505,12 @@ impl StaticSortedFile {
}
/// Gets a key block from the cache or reads it from the file.
fn get_key_block(
fn get_key_block<KC: ValueBlockCache<ArcBytes>>(
&self,
block: u16,
key_block_cache: &BlockCache,
key_block_cache: &mut KC,
) -> Result<ArcBytes, anyhow::Error> {
Ok(
match key_block_cache.get_value_or_guard(&(self.meta.sequence_number, block), None) {
GuardResult::Value(block) => block,
GuardResult::Guard(guard) => {
let block = self.read_block(block)?;
let _ = guard.insert(block.clone());
block
}
GuardResult::Timeout => unreachable!(),
},
)
}
/// Reads a block from the file, decompressing if needed, and verifies its checksum.
///
/// The checksum is verified on the raw on-disk data **before** decompression, so
/// corruption is caught before passing data to LZ4.
fn read_block(&self, block_index: u16) -> Result<ArcBytes> {
read_block_generic(&self.mmap, &self.meta, block_index)
key_block_cache.get_or_read(&self.mmap, &self.meta, block)
}
}
......@@ -605,7 +648,7 @@ fn handle_key_match_generic<B: SharedBytes>(
ty: u8,
val: &[u8],
key_block: &B,
reader: impl ValueBlockCache<B>,
mut reader: impl ValueBlockCache<B>,
) -> Result<LookupValue<B>> {
Ok(match ty {
KEY_BLOCK_ENTRY_TYPE_SMALL => {
......
......@@ -1381,7 +1381,7 @@ mod tests {
kc: &TestBlockCache,
vc: &TestBlockCache,
) -> Result<()> {
let result = sst.lookup::<_, false>(entry.hash, &entry.key, kc, vc)?;
let result = sst.lookup::<_, _, _, false>(entry.hash, &entry.key, kc, vc)?;
match (&entry.value_kind, result) {
(_, SstLookupResult::Found(values))
if values.len() == 1 && matches!(values[0], LookupValue::Slice { .. }) =>
......@@ -1690,8 +1690,8 @@ mod tests {
let vc = make_cache();
for entry in &entries {
let r1 = sst1.lookup::<_, false>(entry.hash, &entry.key, &kc, &vc)?;
let r2 = sst2.lookup::<_, false>(entry.hash, &entry.key, &kc, &vc)?;
let r1 = sst1.lookup::<_, _, _, false>(entry.hash, &entry.key, &kc, &vc)?;
let r2 = sst2.lookup::<_, _, _, false>(entry.hash, &entry.key, &kc, &vc)?;
match (&r1, &r2) {
(SstLookupResult::Found(v1), SstLookupResult::Found(v2))
if v1.len() == 1 && v2.len() == 1 =>
......@@ -1816,7 +1816,7 @@ mod tests {
let sst = open_sst(dir, seq, meta).unwrap();
let kc = make_cache();
let vc = make_cache();
match sst.lookup::<_, false>(entries[0].hash, &entries[0].key, &kc, &vc) {
match sst.lookup::<_, _, _, false>(entries[0].hash, &entries[0].key, &kc, &vc) {
Err(err) => {
let msg = format!("{err}");
assert!(
......
......@@ -14,6 +14,7 @@ use std::{
use bincode::{Decode, Encode};
use tracing::trace_span;
use turbo_bincode::new_turbo_bincode_decoder;
use turbo_tasks::{
CellId, FxIndexMap, TaskExecutionReason, TaskId, TaskPriority, TurboTasksBackendApi,
TurboTasksCallApi, TypedSharedReference, backend::CachedTaskType,
......@@ -31,6 +32,11 @@ use crate::{
data::{ActivenessState, CollectibleRef, Dirtyness, InProgressState, TransientTask},
};
struct TaskRestoreEntry {
task_id: TaskId,
category: TaskDataCategory,
}
pub trait Operation: Encode + Decode<()> + Default + TryFrom<AnyOperation, Error = ()> {
fn execute(self, ctx: &mut impl ExecuteContext<'_>);
}
......@@ -202,45 +208,6 @@ impl<'e, B: BackingStorage> ExecuteContextImpl<'e, B> {
}
}
fn restore_task_data_batch(
&self,
task_ids: &[TaskId],
category: SpecificTaskDataCategory,
reason: &'static str,
) -> Option<Vec<TaskStorage>> {
debug_assert!(
task_ids.len() > 1,
"Use restore_task_data_typed for single task"
);
if !self.should_check_backing_storage() {
// If we don't need to restore, we return None
return None;
}
let _span = trace_span!(
"restore_task_data_batch",
reason,
category = ?category,
keys = task_ids.len(),
)
.entered();
let result = self
.backend
.backing_storage
.batch_lookup_data(task_ids, category);
match result {
Ok(result) => Some(result),
Err(e) => {
panic!(
"Failed to restore task data (corrupted database or bug): {:?}",
e.context(format!(
"{category:?} for batch of {} tasks",
task_ids.len()
))
)
}
}
}
fn prepare_tasks_with_callback(
&mut self,
task_ids: impl IntoIterator<Item = (TaskId, TaskDataCategory)>,
......@@ -265,7 +232,7 @@ impl<'e, B: BackingStorage> ExecuteContextImpl<'e, B> {
let mut data_count = 0;
let mut meta_count = 0;
let mut all_count = 0;
let mut tasks = task_ids
let tasks = task_ids
.into_iter()
.filter(|&(id, category)| {
if id.is_transient() {
......@@ -288,18 +255,22 @@ impl<'e, B: BackingStorage> ExecuteContextImpl<'e, B> {
TaskDataCategory::Meta => meta_count += 1,
TaskDataCategory::All => all_count += 1,
})
.map(|(id, category)| (id, category, None, None))
.map(|(id, category)| TaskRestoreEntry {
task_id: id,
category,
})
.collect::<Vec<_>>();
data_count += all_count;
meta_count += all_count;
span.record("requested_data", data_count);
span.record("requested_meta", meta_count);
let mut tasks_to_restore_for_data = Vec::with_capacity(data_count);
let mut tasks_to_restore_for_data_indicies = Vec::with_capacity(data_count);
let mut tasks_to_restore_for_meta = Vec::with_capacity(meta_count);
let mut tasks_to_restore_for_meta_indicies = Vec::with_capacity(meta_count);
for (i, &(task_id, category, _, _)) in tasks.iter().enumerate() {
let mut tasks_to_restore_for_data: Vec<TaskId> = Vec::with_capacity(data_count);
let mut tasks_to_restore_for_data_indices: Vec<usize> = Vec::with_capacity(data_count);
let mut tasks_to_restore_for_meta: Vec<TaskId> = Vec::with_capacity(meta_count);
let mut tasks_to_restore_for_meta_indices: Vec<usize> = Vec::with_capacity(meta_count);
for (i, entry) in tasks.iter().enumerate() {
let (task_id, category) = (entry.task_id, entry.category);
self.task_lock_counter.acquire();
let task = self.backend.storage.access_mut(task_id);
......@@ -308,14 +279,14 @@ impl<'e, B: BackingStorage> ExecuteContextImpl<'e, B> {
&& !task.flags.is_restored(TaskDataCategory::Data)
{
tasks_to_restore_for_data.push(task_id);
tasks_to_restore_for_data_indicies.push(i);
tasks_to_restore_for_data_indices.push(i);
ready = false;
}
if matches!(category, TaskDataCategory::Meta | TaskDataCategory::All)
&& !task.flags.is_restored(TaskDataCategory::Meta)
{
tasks_to_restore_for_meta.push(task_id);
tasks_to_restore_for_meta_indicies.push(i);
tasks_to_restore_for_meta_indices.push(i);
ready = false;
}
self.task_lock_counter.release();
......@@ -327,93 +298,206 @@ impl<'e, B: BackingStorage> ExecuteContextImpl<'e, B> {
return;
}
match tasks_to_restore_for_data.len() {
0 => {}
1 => {
let task_id = tasks_to_restore_for_data[0];
let data = self.restore_task_data(task_id, SpecificTaskDataCategory::Data);
let idx = tasks_to_restore_for_data_indicies[0];
tasks[idx].2 = Some(data);
}
_ => {
if let Some(data) = self.restore_task_data_batch(
// Restore data and meta batches.
// Each decoded TaskStorage is written into backend.storage immediately inside the
// batch_lookup_data callback, and prepared_task_callback is called as soon as
// task.flags.is_restored(entry.category) becomes true (i.e. all required categories
// for that entry are satisfied). The guard is passed directly to the callback while
// still held — no second pass needed.
let mut races_data = 0u32;
let mut races_meta = 0u32;
self.restore_batch(
&tasks,
&tasks_to_restore_for_data,
&tasks_to_restore_for_data_indices,
SpecificTaskDataCategory::Data,
reason,
&mut races_data,
&mut races_meta,
&mut prepared_task_callback,
);
self.restore_batch(
&tasks,
&tasks_to_restore_for_meta,
&tasks_to_restore_for_meta_indices,
SpecificTaskDataCategory::Meta,
reason,
&mut races_data,
&mut races_meta,
&mut prepared_task_callback,
);
span.record("races_data", races_data);
span.record("races_meta", races_meta);
}
/// Decodes a batch of task data from backing storage, writing each `TaskStorage` immediately
/// into `backend.storage` as it arrives so it can be freed before the next one is decoded.
///
/// Calls `prepared_task_callback` immediately (while the task write guard is still held)
/// as soon as `task.flags.is_restored(entry.category)` becomes true — i.e. all categories
/// required by the entry are satisfied. For `All`-category entries this means the callback
/// fires in the meta batch (after both data and meta have been set).
fn restore_batch(
&mut self,
tasks: &[TaskRestoreEntry],
task_ids: &[TaskId],
task_indices: &[usize],
category: SpecificTaskDataCategory,
reason: &'static str,
races_data: &mut u32,
races_meta: &mut u32,
prepared_task_callback: &mut impl FnMut(
&mut Self,
TaskId,
TaskDataCategory,
StorageWriteGuard<'e>,
),
) {
data.into_iter()
.zip(tasks_to_restore_for_data_indicies)
.for_each(|(item, idx)| {
tasks[idx].2 = Some(item);
if task_ids.is_empty() {
return;
}
let _span = trace_span!(
"restore_task_data_batch",
reason,
category = ?category,
keys = task_ids.len(),
)
.entered();
if self.backend.should_restore() && self.backend.local_is_partial {
let result = self.backend.backing_storage.batch_lookup_data(
task_ids,
category,
&mut |index, opt_bytes| {
// opt_bytes is Some(&[u8]) when found, None when not in DB.
// The byte slice (and any underlying decompressed block) is dropped at the
// end of this closure, before the next key is fetched.
let task_index = task_indices[index];
let entry = &tasks[task_index];
self.task_lock_counter.acquire();
let mut task = self.backend.storage.access_mut(entry.task_id);
match category {
SpecificTaskDataCategory::Data => {
if !task.flags.is_restored(TaskDataCategory::Data) {
if let Some(bytes) = opt_bytes {
let mut decoder = new_turbo_bincode_decoder(bytes);
task.decode(SpecificTaskDataCategory::Data, &mut decoder)
.unwrap_or_else(|e| {
panic!(
"Failed to decode Data for {:?}: {e:?}",
entry.task_id
)
});
} else {
for idx in tasks_to_restore_for_data_indicies {
tasks[idx].2 = Some(TaskStorage::default());
}
task.flags.set_restored(TaskDataCategory::Data);
let task_type = task.get_persistent_task_type().cloned();
if task.flags.is_restored(entry.category) {
self.task_lock_counter.release();
prepared_task_callback(
self,
entry.task_id,
entry.category,
task,
);
} else {
drop(task);
self.task_lock_counter.release();
}
if let Some(task_type) = task_type {
self.backend
.task_cache
.entry(task_type)
.or_insert(entry.task_id);
}
} else {
*races_data += 1;
drop(task);
self.task_lock_counter.release();
}
match tasks_to_restore_for_meta.len() {
0 => {}
1 => {
let task_id = tasks_to_restore_for_meta[0];
let data = self.restore_task_data(task_id, SpecificTaskDataCategory::Meta);
let idx = tasks_to_restore_for_meta_indicies[0];
tasks[idx].3 = Some(data);
}
_ => {
if let Some(data) = self.restore_task_data_batch(
&tasks_to_restore_for_meta,
SpecificTaskDataCategory::Meta,
reason,
) {
data.into_iter()
.zip(tasks_to_restore_for_meta_indicies)
.for_each(|(item, idx)| {
tasks[idx].3 = Some(item);
SpecificTaskDataCategory::Meta => {
if !task.flags.is_restored(TaskDataCategory::Meta) {
if let Some(bytes) = opt_bytes {
let mut decoder = new_turbo_bincode_decoder(bytes);
task.decode(SpecificTaskDataCategory::Meta, &mut decoder)
.unwrap_or_else(|e| {
panic!(
"Failed to decode Meta for {:?}: {e:?}",
entry.task_id
)
});
}
task.flags.set_restored(TaskDataCategory::Meta);
if task.flags.is_restored(entry.category) {
self.task_lock_counter.release();
prepared_task_callback(
self,
entry.task_id,
entry.category,
task,
);
} else {
for idx in tasks_to_restore_for_meta_indicies {
tasks[idx].3 = Some(TaskStorage::new());
drop(task);
self.task_lock_counter.release();
}
} else {
*races_meta += 1;
drop(task);
self.task_lock_counter.release();
}
}
}
let mut races_data = 0u32;
let mut races_meta = 0u32;
for (task_id, category, storage_for_data, storage_for_meta) in tasks {
if storage_for_data.is_none() && storage_for_meta.is_none() {
continue;
},
);
if let Err(e) = result {
panic!(
"Failed to restore task data (corrupted database or bug): {:?}",
e.context(format!(
"{category:?} for batch of {} tasks",
task_ids.len()
))
)
}
} else {
// No backing storage — mark all tasks as restored with empty data.
for &task_index in task_indices {
let entry = &tasks[task_index];
self.task_lock_counter.acquire();
let mut task_type = None;
let mut task = self.backend.storage.access_mut(task_id);
if let Some(storage) = storage_for_data {
let mut task = self.backend.storage.access_mut(entry.task_id);
match category {
SpecificTaskDataCategory::Data => {
if !task.flags.is_restored(TaskDataCategory::Data) {
task.restore_from(storage, TaskDataCategory::Data);
task.flags.set_restored(TaskDataCategory::Data);
task_type = task.get_persistent_task_type().cloned()
if task.flags.is_restored(entry.category) {
self.task_lock_counter.release();
prepared_task_callback(self, entry.task_id, entry.category, task);
} else {
races_data += 1;
span.record("races_data", races_data);
drop(task);
self.task_lock_counter.release();
}
} else {
*races_data += 1;
drop(task);
self.task_lock_counter.release();
}
if let Some(storage) = storage_for_meta {
}
SpecificTaskDataCategory::Meta => {
if !task.flags.is_restored(TaskDataCategory::Meta) {
task.restore_from(storage, TaskDataCategory::Meta);
task.flags.set_restored(TaskDataCategory::Meta);
if task.flags.is_restored(entry.category) {
self.task_lock_counter.release();
prepared_task_callback(self, entry.task_id, entry.category, task);
} else {
races_meta += 1;
span.record("races_meta", races_meta);
}
drop(task);
self.task_lock_counter.release();
}
} else {
*races_meta += 1;
drop(task);
self.task_lock_counter.release();
prepared_task_callback(self, task_id, category, task);
if let Some(task_type) = task_type {
// Insert into the task cache to avoid future lookups
self.backend.task_cache.entry(task_type).or_insert(task_id);
}
}
}
}
}
}
......
......@@ -78,13 +78,22 @@ pub trait BackingStorageSealed: 'static + Send + Sync {
storage: &mut TaskStorage,
) -> Result<()>;
/// Batch lookup and decode data for multiple tasks directly into TypedStorage instances.
/// Returns a vector of TypedStorage, one for each task_id in the input slice.
/// Batch lookup raw bytes for multiple tasks, calling
/// `callback(index, Option<&[u8]>)` for every task in `task_ids` immediately after its
/// entry is resolved. Index corresponds to the position in `task_ids`. `None` means the key
/// was not found in the database (no allocation is made for missing keys).
///
/// The caller is responsible for decoding the bytes. The byte slice is only valid for the
/// duration of the callback invocation and must not be stored.
///
/// This avoids allocating an intermediate `TaskStorage` per entry — callers can decode
/// directly into the live in-memory storage, reducing peak memory usage for large batches.
fn batch_lookup_data(
&self,
task_ids: &[TaskId],
category: SpecificTaskDataCategory,
) -> Result<Vec<TaskStorage>>;
callback: &mut dyn FnMut(usize, Option<&[u8]>),
) -> Result<()>;
fn compact(&self) -> Result<bool> {
Ok(false)
......@@ -151,8 +160,9 @@ where
&self,
task_ids: &[TaskId],
category: SpecificTaskDataCategory,
) -> Result<Vec<TaskStorage>> {
either::for_both!(self, this => this.batch_lookup_data(task_ids, category))
callback: &mut dyn FnMut(usize, Option<&[u8]>),
) -> Result<()> {
either::for_both!(self, this => this.batch_lookup_data(task_ids, category, callback))
}
fn compact(&self) -> Result<bool> {
......
......@@ -75,17 +75,24 @@ pub trait KeyValueDatabase {
Ok(self.get(key_space, key)?.into_iter().collect())
}
fn batch_get(
/// Calls `callback(index, Option<&[u8]>)` for each key immediately after it is resolved,
/// rather than accumulating all results into a `Vec`. This avoids holding every decompressed
/// value simultaneously in memory.
///
/// The default implementation falls back to sequential `get` calls. Implementations backed by
/// [`TurboPersistence`] override this to use the native streaming path.
fn batch_get_with(
&self,
key_space: KeySpace,
keys: &[&[u8]],
) -> Result<Vec<Option<Self::ValueBuffer<'_>>>> {
let mut results = Vec::with_capacity(keys.len());
for key in keys {
mut callback: impl FnMut(usize, Option<&[u8]>) -> Result<()>,
) -> Result<()> {
for (index, key) in keys.iter().enumerate() {
let value = self.get(key_space, key)?;
results.push(value);
let opt_bytes = value.as_ref().map(std::borrow::Borrow::<[u8]>::borrow);
callback(index, opt_bytes)?;
}
Ok(results)
Ok(())
}
type ConcurrentWriteBatch<'l>: ConcurrentWriteBatch<'l>
......
......@@ -96,12 +96,13 @@ impl KeyValueDatabase for TurboKeyValueDatabase {
self.db.get(key_space as usize, &key)
}
fn batch_get(
fn batch_get_with(
&self,
key_space: KeySpace,
keys: &[&[u8]],
) -> Result<Vec<Option<Self::ValueBuffer<'_>>>> {
self.db.batch_get(key_space as usize, keys)
callback: impl FnMut(usize, Option<&[u8]>) -> Result<()>,
) -> Result<()> {
self.db.batch_get_with(key_space as usize, keys, callback)
}
fn get_multiple(
......
......@@ -347,32 +347,25 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
&self,
task_ids: &[TaskId],
category: SpecificTaskDataCategory,
) -> Result<Vec<TaskStorage>> {
callback: &mut dyn FnMut(usize, Option<&[u8]>),
) -> 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<_>>();
let bytes = inner
inner
.database
.batch_get(category.key_space(), &keys)
.batch_get_with(category.key_space(), &keys, |index, opt_bytes| {
callback(index, opt_bytes);
// `opt_bytes` (and any underlying ArcBytes) is dropped here before the next
// iteration, so only one decompressed block is live at a time.
Ok(())
})
.with_context(|| {
format!(
"Looking up typed data for {} tasks from database failed",
task_ids.len()
)
})?;
bytes
.into_iter()
.map(|opt_bytes| {
let mut storage = TaskStorage::new();
if let Some(bytes) = opt_bytes {
let mut decoder = new_turbo_bincode_decoder(bytes.borrow());
storage
.decode(category, &mut decoder)
.map_err(|e| anyhow::anyhow!("Failed to decode {category:?}: {e:?}"))?;
}
Ok(storage)
})
.collect::<Result<Vec<_>>>()
}
fn compact(&self) -> Result<bool> {
......
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