Unverified Commit 536581c0 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

turbopack: speed up and share reverse postorder ranks (#100452)

Stacked on #100440. The lower PRs of the stack (#100428, #100429,
#100430) are merged.

### What?

Two changes to the reverse postorder ranks that the RPO stack computes
before each fixed-point traversal:

1. **A faster `ModuleGraphSnapshot::reverse_postorder_ranks`, with
identical ranks.**
- Visited nodes are tracked in one `FixedBitSet` per graph instead of an
`FxHashSet<GraphNodeIndex>`. `DiGraph` node indices are dense, and
`VisitedModule` aliases are resolved first.
- `postorder` is preallocated, and the result map is created with
capacity. Collecting a `Result` iterator into a map gives it no capacity
hint, so it rehashes as it grows.
   - One DFS stack is reused across roots.
   - DFS order and rank numbering are unchanged.
- The method now asserts it's called on the whole graph, not on an
individual graph layer, where `VisitedModule` nodes can't be resolved.
This matches the existing check in
`traverse_edges_fixed_point_with_priority`.
2. **One shared rank computation for chunk group info and merged
modules.**
- The new `ModuleGraphSnapshot::entry_ranks` computes the ranks from the
entries of the graph (derived from its chunk groups) on first use and
caches them in a `OnceLock` on the snapshot.
- `compute_chunk_group_info` and `compute_merged_modules` already
computed exactly these ranks (same entries, same order) on the same
graph, so they now share one computation.

### Why?

The RPO stack adds a rank pass in front of each fixed-point analysis, 5
per build. This removes most of that added cost.

The cache lives on the immutable `ModuleGraph` snapshot that the
analyses already read through the shared `ReadRef`:
- the ranks always belong to exactly the graph being traversed;
- there is no extra turbo-tasks function or cell, and no second,
separately versioned read inside a task;
- there is nothing extra to invalidate, since a changed graph is a new
snapshot with an empty cache;
- the ranks are computed inside `OnceLock::get_or_init`, so concurrent
cold callers wait for one computation instead of racing;
- an error is cached too (as a cloneable `SharedError`) and returned to
every caller of that snapshot.

Not shared:
- **`collect_graph`** roots its DFS only at `Entry` chunk groups.
Sharing all-entry ranks would change its order on cyclic graphs, so it
keeps computing its own ranks (with the faster implementation).
- **`compute_binding_usage_info`** runs on different graphs, before
unused references are removed, so it keeps computing its own ranks as
well.

### Benchmarks

> **Historical, not rerun:** measured in the previous review round,
before this stack was rebased onto canary `502b6b7d` and before the
latest review changes. This round only reran the `turbo-bitset`
microbenchmarks in #100566.

Real Turbopack `next build --experimental-build-mode compile` with
release `next-swc` builds (LTO off, 16 codegen units). #100440 and this
PR were each built with the same local timing instrumentation and run 5
times per app, interleaved in randomized order. Times are medians
[min–max], summed over all rank computations of a build:

| | rank passes per build | #100440 | this PR |
|---|---|---|---|
| generated app router app, 300 routes | 5 → 4 | 21.1 ms [20.0–23.6] |
14.2 ms [12.7–15.5] |
| `bench/nested-deps-app-router-many-pages` | 5 → 4 | 67.9 ms
[58.8–70.7] | 25.5 ms [25.1–32.5] |

Per caller (many-pages, median):

| | binding usage (2×) | chunk group info | collect | merged modules |
|---|---|---|---|---|
| #100440 | 26.6 ms | 12.4 ms | 11.6 ms | 12.0 ms |
| this PR | 12.7 ms | 6.5 ms (shared) | 6.4 ms | cached |

- **Visit counts:** identical between both versions, for every
fixed-point analysis, in all runs.
- **Fixed-point time:** expected to be unchanged. The measured
differences are within the run-to-run noise.
- **Caveats:**
  - These are sums of rank-helper timers, not wall-clock savings.
- This machine was slower than in the earlier PRs of the stack, so
absolute numbers aren't comparable with those PRs.

### How was it verified?

- **Exact ranks:** while developing, the previous implementation was
kept as a reference and compared against the new one on every call, with
`assert_eq!` on the rank maps. The comparison ran across the
`turbopack-core` lib tests, the snapshot and execution suites, and real
builds of both benchmark apps (4 rank computations per build). There
were no mismatches. The reference was removed afterwards.
- **New unit tests:**
- the shared ranks equal
`reverse_postorder_ranks(all_chunk_group_entry_modules())` on a graph
with a diamond and a cycle, and a second call returns the same map;
- a new snapshot of an edited graph gets fresh ranks, including the new
module, while the old snapshot keeps its cached map;
  - calling `reverse_postorder_ranks` on a graph layer panics.
- **Suites and checks:** `cargo test -p turbopack-core --lib`, `cargo
test -p turbopack-tests --test snapshot` (no snapshot changes) and
`cargo test -p turbopack-tests --test execution` pass. `cargo clippy -p
turbopack-core --all-targets -- -D warnings` and `RUSTDOCFLAGS='-D
warnings' cargo doc -p turbopack-core --no-deps` are clean.
- **Real builds:** the emitted chunks of both benchmark apps are
byte-identical to #100440 (sha256 over all JS files in
`.next/server/chunks` and `.next/static/chunks`).

<!-- 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>
Co-authored-by: 's avatarVercel Fleet <fleet@vercel.com>
parent cc0cdc8b
......@@ -9622,6 +9622,7 @@ dependencies = [
"data-encoding",
"either",
"erased-serde",
"fixedbitset",
"indexmap 2.14.0",
"itertools 0.10.5",
"num-bigint",
......
......@@ -24,6 +24,7 @@ const_format = { workspace = true }
data-encoding = { workspace = true }
either = { workspace = true }
erased-serde = { workspace = true }
fixedbitset = { workspace = true }
indexmap = { workspace = true }
itertools = { workspace = true }
num-bigint = "0.4"
......
......@@ -168,9 +168,9 @@ pub async fn compute_binding_usage_info(
// Visit modules in reverse postorder. In an acyclic graph, this processes each module only
// after all modules importing it, i.e. once, with its final usage. Cycles still rely on the
// fixed point and may revisit modules in or after them. This avoids order-dependent
// revisits in DAG-shaped graphs, at the cost of an additional traversal to compute ranks.
let module_rank =
graph_ref.reverse_postorder_ranks(graph_ref.all_chunk_group_entry_modules())?;
// revisits in DAG-shaped graphs, at the cost of an additional traversal to compute ranks
// (shared with the other analyses of this graph).
let module_rank = graph_ref.entry_ranks()?;
let visit_count = graph_ref.traverse_edges_fixed_point_with_priority(
graph_ref
......
......@@ -639,9 +639,9 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result<Vc<ChunkGro
let entries = graph.all_chunk_group_entries().collect::<Vec<_>>();
// First, rank every module in reverse postorder (so that a module is visited after the
// modules importing it), and initialize `module_chunk_groups` with empty bitmaps.
let module_rank =
graph.reverse_postorder_ranks(entries.iter().flat_map(|e| e.entries()))?;
// modules importing it), and initialize `module_chunk_groups` with empty bitmaps. The ranks
// from the entries of the graph are shared with other analyses of this graph.
let module_rank = graph.entry_ranks()?;
module_chunk_groups.reserve(module_rank.len());
for module in module_rank.keys() {
module_chunk_groups.insert(*module, RoaringBitmapWrapper::default());
......
......@@ -210,10 +210,11 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
.collect::<Vec<_>>();
// First, rank every module in reverse postorder, so that a module is visited after the
// modules importing it.
// modules importing it. The ranks from the entries of the graph are shared with other
// analyses of this graph (e.g. the chunk group info).
let module_rank = {
let _inner_span = tracing::info_span!("compute reverse postorder").entered();
module_graph.reverse_postorder_ranks(entries.iter().copied())?
module_graph.entry_ranks()?
};
// For each module, the indices in the bitmap store which merge group entry modules
......
......@@ -8,6 +8,7 @@ use std::{
use anyhow::{Context, Result, bail};
use bincode::{Decode, Encode};
use fixedbitset::FixedBitSet;
use petgraph::{
Direction,
graph::{DiGraph, EdgeIndex, NodeIndex},
......@@ -23,6 +24,7 @@ use turbo_tasks::{
debug::ValueDebugFormat,
graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow},
keyed::KeyedAccess,
util::SharedError,
};
use turbo_tasks_fs::FileSystemPath;
......@@ -841,6 +843,7 @@ impl ModuleGraph {
} else {
None
},
entry_ranks: OnceLock::new(),
},
}
.cell())
......@@ -981,6 +984,7 @@ impl ModuleGraphLayer {
} else {
None
},
entry_ranks: OnceLock::new(),
},
}
.cell())
......@@ -998,6 +1002,9 @@ impl Deref for ModuleGraphLayer {
#[turbo_tasks::value(transparent)]
pub struct ModuleGraphLayers(Vec<OperationVc<ModuleGraphLayer>>);
/// The reverse postorder rank of each module, see [`ModuleGraphSnapshot::reverse_postorder_ranks`].
type ModuleRanks = FxHashMap<ResolvedVc<Box<dyn Module>>, usize>;
/// This struct provides traversal functionality for the module graph.
///
/// Some edges might be ignored during traversal: unused references listed in
......@@ -1021,6 +1028,11 @@ pub struct ModuleGraphSnapshot {
/// The edges of unused references (from [`BindingUsageInfo::unused_references_edges`]), which
/// are skipped during traversals.
unused_references_edges: Option<ReadRef<UnusedReferenceEdges>>,
/// Lazily computed [`Self::entry_ranks`] (or the error computing them). Derived from the
/// immutable graphs, so it never needs to be invalidated.
#[turbo_tasks(debug_ignore, unsafe_ignore)]
entry_ranks: OnceLock<Result<ModuleRanks, SharedError>>,
}
impl ModuleGraphSnapshot {
......@@ -1520,10 +1532,20 @@ impl ModuleGraphSnapshot {
/// visited multiple times.
///
/// Runs in linear time and without recursion.
pub fn reverse_postorder_ranks(
///
/// Must be called on the whole graph, not on an individual graph layer (where `VisitedModule`
/// nodes can't be resolved).
///
/// Use [`Self::entry_ranks`] for the ranks from the entries of the graph, which are computed
/// once per snapshot. This is only for other roots, e.g. a subset of the entries.
fn reverse_postorder_ranks(
&self,
entries: impl IntoIterator<Item = ResolvedVc<Box<dyn Module>>>,
) -> Result<FxHashMap<ResolvedVc<Box<dyn Module>>, usize>> {
assert!(
!self.skip_visited_module_children && self.graph_idx_override.is_none(),
"reverse_postorder_ranks musn't be called on individual graphs"
);
// Nodes are identified by their canonical node (i.e. never a `VisitedModule`), which is
// the node the fixed point traversal expands.
let canonical = |node: GraphNodeIndex| -> Result<GraphNodeIndex> {
......@@ -1533,21 +1555,36 @@ impl ModuleGraphSnapshot {
.unwrap_or(node))
};
let mut visited: FxHashSet<GraphNodeIndex> = FxHashSet::default();
let mut postorder: Vec<GraphNodeIndex> = Vec::new();
// Node indices of a `DiGraph` are dense, so a bitset per graph tracks the visited nodes.
let mut visited = self
.graphs
.iter()
.map(|g| FixedBitSet::with_capacity(g.graph.node_count()))
.collect::<Vec<_>>();
// Marks `node` as visited, returns whether it wasn't visited before.
let mut visit =
|node: GraphNodeIndex| !visited[node.graph_idx as usize].put(node.node_idx.index());
let mut postorder: Vec<GraphNodeIndex> = Vec::with_capacity(
self.graphs
.iter()
.map(|g| g.graph.node_count())
.sum::<usize>(),
);
let mut stack = Vec::new();
for entry in entries {
let entry = canonical(self.get_entry(entry)?)?;
if !visited.insert(entry) {
if !visit(entry) {
continue;
}
let mut stack = vec![(
stack.push((
entry,
self.iter_graphs_neighbors_rev(entry, Direction::Outgoing, false, false),
)];
));
while let Some((node, children)) = stack.last_mut() {
if let Some((_, child)) = children.next() {
let child = canonical(child)?;
if visited.insert(child) {
if visit(child) {
stack.push((
child,
self.iter_graphs_neighbors_rev(
......@@ -1566,11 +1603,38 @@ impl ModuleGraphSnapshot {
}
let count = postorder.len();
postorder
.into_iter()
.enumerate()
.map(|(i, node)| Ok((self.get_node(node)?.module(), count - 1 - i)))
.collect()
let mut ranks = FxHashMap::with_capacity_and_hasher(count, Default::default());
for (i, node) in postorder.into_iter().enumerate() {
ranks.insert(self.get_node(node)?.module(), count - 1 - i);
}
Ok(ranks)
}
/// A priority for [`Self::traverse_edges_fixed_point_with_priority`] that minimizes the number
/// of retraversals: the rank of every module reachable from the entries of the graph, i.e. the
/// entries of its chunk groups ([`Self::all_chunk_group_entry_modules`]), in the *reverse
/// postorder* of a depth-first search from them.
///
/// Traced and unused references are ignored, like in the fixed point traversal. For every
/// reference outside of a cycle, the importing module has a lower rank than the imported
/// module. So when the graph has no cycles, visiting lower ranks first (e.g. using
/// [`std::cmp::Reverse`] as the priority, as the traversal visits high priorities first) visits
/// every module only after all of the modules importing it, i.e. exactly once. Modules in or
/// after a cycle can still be visited multiple times.
///
/// They are computed on the first call and cached in this snapshot, so that all analyses of
/// the same graph that need exactly these ranks share one computation. As the snapshot is
/// immutable, the cached ranks always match the graph. They are computed only once, even with
/// concurrent callers (which wait for the first one). An error is cached as well and returned
/// to every caller.
pub fn entry_ranks(&self) -> Result<&FxHashMap<ResolvedVc<Box<dyn Module>>, usize>> {
self.entry_ranks
.get_or_init(|| {
self.reverse_postorder_ranks(self.all_chunk_group_entry_modules())
.map_err(SharedError::new)
})
.as_ref()
.map_err(|err| err.clone().into())
}
/// Traverses all reachable nodes and also continue revisiting them as long the visitor returns
......@@ -1580,7 +1644,7 @@ impl ModuleGraphSnapshot {
///
/// Nodes are (re)visited according to the returned priority of the node, prioritizing high
/// values. This priority is intended to be used a heuristic to reduce the number of
/// retraversals. [`ModuleGraphSnapshot::reverse_postorder_ranks`] computes a priority that
/// retraversals. [`ModuleGraphSnapshot::entry_ranks`] computes a priority that
/// avoids retraversals for all modules not in or after a cycle.
///
/// * `entries` - The entry modules to start the traversal from
......@@ -3430,6 +3494,171 @@ pub mod tests {
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_entry_ranks_cached() {
run_graph_test(
vec![rcstr!("a.js"), rcstr!("e.js")],
{
// A diamond (a -> b, c -> d) and a cycle (d -> a)
let mut deps = FxHashMap::default();
deps.insert(rcstr!("a.js"), vec![rcstr!("b.js"), rcstr!("c.js")]);
deps.insert(rcstr!("b.js"), vec![rcstr!("d.js")]);
deps.insert(rcstr!("c.js"), vec![rcstr!("d.js")]);
deps.insert(rcstr!("d.js"), vec![rcstr!("a.js")]);
deps.insert(rcstr!("e.js"), vec![rcstr!("c.js")]);
deps
},
|graph, _, _| {
let shared = graph.entry_ranks()?;
let expected =
graph.reverse_postorder_ranks(graph.all_chunk_group_entry_modules())?;
assert_eq!(shared, &expected);
assert_eq!(shared.len(), 5);
// The second call returns the cached map
assert!(std::ptr::eq(shared, graph.entry_ranks()?));
Ok(())
},
)
.await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_entry_ranks_new_snapshot() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async move {
#[turbo_tasks::value]
struct Results {
old_len_before: usize,
old_len_after: usize,
old_unchanged: bool,
new_len: usize,
new_matches_fresh: bool,
new_contains_c: bool,
old_contains_c: bool,
}
#[turbo_tasks::function(operation, root)]
async fn new_snapshot_operation() -> Result<Vc<Results>> {
let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
let root = fs.root().await?;
async fn graph_for(
root: &FileSystemPath,
deps: Vec<(&'static str, Vec<&'static str>)>,
) -> Result<(ReadRef<ModuleGraph>, ResolvedVc<Box<dyn Module>>)> {
let repo = TestRepo::new(root, deps);
let module = |name| {
Vc::upcast::<Box<dyn Module>>(MockModule::new(
root.join(name).unwrap(),
repo,
))
.to_resolved()
};
let a = module("a.js").await?;
let c = module("c.js").await?;
let graph = SingleModuleGraph::new_with_entries(
GraphEntries::from_chunk_groups(vec![ChunkGroupEntry::Entry {
modules: vec![a],
heuristics: EntryHeuristics::default(),
}])
.resolved_cell(),
false,
false,
);
let graph = ModuleGraph::from_graphs(vec![graph], None)
.connect()
.await?;
Ok((graph, c))
}
// The first graph: a -> b
let (old_graph, old_c_module) =
graph_for(&root, vec![("a.js", vec!["b.js"])]).await?;
let old_ranks = old_graph.entry_ranks()?;
let old_len_before = old_ranks.len();
// The edited graph: a -> b -> c
let (new_graph, c_module) =
graph_for(&root, vec![("a.js", vec!["b.js"]), ("b.js", vec!["c.js"])]).await?;
let new_ranks = new_graph.entry_ranks()?;
let fresh =
new_graph.reverse_postorder_ranks(new_graph.all_chunk_group_entry_modules())?;
Ok(Results {
old_len_before,
old_len_after: old_graph.entry_ranks()?.len(),
old_unchanged: std::ptr::eq(old_ranks, old_graph.entry_ranks()?),
new_len: new_ranks.len(),
new_matches_fresh: new_ranks == &fresh,
new_contains_c: new_ranks.contains_key(&c_module),
old_contains_c: old_ranks.contains_key(&old_c_module),
}
.cell())
}
let results = new_snapshot_operation().read_strongly_consistent().await?;
assert_eq!(results.old_len_before, 2);
assert_eq!(results.old_len_after, 2);
assert!(results.old_unchanged);
assert!(!results.old_contains_c);
assert_eq!(results.new_len, 3);
assert!(results.new_matches_fresh);
assert!(results.new_contains_c);
Ok(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_reverse_postorder_ranks_layer_snapshot_panics() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async move {
#[turbo_tasks::function(operation, root)]
async fn layer_panics_operation() -> Result<Vc<bool>> {
let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
let root = fs.root().await?;
let repo = TestRepo::new(&root, [("a.js", vec!["b.js"])]);
let a = Vc::upcast::<Box<dyn Module>>(MockModule::new(
root.join("a.js").unwrap(),
repo,
))
.to_resolved()
.await?;
let graph = SingleModuleGraph::new_with_entries(
GraphEntries::from_chunk_groups(vec![ChunkGroupEntry::Entry {
modules: vec![a],
heuristics: EntryHeuristics::default(),
}])
.resolved_cell(),
false,
false,
);
let layers = ModuleGraph::from_graphs(vec![graph], None)
.connect()
.iter_graphs()
.await?;
let layer = layers[0].connect().await?;
let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _ = layer.reverse_postorder_ranks([a]);
}))
.is_err();
Ok(Vc::cell(panicked))
}
assert!(*layer_panics_operation().read_strongly_consistent().await?);
Ok(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_traverse_edges_fixed_point_dedups_entries() {
run_graph_test(
......
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