Unverified Commit 9a53adc3 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

[Turbopack] Perf improvements new backend (#71249)

### What?

A bunch of small performance optimizations

* split operation_suspend_point in inlined and cold part
* keep children count instead of iterating children every time
* avoid bubbling find and schedule into already scheduling parts of the
graph
* reduce number of turbo-tasks function calls in
EsmAssertReference::code_generation
* avoid creating empty maps

Sadly no measurable effect...
parent b1f5d139
......@@ -206,28 +206,36 @@ impl TurboTasksBackendInner {
}
fn operation_suspend_point(&self, suspend: impl FnOnce() -> AnyOperation) {
if self.suspending_requested() {
#[cold]
fn operation_suspend_point_cold(
this: &TurboTasksBackendInner,
suspend: impl FnOnce() -> AnyOperation,
) {
let operation = Arc::new(suspend());
let mut snapshot_request = self.snapshot_request.lock();
let mut snapshot_request = this.snapshot_request.lock();
if snapshot_request.snapshot_requested {
snapshot_request
.suspended_operations
.insert(operation.clone().into());
let value = self.in_progress_operations.fetch_sub(1, Ordering::AcqRel) - 1;
let value = this.in_progress_operations.fetch_sub(1, Ordering::AcqRel) - 1;
assert!((value & SNAPSHOT_REQUESTED_BIT) != 0);
if value == SNAPSHOT_REQUESTED_BIT {
self.operations_suspended.notify_all();
this.operations_suspended.notify_all();
}
self.snapshot_completed
this.snapshot_completed
.wait_while(&mut snapshot_request, |snapshot_request| {
snapshot_request.snapshot_requested
});
self.in_progress_operations.fetch_add(1, Ordering::AcqRel);
this.in_progress_operations.fetch_add(1, Ordering::AcqRel);
snapshot_request
.suspended_operations
.remove(&operation.into());
}
}
if self.suspending_requested() {
operation_suspend_point_cold(self, suspend);
}
}
pub(crate) fn start_operation(&self) -> OperationGuard<'_> {
......
......@@ -614,18 +614,18 @@ impl AggregationUpdateQueue {
}
}
if is_aggregating_node(get_aggregation_number(&task)) {
// TODO if it has an `AggregateRoot` we can skip visiting the nested nodes since
// if it has an `AggregateRoot` we can skip visiting the nested nodes since
// this would already be scheduled by the `AggregateRoot`
if !task.has_key(&CachedDataItemKey::AggregateRoot {}) {
task.insert(CachedDataItem::AggregateRoot {
value: RootState::new(ActiveType::CachedActiveUntilClean, task_id),
});
}
let dirty_containers: Vec<_> = get_many!(task, AggregatedDirtyContainer { task } count if count.get(session_id) > 0 => *task);
if !dirty_containers.is_empty() {
self.push(AggregationUpdateJob::FindAndScheduleDirty {
task_ids: dirty_containers,
});
let dirty_containers: Vec<_> = get_many!(task, AggregatedDirtyContainer { task } count if count.get(session_id) > 0 => *task);
if !dirty_containers.is_empty() {
self.push(AggregationUpdateJob::FindAndScheduleDirty {
task_ids: dirty_containers,
});
}
}
}
}
......
......@@ -13,7 +13,7 @@ use crate::{
invalidate::make_task_dirty,
AggregatedDataUpdate, ExecuteContext, Operation,
},
storage::update_count,
storage::{update, update_count},
TaskDataCategory,
},
data::{CachedDataItemKey, CellRef, CollectibleRef, CollectiblesRef},
......@@ -82,6 +82,12 @@ impl Operation for CleanupOldEdgesOperation {
for &child_id in children.iter() {
task.remove(&CachedDataItemKey::Child { task: child_id });
}
let remove_children_count = u32::try_from(children.len()).unwrap();
update!(task, ChildrenCount, |count: Option<u32>| {
// If this underflows, we messed up counting somewhere
let count = count.unwrap_or_default() - remove_children_count;
(count != 0).then_some(count)
});
if is_aggregating_node(get_aggregation_number(&task)) {
queue.push(AggregationUpdateJob::InnerLostFollowers {
upper_ids: vec![task_id],
......
......@@ -11,10 +11,10 @@ use crate::{
},
is_root_node, ExecuteContext, Operation,
},
storage::get,
storage::{get, update},
TaskDataCategory,
},
data::{CachedDataItem, CachedDataItemIndex, CachedDataItemKey},
data::{CachedDataItem, CachedDataItemKey},
};
const AGGREGATION_NUMBER_BUFFER_SPACE: u32 = 2;
......@@ -44,6 +44,13 @@ impl ConnectChildOperation {
task: child_task_id,
value: (),
}) {
// Update the children count
let mut children_count = 0;
update!(parent_task, ChildrenCount, |count: Option<u32>| {
children_count = count.unwrap_or_default() + 1;
Some(children_count)
});
// Update the task aggregation
let mut queue = AggregationUpdateQueue::new();
......@@ -54,16 +61,6 @@ impl ConnectChildOperation {
let parent_aggregation = if is_root_node(current_parent_aggregation.base) {
u32::MAX
} else {
let children_count = parent_task
.iter(CachedDataItemIndex::Children)
.filter(|(k, _)| {
matches!(
*k,
CachedDataItemKey::Child { .. }
| CachedDataItemKey::OutdatedChild { .. }
)
})
.count();
let target_distance = children_count.ilog2() * 2;
if target_distance != current_parent_aggregation.distance {
queue.push(AggregationUpdateJob::UpdateAggregationNumber {
......
......@@ -192,7 +192,7 @@ where
}
}
fn get_map_mut(&mut self, key: &T::Key) -> &mut AutoMap<T::Key, T::Value> {
fn get_or_create_map_mut(&mut self, key: &T::Key) -> &mut AutoMap<T::Key, T::Value> {
self.check_threshold();
match self {
InnerStorage::Plain { map, .. } => map,
......@@ -200,6 +200,14 @@ where
}
}
fn get_map_mut(&mut self, key: &T::Key) -> Option<&mut AutoMap<T::Key, T::Value>> {
self.check_threshold();
match self {
InnerStorage::Plain { map, .. } => Some(map),
InnerStorage::Indexed { map, .. } => map.get_mut(&key.index()),
}
}
fn get_map(&self, key: &T::Key) -> Option<&AutoMap<T::Key, T::Value>> {
match self {
InnerStorage::Plain { map, .. } => Some(map),
......@@ -216,7 +224,7 @@ where
pub fn add(&mut self, item: T) -> bool {
let (key, value) = item.into_key_and_value();
match self.get_map_mut(&key).entry(key) {
match self.get_or_create_map_mut(&key).entry(key) {
Entry::Occupied(_) => false,
Entry::Vacant(e) => {
e.insert(value);
......@@ -227,11 +235,11 @@ where
pub fn insert(&mut self, item: T) -> Option<T::Value> {
let (key, value) = item.into_key_and_value();
self.get_map_mut(&key).insert(key, value)
self.get_or_create_map_mut(&key).insert(key, value)
}
pub fn remove(&mut self, key: &T::Key) -> Option<T::Value> {
self.get_map_mut(key).remove(key)
self.get_map_mut(key).and_then(|m| m.remove(key))
}
pub fn get(&self, key: &T::Key) -> Option<&T::Value> {
......@@ -239,7 +247,7 @@ where
}
pub fn get_mut(&mut self, key: &T::Key) -> Option<&mut T::Value> {
self.get_map_mut(key).get_mut(key)
self.get_map_mut(key).and_then(|m| m.get_mut(key))
}
pub fn has_key(&self, key: &T::Key) -> bool {
......@@ -283,7 +291,7 @@ where
key: &T::Key,
update: impl FnOnce(Option<T::Value>) -> Option<T::Value>,
) {
let map = self.get_map_mut(key);
let map = self.get_or_create_map_mut(key);
if let Some(value) = map.get_mut(key) {
let v = take(value);
if let Some(v) = update(Some(v)) {
......
......@@ -313,6 +313,9 @@ pub enum CachedDataItem {
task: TaskId,
value: (),
},
ChildrenCount {
value: u32,
},
// Cells
CellData {
......@@ -438,6 +441,7 @@ impl CachedDataItem {
}
CachedDataItem::Dirty { .. } => true,
CachedDataItem::Child { task, .. } => !task.is_transient(),
CachedDataItem::ChildrenCount { .. } => true,
CachedDataItem::CellData { .. } => true,
CachedDataItem::CellTypeMaxIndex { .. } => true,
CachedDataItem::OutputDependency { target, .. } => !target.is_transient(),
......@@ -502,6 +506,7 @@ impl CachedDataItemKey {
}
CachedDataItemKey::Dirty { .. } => true,
CachedDataItemKey::Child { task, .. } => !task.is_transient(),
CachedDataItemKey::ChildrenCount {} => true,
CachedDataItemKey::CellData { .. } => true,
CachedDataItemKey::CellTypeMaxIndex { .. } => true,
CachedDataItemKey::OutputDependency { target, .. } => !target.is_transient(),
......@@ -534,6 +539,7 @@ impl CachedDataItemKey {
match self {
CachedDataItemKey::Collectible { .. }
| CachedDataItemKey::Child { .. }
| CachedDataItemKey::ChildrenCount { .. }
| CachedDataItemKey::CellData { .. }
| CachedDataItemKey::CellTypeMaxIndex { .. }
| CachedDataItemKey::OutputDependency { .. }
......@@ -678,6 +684,7 @@ impl CachedDataItemValue {
#[derive(Debug)]
pub struct CachedDataUpdate {
pub task: TaskId,
// TODO generate CachedDataItemUpdate to avoid repeating the variant field 3 times
pub key: CachedDataItemKey,
pub value: Option<CachedDataItemValue>,
pub old_value: Option<CachedDataItemValue>,
......
......@@ -70,7 +70,6 @@ pub enum ModuleResolveResultItem {
Error(Vc<RcStr>),
Empty,
Custom(u8),
Unresolveable,
}
#[turbo_tasks::value(shared)]
......@@ -398,7 +397,6 @@ pub enum ResolveResultItem {
Error(Vc<RcStr>),
Empty,
Custom(u8),
Unresolveable,
}
/// Represents the key for a request that leads to a certain results during
......@@ -491,9 +489,6 @@ impl ValueToString for ResolveResult {
ResolveResultItem::Custom(_) => {
result.push_str("custom");
}
ResolveResultItem::Unresolveable => {
result.push_str("unresolveable");
}
}
result.push('\n');
}
......@@ -684,9 +679,6 @@ impl ResolveResult {
ResolveResultItem::Custom(u8) => {
ModuleResolveResultItem::Custom(u8)
}
ResolveResultItem::Unresolveable => {
ModuleResolveResultItem::Unresolveable
}
},
))
}
......
......@@ -135,7 +135,7 @@ impl AsyncModule {
}
}
ReferencedAsset::External(..) => None,
ReferencedAsset::None => None,
ReferencedAsset::None | ReferencedAsset::Unresolveable => None,
})
})
.try_flat_join()
......
......@@ -43,6 +43,7 @@ pub enum ReferencedAsset {
Some(Vc<Box<dyn EcmascriptChunkPlaceable>>),
External(RcStr, ExternalType),
None,
Unresolveable,
}
impl ReferencedAsset {
......@@ -52,7 +53,7 @@ impl ReferencedAsset {
ReferencedAsset::External(request, ty) => Some(magic_identifier::mangle(&format!(
"{ty} external {request}"
))),
ReferencedAsset::None => None,
ReferencedAsset::None | ReferencedAsset::Unresolveable => None,
})
}
......@@ -72,7 +73,11 @@ impl ReferencedAsset {
#[turbo_tasks::function]
pub async fn from_resolve_result(resolve_result: Vc<ModuleResolveResult>) -> Result<Vc<Self>> {
// TODO handle multiple keyed results
for (_key, result) in resolve_result.await?.primary.iter() {
let result = resolve_result.await?;
if result.primary.is_empty() {
return Ok(ReferencedAsset::Unresolveable.cell());
}
for (_key, result) in result.primary.iter() {
match result {
ModuleResolveResultItem::External(request, ty) => {
return Ok(ReferencedAsset::External(request.clone(), *ty).cell());
......@@ -82,14 +87,14 @@ impl ReferencedAsset {
Vc::try_resolve_downcast::<Box<dyn EcmascriptChunkPlaceable>>(module)
.await?
{
return Ok(ReferencedAsset::cell(ReferencedAsset::Some(placeable)));
return Ok(ReferencedAsset::Some(placeable).cell());
}
}
// TODO ignore should probably be handled differently
_ => {}
}
}
Ok(ReferencedAsset::cell(ReferencedAsset::None))
Ok(ReferencedAsset::None.cell())
}
}
......@@ -244,28 +249,21 @@ impl CodeGenerateable for EsmAssetReference {
chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> {
let this = &*self.await?;
let chunking_type = self.chunking_type().await?;
let resolved = self.resolve_reference().await?;
// Insert code that throws immediately at time of import if a request is
// unresolvable
if resolved.is_unresolveable_ref() {
let request = request_to_string(this.request).await?.to_string();
let stmt = Stmt::Expr(ExprStmt {
expr: Box::new(throw_module_not_found_expr(&request)),
span: DUMMY_SP,
});
return Ok(CodeGeneration::hoisted_stmt(
format!("throw {request}").into(),
stmt,
));
}
// only chunked references can be imported
let result = if chunking_type.is_some() {
let referenced_asset = self.get_referenced_asset().await?;
let result = if this.annotations.chunking_type() != Some("none") {
let import_externals = this.import_externals;
if let Some(ident) = referenced_asset.get_ident().await? {
let referenced_asset = self.get_referenced_asset().await?;
if let ReferencedAsset::Unresolveable = &*referenced_asset {
// Insert code that throws immediately at time of import if a request is
// unresolvable
let request = request_to_string(this.request).await?.to_string();
let stmt = Stmt::Expr(ExprStmt {
expr: Box::new(throw_module_not_found_expr(&request)),
span: DUMMY_SP,
});
Some((format!("throw {request}").into(), stmt))
} else if let Some(ident) = referenced_asset.get_ident().await? {
let span = this
.issue_source
.await?
......@@ -275,6 +273,9 @@ impl CodeGenerateable for EsmAssetReference {
Span::new(BytePos(start as u32), BytePos(end as u32))
});
match &*referenced_asset {
ReferencedAsset::Unresolveable => {
unreachable!()
}
ReferencedAsset::Some(asset) => {
let id = asset
.as_chunk_item(Vc::upcast(chunking_context))
......
......@@ -205,7 +205,7 @@ impl CodeGenerateable for UrlAssetReference {
request
)
}
ReferencedAsset::None => {}
ReferencedAsset::None | ReferencedAsset::Unresolveable => {}
}
}
UrlRewriteBehavior::Full => {
......@@ -293,7 +293,7 @@ impl CodeGenerateable for UrlAssetReference {
request
)
}
ReferencedAsset::None => {}
ReferencedAsset::None | ReferencedAsset::Unresolveable => {}
}
}
UrlRewriteBehavior::None => {
......
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