Unverified Commit 753e102c authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

turbopack: use reverse postorder priority in collect_graph (#100429)

## Summary

`collect_graph` computes per-module entry membership with the same
fixed-point traversal and BFS-depth priority as
`compute_chunk_group_info`. This PR switches it to the reverse-postorder
rank added in the PR below. That removes its own BFS depth pass, and a
module is now visited only after all of its importers (except across
cycles).

`TraversalPriority` has no remaining users, so it is removed.

Stacked on #100428, which introduces
`ModuleGraphSnapshot::reverse_postorder_ranks`.

### Benchmarks

**Setup:**
- Same as the PR below: Turbopack `next build --experimental-build-mode
compile`.
- `next-swc` release builds (LTO disabled, 16 codegen units).
- Binaries interleaved per run, 3 runs each, clean `.next`.
- Time is the depth or rank pass plus the fixed-point traversal,
measured with local-only instrumentation. Values are medians with
min–max ranges.
- "Before" is the PR below, which already includes its entry
deduplication.

| app | before | after |
|---|---|---|
| generated app router app (300 routes, ~12k modules) | 14.5 ms
(14.4–16.5), 12,030 visits | **9.5 ms** (8.3–11.0), 11,938 visits |
| `bench/nested-deps-app-router-many-pages` (~31k modules) | 422 ms
(417–426), 30,869 visits | **197 ms** (193–205), 30,777 visits |

For reference, `collect_graph` on many-pages takes 534 ms (496–546) on
canary.

## Verification

- `cargo test -p turbopack-core --lib`
- `cargo test -p turbopack-tests --test snapshot`: passes with no
snapshot changes.
- `cargo test -p turbopack-tests --test execution -- collect`
(emit/collect execution tests).

<!-- NEXT_JS_LLM -->


<!-- fleet b56269ed-2145-4f30-b0fe-dc9762520521 -->
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 5315c7b1
......@@ -465,30 +465,6 @@ impl Deref for ChunkGroupId {
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TraversalPriority {
pub depth: usize,
pub chunk_group_len: u64,
}
impl PartialOrd for TraversalPriority {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
// TODO automatically derive this using Reverse<_>
impl Ord for TraversalPriority {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
// BinaryHeap prioritizes high values
// Smaller depth has higher priority
let depth_order = self.depth.cmp(&other.depth).reverse();
// Smaller group length has higher priority
let chunk_group_len_order = self.chunk_group_len.cmp(&other.chunk_group_len).reverse();
depth_order.then(chunk_group_len_order)
}
}
pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGroupInfo>> {
let span_outer = tracing::info_span!(
"compute chunk group info",
......
use std::borrow::Cow;
use std::{borrow::Cow, cmp::Reverse};
use anyhow::{Context, Result, bail};
use rustc_hash::FxHashMap;
......@@ -12,7 +12,7 @@ use crate::{
module::Module,
module_graph::{
GraphTraversalAction, ModuleGraph, RefData,
chunk_group_info::{ChunkGroupEntry, RoaringBitmapWrapper, TraversalPriority},
chunk_group_info::{ChunkGroupEntry, RoaringBitmapWrapper},
},
};
......@@ -71,26 +71,12 @@ pub async fn collect_graph(graph: Vc<ModuleGraph>) -> Result<Vc<CollectedModules
}
}
// First, compute the depth for each module in the graph
let module_depth: FxHashMap<ResolvedVc<Box<dyn Module>>, usize> = {
let mut module_depth =
FxHashMap::with_capacity_and_hasher(module_count, Default::default());
graph.traverse_edges_bfs(entry_group_modules.iter().copied(), |parent, node| {
if let Some((parent, _)) = parent {
let parent_depth = *module_depth
.get(&parent)
.context("Module depth not found")?;
module_depth.entry(node).or_insert(parent_depth + 1);
} else {
module_depth.insert(node, 0);
};
module_entry_membership.entry(node).or_default();
Ok(GraphTraversalAction::Continue)
})?;
module_depth
};
// First, rank every module in reverse postorder (so that a module is visited after the
// modules importing it), and initialize the membership of every reachable module.
let module_rank = graph.reverse_postorder_ranks(entry_group_modules.iter().copied())?;
for module in module_rank.keys() {
module_entry_membership.entry(*module).or_default();
}
// - Discover all collecting module
// - Discover all emitted references
......@@ -105,10 +91,7 @@ pub async fn collect_graph(graph: Vc<ModuleGraph>) -> Result<Vc<CollectedModules
.map(|e| {
Ok((
*e,
TraversalPriority {
depth: *module_depth.get(e).context("Module depth not found")?,
chunk_group_len: 0,
},
Reverse(*module_rank.get(e).context("Module rank not found")?),
))
})
.collect::<Result<Vec<_>>>()?,
......@@ -158,16 +141,14 @@ pub async fn collect_graph(graph: Vc<ModuleGraph>) -> Result<Vc<CollectedModules
}
}
},
|successor, (module_entry_membership, _)| {
Ok(TraversalPriority {
depth: *module_depth
// Visit modules in reverse postorder (lowest rank first, the traversal visits the highest
// priority first), so that most modules are visited once, with their final membership.
|successor, _| {
Ok(Reverse(
*module_rank
.get(&successor)
.context("Module depth not found")?,
chunk_group_len: module_entry_membership
.get(&successor)
.context("Module entry membership not found")?
.len(),
})
.context("Module rank not found")?,
))
},
)?;
......
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