Unverified Commit 1d09f425 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: Use batch get request to read more efficient from database (#87106)

### What?

Making a batch read from database can be more efficient:
* Order keys by hash for better cache locallity (in AMQF, key blocks, value blocks)
* Use binary search to filter keys by min/max hash of the SST files
* Only need to check family once instead of per key

Prefetch tasks with batch reads.
Add helper for "for each task" which can use batch read.

add tracing for database reads
parent f5cfb23b
......@@ -1338,6 +1338,9 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
/// might hold onto a block of the database and it should not be hold long-term.
pub fn get<K: QueryKey>(&self, family: usize, key: &K) -> Result<Option<ArcSlice<u8>>> {
debug_assert!(family < FAMILIES, "Family index out of bounds");
let span =
tracing::trace_span!("database read", family, result_size = tracing::field::Empty)
.entered();
let hash = hash_key(key);
let inner = self.inner.read();
for meta in inner.meta_files.iter().rev() {
......@@ -1368,17 +1371,20 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
LookupValue::Deleted => {
#[cfg(feature = "stats")]
self.stats.hits_deleted.fetch_add(1, Ordering::Relaxed);
span.record("result_size", "deleted");
return Ok(None);
}
LookupValue::Slice { value } => {
#[cfg(feature = "stats")]
self.stats.hits_small.fetch_add(1, Ordering::Relaxed);
span.record("result_size", value.len());
return Ok(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)?;
span.record("result_size", blob.len());
return Ok(Some(blob));
}
}
......@@ -1392,9 +1398,118 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
}
#[cfg(feature = "stats")]
self.stats.miss_global.fetch_add(1, Ordering::Relaxed);
span.record("result_size", "not found");
Ok(None)
}
pub fn batch_get<K: QueryKey>(
&self,
family: usize,
keys: &[K],
) -> Result<Vec<Option<ArcSlice<u8>>>> {
debug_assert!(family < FAMILIES, "Family index out of bounds");
let span = tracing::trace_span!(
"database batch read",
family,
keys = keys.len(),
not_found = tracing::field::Empty,
deleted = tracing::field::Empty,
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();
for (index, key) in keys.iter().enumerate() {
let hash = hash_key(key);
cells.push((hash, index, None));
}
cells.sort_by_key(|(hash, _, _)| *hash);
let inner = self.inner.read();
for meta in inner.meta_files.iter().rev() {
let _result = meta.batch_lookup(
family as u32,
keys,
&mut cells,
&mut empty_cells,
&self.amqf_cache,
&self.key_block_cache,
&self.value_block_cache,
)?;
#[cfg(feature = "stats")]
{
let crate::meta_file::MetaBatchLookupResult {
family_miss,
range_misses,
quick_filter_misses,
sst_misses,
hits: _,
} = _result;
if family_miss {
self.stats.miss_family.fetch_add(1, Ordering::Relaxed);
}
if range_misses > 0 {
self.stats
.miss_range
.fetch_add(range_misses as u64, Ordering::Relaxed);
}
if quick_filter_misses > 0 {
self.stats
.miss_amqf
.fetch_add(quick_filter_misses as u64, Ordering::Relaxed);
}
if sst_misses > 0 {
self.stats
.miss_key
.fetch_add(sst_misses as u64, Ordering::Relaxed);
}
}
if empty_cells == 0 {
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;
} else {
#[cfg(feature = "stats")]
self.stats.miss_global.fetch_add(1, Ordering::Relaxed);
not_found += 1;
}
}
span.record("not_found", not_found);
span.record("deleted", deleted);
span.record("result_size", result_size);
Ok(results)
}
/// Returns database statistics.
#[cfg(feature = "stats")]
pub fn statistics(&self) -> Statistics {
......
use std::{
cmp::Ordering,
fmt::Display,
fs::File,
hash::BuildHasherDefault,
......@@ -20,6 +21,7 @@ use turbo_bincode::turbo_bincode_decode;
use crate::{
QueryKey,
lookup_entry::LookupValue,
static_sorted_file::{BlockCache, SstLookupResult, StaticSortedFile, StaticSortedFileMetaData},
};
......@@ -211,6 +213,27 @@ pub enum MetaLookupResult {
SstLookup(SstLookupResult),
}
/// The result of a batch lookup operation.
#[derive(Default)]
pub struct MetaBatchLookupResult {
/// The key was not found because it is from a different key family.
#[cfg(feature = "stats")]
pub family_miss: bool,
/// The key was not found because it is out of the range of this SST file. But it was the
/// correct key family.
#[cfg(feature = "stats")]
pub range_misses: usize,
/// The key was not found because it was not in the AMQF filter. But it was in the range.
#[cfg(feature = "stats")]
pub quick_filter_misses: usize,
/// The key was unsuccessfully looked up in the SST file. It was in the AMQF filter.
#[cfg(feature = "stats")]
pub sst_misses: usize,
/// The key was found in the SST file.
#[cfg(feature = "stats")]
pub hits: usize,
}
/// The key family and hash range of an SST file.
#[derive(Clone, Copy)]
pub struct StaticSortedFileRange {
......@@ -406,4 +429,99 @@ impl MetaFile {
}
Ok(miss_result)
}
pub fn batch_lookup<K: QueryKey>(
&self,
key_family: u32,
keys: &[K],
cells: &mut [(u64, usize, Option<LookupValue>)],
empty_cells: &mut usize,
amqf_cache: &AmqfCache,
key_block_cache: &BlockCache,
value_block_cache: &BlockCache,
) -> Result<MetaBatchLookupResult> {
if key_family != self.family {
#[cfg(feature = "stats")]
return Ok(MetaBatchLookupResult {
family_miss: true,
..Default::default()
});
#[cfg(not(feature = "stats"))]
return Ok(MetaBatchLookupResult {});
}
debug_assert!(
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();
for entry in self.entries.iter().rev() {
let start_index = cells
.binary_search_by(|(hash, _, _)| hash.cmp(&entry.min_hash).then(Ordering::Greater))
.err()
.unwrap();
if start_index >= cells.len() {
#[cfg(feature = "stats")]
{
lookup_result.range_misses += 1;
}
continue;
}
let end_index = cells
.binary_search_by(|(hash, _, _)| hash.cmp(&entry.max_hash).then(Ordering::Less))
.err()
.unwrap()
.checked_sub(1);
let Some(end_index) = end_index else {
#[cfg(feature = "stats")]
{
lookup_result.range_misses += 1;
}
continue;
};
if start_index > end_index {
#[cfg(feature = "stats")]
{
lookup_result.range_misses += 1;
}
continue;
}
let amqf = entry.amqf(self, amqf_cache)?;
for (hash, index, result) in &mut cells[start_index..=end_index] {
if result.is_some() {
continue;
}
if !amqf.contains_fingerprint(*hash) {
#[cfg(feature = "stats")]
{
lookup_result.quick_filter_misses += 1;
}
continue;
}
let sst_result = entry.sst(self)?.lookup(
*hash,
&keys[*index],
key_block_cache,
value_block_cache,
)?;
if let SstLookupResult::Found(value) = sst_result {
*result = Some(value);
*empty_cells -= 1;
#[cfg(feature = "stats")]
{
lookup_result.hits += 1;
}
if *empty_cells == 0 {
return Ok(lookup_result);
}
} else {
#[cfg(feature = "stats")]
{
lookup_result.sst_misses += 1;
}
}
}
}
Ok(lookup_result)
}
}
......@@ -4,12 +4,10 @@ mod storage;
use std::{
borrow::Cow,
cmp::min,
fmt::{self, Write},
future::Future,
hash::BuildHasherDefault,
mem::take,
ops::Range,
pin::Pin,
sync::{
Arc, LazyLock,
......@@ -26,8 +24,8 @@ use smallvec::{SmallVec, smallvec};
use tokio::time::{Duration, Instant};
use tracing::{Span, trace_span};
use turbo_tasks::{
CellId, FxDashMap, FxIndexMap, KeyValuePair, RawVc, ReadCellOptions, ReadConsistency,
ReadOutputOptions, ReadTracking, TRANSIENT_TASK_BIT, TaskExecutionReason, TaskId, TraitTypeId,
CellId, FxDashMap, KeyValuePair, RawVc, ReadCellOptions, ReadConsistency, ReadOutputOptions,
ReadTracking, TRANSIENT_TASK_BIT, TaskExecutionReason, TaskId, TraitTypeId,
TurboTasksBackendApi, ValueTypeId,
backend::{
Backend, CachedTaskType, CellContent, TaskExecutionSpec, TransientTaskRoot,
......@@ -39,7 +37,7 @@ use turbo_tasks::{
task_statistics::TaskStatisticsApi,
trace::TraceRawVcs,
turbo_tasks,
util::{IdFactoryWithReuse, good_chunk_size},
util::IdFactoryWithReuse,
};
pub use self::{operation::AnyOperation, storage::TaskDataCategory};
......@@ -169,10 +167,6 @@ impl Default for BackendOptions {
pub enum TurboTasksBackendJob {
InitialSnapshot,
FollowUpSnapshot,
Prefetch {
data: Arc<FxIndexMap<TaskId, bool>>,
range: Option<Range<usize>>,
},
}
pub struct TurboTasksBackend<B: BackingStorage>(Arc<TurboTasksBackendInner<B>>);
......@@ -1643,6 +1637,11 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
{
let mut ctx = self.execute_context(turbo_tasks);
let mut task = ctx.task(task_id, TaskDataCategory::All);
if let Some(tasks) = task.prefetch() {
drop(task);
ctx.prepare_tasks(tasks);
task = ctx.task(task_id, TaskDataCategory::All);
}
let in_progress = remove!(task, InProgress)?;
let InProgressState::Scheduled { done_event, reason } = in_progress else {
task.add_new(CachedDataItem::InProgress { value: in_progress });
......@@ -2171,6 +2170,14 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
) {
debug_assert!(!output_dependent_tasks.is_empty());
if output_dependent_tasks.len() > 1 {
ctx.prepare_tasks(
output_dependent_tasks
.iter()
.map(|&id| (id, TaskDataCategory::All)),
);
}
let mut queue = AggregationUpdateQueue::new();
for dependent_task_id in output_dependent_tasks {
#[cfg(feature = "trace_task_output_dependencies")]
......@@ -2228,9 +2235,9 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
debug_assert!(!new_children.is_empty());
let mut queue = AggregationUpdateQueue::new();
for &child_id in new_children {
let child_task = ctx.task(child_id, TaskDataCategory::Meta);
ctx.for_each_task_meta(new_children.iter().copied(), |child_task, ctx| {
if !child_task.has_key(&CachedDataItemKey::Output {}) {
let child_id = child_task.id();
make_task_dirty_internal(
child_task,
child_id,
......@@ -2241,7 +2248,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
ctx,
);
}
}
});
queue.execute(ctx);
}
......@@ -2579,41 +2586,6 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
}
}
}
TurboTasksBackendJob::Prefetch { data, range } => {
let range: Range<usize> = if let Some(range) = range {
range
} else {
if data.len() > 128 {
let chunk_size = good_chunk_size(data.len());
let chunks = data.len().div_ceil(chunk_size);
for i in 0..chunks {
turbo_tasks.schedule_backend_background_job(
TurboTasksBackendJob::Prefetch {
data: data.clone(),
range: Some(
(i * chunk_size)..min(data.len(), (i + 1) * chunk_size),
),
},
);
}
return;
}
0..data.len()
};
let _span = trace_span!("prefetching").entered();
let mut ctx = self.execute_context(turbo_tasks);
for i in range {
let (&task, &with_data) = data.get_index(i).unwrap();
let category = if with_data {
TaskDataCategory::All
} else {
TaskDataCategory::Meta
};
// Prefetch the task
drop(ctx.task(task, category));
}
}
}
})
}
......
......@@ -1501,12 +1501,8 @@ impl AggregationUpdateQueue {
ctx: &mut impl ExecuteContext,
update: AggregatedDataUpdate,
) {
for upper_id in upper_ids {
let mut upper = ctx.task(
upper_id,
// For performance reasons this should stay `Meta` and not `All`
TaskDataCategory::Meta,
);
// For performance reasons this should stay `Meta` and not `All`
ctx.for_each_task_meta(upper_ids.iter().copied(), |mut upper, ctx| {
let diff = update.apply(&mut upper, ctx.should_track_activeness(), self);
if !diff.is_empty() {
let upper_ids = get_uppers(&upper);
......@@ -1520,7 +1516,7 @@ impl AggregationUpdateQueue {
);
}
}
}
});
}
fn inner_of_uppers_lost_follower(
......@@ -1565,13 +1561,9 @@ impl AggregationUpdateQueue {
drop(follower);
if !data.is_empty() {
for upper_id in removed_uppers.iter() {
// remove data from upper
let mut upper = ctx.task(
*upper_id,
// For performance reasons this should stay `Meta` and not `All`
TaskDataCategory::Meta,
);
// remove data from upper
// For performance reasons this should stay `Meta` and not `All`
ctx.for_each_task_meta(removed_uppers.iter().copied(), |mut upper, ctx| {
let diff = data.apply(&mut upper, ctx.should_track_activeness(), self);
if !diff.is_empty() {
let upper_ids = get_uppers(&upper);
......@@ -1583,7 +1575,7 @@ impl AggregationUpdateQueue {
.into(),
)
}
}
});
}
if !followers.is_empty() {
self.push(
......@@ -1956,13 +1948,9 @@ impl AggregationUpdateQueue {
let has_data = !data.is_empty();
if has_data || !is_active {
for upper_id in upper_ids.iter() {
// add data to upper
let mut upper = ctx.task(
*upper_id,
// For performance reasons this should stay `Meta` and not `All`
TaskDataCategory::Meta,
);
// add data to upper
// For performance reasons this should stay `Meta` and not `All`
ctx.for_each_task_meta(upper_ids.iter().copied(), |mut upper, ctx| {
if has_data {
let diff = data.apply(&mut upper, ctx.should_track_activeness(), self);
if !diff.is_empty() {
......@@ -1983,7 +1971,7 @@ impl AggregationUpdateQueue {
is_active = true;
}
}
}
});
}
if !children.is_empty() {
self.push(
......
......@@ -15,7 +15,7 @@ use crate::{
AggregationUpdateQueue, ExecuteContext, Operation, TaskGuard,
invalidate::make_task_dirty_internal,
},
storage::{get_many, remove},
storage::{iter_many, remove},
},
data::{CachedDataItem, CachedDataItemKey, CellRef},
};
......@@ -96,12 +96,17 @@ impl UpdateCellOperation {
// When not recomputing, we need to notify dependent tasks if the content actually
// changes.
let dependent_tasks: SmallVec<[TaskId; 4]> = get_many!(
let dependent_tasks: SmallVec<[TaskId; 4]> = iter_many!(
task,
CellDependent { cell: dependent_cell, task }
if dependent_cell == cell
=> task
);
)
.filter(|&dependent_task_id| {
// once tasks are never invalidated
!ctx.is_once_task(dependent_task_id)
})
.collect();
if !dependent_tasks.is_empty() {
// Slow path: We need to invalidate tasks depending on this cell.
......@@ -125,6 +130,12 @@ impl UpdateCellOperation {
drop(task);
drop(old_content);
ctx.prepare_tasks(
dependent_tasks
.iter()
.map(|&id| (id, TaskDataCategory::All)),
);
UpdateCellOperation::InvalidateWhenCellDependency {
is_serializable_cell_content,
cell_ref: CellRef {
......@@ -197,10 +208,6 @@ impl Operation for UpdateCellOperation {
ref mut queue,
} => {
if let Some(dependent_task_id) = dependent_tasks.pop() {
if ctx.is_once_task(dependent_task_id) {
// once tasks are never invalidated
continue;
}
let mut make_stale = true;
let dependent = ctx.task(dependent_task_id, TaskDataCategory::All);
if dependent.has_key(&CachedDataItemKey::OutdatedCellDependency {
......
......@@ -87,6 +87,23 @@ pub trait BackingStorageSealed: 'static + Send + Sync {
task_id: TaskId,
category: TaskDataCategory,
) -> Result<Vec<CachedDataItem>>;
/// # Safety
///
/// `tx` must be a transaction from this BackingStorage instance.
unsafe fn batch_lookup_data(
&self,
tx: Option<&Self::ReadTransaction<'_>>,
task_ids: &[TaskId],
category: TaskDataCategory,
) -> Result<Vec<Vec<CachedDataItem>>> {
let mut results = Vec::with_capacity(task_ids.len());
for &task_id in task_ids {
// TODO more efficient batch implementation
let data = unsafe { self.lookup_data(tx, task_id, category)? };
results.push(data);
}
Ok(results)
}
fn shutdown(&self) -> Result<()> {
Ok(())
......@@ -204,6 +221,24 @@ where
}
}
unsafe fn batch_lookup_data(
&self,
tx: Option<&Self::ReadTransaction<'_>>,
task_ids: &[TaskId],
category: TaskDataCategory,
) -> Result<Vec<Vec<CachedDataItem>>> {
match self {
Either::Left(this) => {
let tx = tx.map(|tx| read_transaction_left_or_panic(tx.as_ref()));
unsafe { this.batch_lookup_data(tx, task_ids, category) }
}
Either::Right(this) => {
let tx = tx.map(|tx| read_transaction_right_or_panic(tx.as_ref()));
unsafe { this.batch_lookup_data(tx, task_ids, category) }
}
}
}
fn shutdown(&self) -> Result<()> {
either::for_both!(self, this => this.shutdown())
}
......
......@@ -35,6 +35,20 @@ pub trait KeyValueDatabase {
key: &[u8],
) -> Result<Option<Self::ValueBuffer<'l>>>;
fn batch_get<'l, 'db: 'l>(
&'l self,
transaction: &'l Self::ReadTransaction<'db>,
key_space: KeySpace,
keys: &[&[u8]],
) -> Result<Vec<Option<Self::ValueBuffer<'l>>>> {
let mut results = Vec::with_capacity(keys.len());
for key in keys {
let value = self.get(transaction, key_space, key)?;
results.push(value);
}
Ok(results)
}
type SerialWriteBatch<'l>: SerialWriteBatch<'l>
= UnimplementedWriteBatch
where
......
......@@ -84,6 +84,15 @@ impl KeyValueDatabase for TurboKeyValueDatabase {
self.db.get(key_space as usize, &key)
}
fn batch_get<'l, 'db: 'l>(
&'l self,
_transaction: &'l Self::ReadTransaction<'db>,
key_space: KeySpace,
keys: &[&[u8]],
) -> Result<Vec<Option<Self::ValueBuffer<'l>>>> {
self.db.batch_get(key_space as usize, keys)
}
type ConcurrentWriteBatch<'l>
= TurboWriteBatch<'l>
where
......
......@@ -523,11 +523,7 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
) -> Result<Vec<CachedDataItem>> {
let Some(bytes) = database.get(
tx,
match category {
TaskDataCategory::Meta => KeySpace::TaskMeta,
TaskDataCategory::Data => KeySpace::TaskData,
TaskDataCategory::All => unreachable!(),
},
category_to_key_space(category),
IntKey::new(*task_id).as_ref(),
)?
else {
......@@ -541,6 +537,52 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
.with_context(|| format!("Looking up data for {task_id} from database failed"))
}
unsafe fn batch_lookup_data(
&self,
tx: Option<&Self::ReadTransaction<'_>>,
task_ids: &[TaskId],
category: TaskDataCategory,
) -> Result<Vec<Vec<CachedDataItem>>> {
let inner = &*self.inner;
fn lookup<D: KeyValueDatabase>(
database: &D,
tx: &D::ReadTransaction<'_>,
task_ids: &[TaskId],
category: TaskDataCategory,
) -> Result<Vec<Vec<CachedDataItem>>> {
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 = database.batch_get(
tx,
match category {
TaskDataCategory::Meta => KeySpace::TaskMeta,
TaskDataCategory::Data => KeySpace::TaskData,
TaskDataCategory::All => unreachable!(),
},
&keys,
)?;
bytes
.into_iter()
.map(|opt_bytes| {
if let Some(bytes) = opt_bytes {
let result: Vec<CachedDataItem> = turbo_bincode_decode(bytes.borrow())?;
Ok(result)
} else {
Ok(Vec::new())
}
})
.collect::<Result<Vec<_>>>()
}
inner
.with_tx(tx, |tx| lookup(&inner.database, tx, task_ids, category))
.with_context(|| {
format!(
"Looking up data for {} tasks from database failed",
task_ids.len()
)
})
}
fn shutdown(&self) -> Result<()> {
self.inner.database.shutdown()
}
......@@ -765,3 +807,11 @@ fn encode_task_data(task: TaskId, data: &Vec<CachedDataItem>) -> Result<TurboBin
})
.with_context(|| format!("Unable to serialize data items for {task}: {filtered_data:#?}"))
}
fn category_to_key_space(category: TaskDataCategory) -> KeySpace {
match category {
TaskDataCategory::Meta => KeySpace::TaskMeta,
TaskDataCategory::Data => KeySpace::TaskData,
TaskDataCategory::All => unreachable!(),
}
}
......@@ -87,7 +87,7 @@ pub async fn compute_binding_usage_info(
remove_unused_imports: bool,
) -> Result<Vc<BindingUsageInfo>> {
let span_outer = tracing::info_span!(
"compute bindung usage info",
"compute binding usage info",
visit_count = tracing::field::Empty,
unused_reference_count = tracing::field::Empty
);
......
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