Unverified Commit dcbe37ad authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

turbopack: merge chunk group lists in parallel in compute_merged_modules (#100237)

### What?

Merges the per-chunk `lists_reverse_indices` and
`intra_group_references_rev` maps of `compute_merged_modules` in
parallel, instead of entry by entry on one thread.

This is the second of three stacked PRs; it is based on #100236.
1. intern bitmaps (#100236)
2. parallel merge of the chunk group lists (this PR)
3. reconciliation shortcuts (#100238)

### Why?

After `map chunk groups`, the per-chunk results were folded into one map
with `entry(key).or_default().extend(set)` on a single thread. On the
bench app below that is ~19.1 M list occurrences, merged in a 1.7 s step
on one core.

### How?

New private helper `merge_index_maps_of_sets(parts, shard_count)`:
- **Split:** in parallel, each part is split into shards by the high
bits of the key's FxHash (`(hash as u128 * shard_count as u128) >> 64`).
Each key's position (part index, index in part) is recorded.
- **Merge:** in parallel, each shard merges its buckets in part order.
The first set of a key is moved instead of copied, and later sets extend
it.
- **Order:** the shard results are concatenated and stably sorted by
each key's first position. Each shard's output is already sorted by
position, so the stable sort merges those runs. Positions are unique, so
stability doesn't change the result.
- **One shard:** when `shard_count` is 0 or 1, the parts are merged
serially into the first part instead: it reserves the remaining parts'
lengths, moves sets for new keys and extends existing ones. No
bucketing, regrouping, parallel work or sort.

The result is exactly that of the serial merge:
- keys appear in order of first appearance;
- each key's set is extended part by part, with the same deduplication.

The shard count is `turbo_tasks::parallel::available_parallelism()`.

The gain comes from parallelizing and from moving first sets instead of
copying them; I didn't measure the two separately.

### Results

Same setup as #100236:
- **Bench app:** `bench/nested-deps-app-router-many-pages`.
- **Builds:** cold `next build` at 32 CPUs, with release binaries built
at the base commit with #100236, and with #100236 plus this change.
- **Rounds:** 1 warm-up per arm, then 4 rounds in alternating order.
- **Phase times:** from the `overview` light trace.

These numbers are for the first commit of this PR (`2a3dd855`):

| Metric (s) | #100236 median | this PR median | Median paired change |
Faster in |
|---|---:|---:|---:|---:|
| Wall | 49.62 | 48.43 | −2.9% | 3/4 |
| "Compiled in" | 30.10 | 28.60 | −6.1% | 4/4 |
| `compute merged modules` | 4.12 | 2.42 | −40.0% | 4/4 |
| `map chunk groups` | 0.45 | 0.47 | +3.4% | 2/4 |
| `merging chunk group lists` | 1.71 | 0.11 | −93.8% | 4/4 |
| `reconciliation` | 0.92 | 1.00 | +7.0% | 1/4 |

<details><summary>Per round (#100236 → this PR)</summary>

| Round | Order | Wall | "Compiled in" | `compute merged modules` | `map
chunk groups` | `merging chunk group lists` | `reconciliation` |
|---|---|---:|---:|---:|---:|---:|---:|
| 1 | #100236 first | 49.75 → 50.68 | 30.80 → 28.70 | 4.15 → 2.37 | 0.45
→ 0.45 | 1.89 → 0.10 | 0.94 → 0.99 |
| 2 | this PR first | 50.25 → 48.27 | 30.10 → 28.70 | 4.08 → 2.58 | 0.46
→ 0.49 | 1.69 → 0.11 | 1.08 → 1.06 |
| 3 | #100236 first | 49.22 → 47.18 | 30.00 → 27.80 | 4.17 → 2.36 | 0.58
→ 0.44 | 1.72 → 0.10 | 0.91 → 1.01 |
| 4 | this PR first | 49.49 → 48.60 | 30.10 → 28.50 | 3.91 → 2.46 | 0.45
→ 0.49 | 1.66 → 0.11 | 0.91 → 0.98 |

</details>

- **`reconciliation`:** it came out about 7% slower (0.92 → 1.00 s). It
runs unchanged code, so this may be the different memory layout of the
merged map, or noise. The next PR in the stack reduces it to ~0.25 s.
- **Limits:** one VM, one app, 4 rounds, and no significance test. Peak
memory of the transient buckets wasn't measured.
- **Output:** the `.next` output is identical to #100236's. Only the
per-build random preview-mode and server-action keys differ.

#### Second commit: serial merge for one shard, stable sort

Measured against the first commit (`2a3dd855`) with
`TURBO_TASKS_AVAILABLE_PARALLELISM=1`, so one shard. The process still
ran on CPUs 0–31, and only Turbo Tasks parallelism was limited. 1
warm-up per arm, then 2 rounds in alternating order:

| `merging chunk group lists` (s) | Round 1 | Round 2 |
|---|---:|---:|
| first commit | 0.362 | 0.366 |
| with second commit | 0.344 | 0.373 |

- **One shard:** no measurable difference at this sample size. The
serial path mainly drops the bucketing, sort and runtime work for one
shard; it doesn't show a speedup here.
- **Stable sort:** no separate timing A/B at 32 CPUs.
- **Output:** the 32-CPU `.next` output is identical to the first
commit's. Only the per-build random preview-mode and server-action keys
differ.

### Verification

- **Unit tests:** they compare `merge_index_maps_of_sets` with the
serial merge, including key order and the order within each set.
- **Inputs:** 20 deterministic random inputs with overlapping keys,
values repeated across parts and empty parts.
  - **Shard counts:** 0, 1, 3 and 64, plus empty input for 0, 1 and 4.
- **No-runtime test:** a plain `#[test]` runs the one-shard path without
a Tokio runtime. It failed before the serial path existed.
- `cargo test -p turbopack-core`
- `cargo test -p turbopack-tests --test snapshot --test execution --
scope_hoisting` (2 snapshot and 52 execution fixtures, with unchanged
snapshots)
- `cargo clippy -p turbopack-core --all-targets -- -D warnings`

<!-- NEXT_JS_LLM -->


<!-- fleet d8fee2f9-18db-4936-b59a-f8417b8f4bbc -->

---------
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 c8e811ee
use std::{cmp::Reverse, collections::hash_map::Entry, hash::Hash};
use std::{
cmp::Reverse,
collections::hash_map::Entry,
hash::{BuildHasher, Hash},
};
use anyhow::{Context, Result, bail};
use rustc_hash::{FxHashMap, FxHashSet};
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
use tracing::Instrument;
use turbo_tasks::{FxIndexMap, FxIndexSet, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc};
......@@ -87,6 +91,95 @@ fn intern_bitmaps<'a, K: Eq + Hash>(
(result, ids.len())
}
/// Merges maps of sets into one map. The result is exactly what extending an empty map with each
/// part in order gives (`result.entry(key).or_default().extend(set)`): keys in order of first
/// appearance, and each key's set extended part by part. Disjoint key shards are merged in
/// parallel, and the first set of each key is moved rather than copied. With a single shard, the
/// parts are merged serially into the first part instead.
fn merge_index_maps_of_sets<K, V>(
parts: Vec<FxIndexMap<K, FxIndexSet<V>>>,
shard_count: usize,
) -> FxIndexMap<K, FxIndexSet<V>>
where
K: Hash + Eq + Send + Sync,
V: Hash + Eq + Send + Sync,
{
/// Entries of one shard from one part, with each key's position (part index, index in part).
type Bucket<K, V> = Vec<((usize, usize), K, FxIndexSet<V>)>;
let shard_count = shard_count.max(1);
if shard_count == 1 {
let mut parts = parts.into_iter();
let Some(mut result) = parts.next() else {
return FxIndexMap::default();
};
let rest = parts.collect::<Vec<_>>();
result.reserve(rest.iter().map(|part| part.len()).sum());
for part in rest {
for (key, set) in part {
match result.entry(key) {
indexmap::map::Entry::Occupied(mut e) => e.get_mut().extend(set),
indexmap::map::Entry::Vacant(e) => {
e.insert(set);
}
}
}
}
return result;
}
// Use the high bits of the hash, so the keys of one shard don't all share the low bits that the
// per-shard hash tables use for bucket selection.
let shard_of =
|key: &K| ((FxBuildHasher.hash_one(key) as u128 * shard_count as u128) >> 64) as usize;
// Split every part into per-shard buckets.
let bucketed: Vec<Vec<Bucket<K, V>>> = turbo_tasks::parallel::map_collect_owned(
parts.into_iter().enumerate().collect::<Vec<_>>(),
|(part_idx, part)| {
let mut buckets: Vec<Bucket<K, V>> = (0..shard_count).map(|_| Vec::new()).collect();
for (i, (key, set)) in part.into_iter().enumerate() {
buckets[shard_of(&key)].push(((part_idx, i), key, set));
}
buckets
},
);
// Regroup by shard, keeping the part order.
let mut per_shard: Vec<Vec<Bucket<K, V>>> = (0..shard_count)
.map(|_| Vec::with_capacity(bucketed.len()))
.collect();
for buckets in bucketed {
for (shard, bucket) in buckets.into_iter().enumerate() {
per_shard[shard].push(bucket);
}
}
// Merge each shard. A key's first position is where the serial merge would insert it.
let merged: Vec<Bucket<K, V>> =
turbo_tasks::parallel::map_collect_owned(per_shard, |buckets| {
let mut map: FxIndexMap<K, ((usize, usize), FxIndexSet<V>)> = FxIndexMap::default();
for bucket in buckets {
for (pos, key, set) in bucket {
if let Some((_, existing)) = map.get_mut(&key) {
existing.extend(set);
} else {
map.insert(key, (pos, set));
}
}
}
map.into_iter()
.map(|(key, (pos, set))| (pos, key, set))
.collect::<Vec<_>>()
});
let mut all = merged.into_iter().flatten().collect::<Vec<_>>();
// Each shard's output is already sorted by position (keys are inserted on first sight, in
// position order), so a stable sort merges these runs instead of sorting from scratch.
// Positions are unique, so stability doesn't change the result.
all.sort_by_key(|(pos, _, _)| *pos);
all.into_iter().map(|(_, key, set)| (key, set)).collect()
}
/// Determine which modules can be merged together:
/// - if all chunks execute a sequence of modules in the same order, they can be merged together and
/// treated as one.
......@@ -304,7 +397,7 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
let mut lists_reverse_indices: FxIndexMap<
ResolvedVc<Box<dyn MergeableModule>>,
FxIndexSet<ListOccurrence>,
> = FxIndexMap::default();
>;
// Once we do the reconciliation below, we need to insert new lists, but the lists are per
// chunk group, so we put them into this one.
......@@ -322,10 +415,10 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
// A map of all references between modules with the same bitmap. These are only the
// references relevant for execution (ignoring cycles), to find the entries of a group.
#[allow(clippy::type_complexity)]
let mut intra_group_references_rev: FxIndexMap<
let intra_group_references_rev: FxIndexMap<
ResolvedVc<Box<dyn Module>>,
FxIndexSet<ResolvedVc<Box<dyn Module>>>,
> = FxIndexMap::default();
>;
{
struct ChunkGroupResult {
......@@ -463,17 +556,10 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
drop(span);
let _span = tracing::info_span!("merging chunk group lists").entered();
lists_reverse_indices
.reserve_exact(result.iter().map(|r| r.lists_reverse_indices.len()).sum());
intra_group_references_rev.reserve_exact(
result
.iter()
.map(|r| r.intra_group_references_rev.len())
.sum(),
);
lists = vec![Default::default(); chunk_group_info.chunk_groups.len() + 1];
LISTS_COMMON_IDX = result.len();
let mut reverse_index_parts = Vec::with_capacity(result.len());
let mut intra_group_references_rev_parts = Vec::with_capacity(result.len());
for ChunkGroupResult {
first_chunk_group_idx,
list_lists: result_lists,
......@@ -485,19 +571,13 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
first_chunk_group_idx..(first_chunk_group_idx + result_lists.len()),
result_lists,
);
for (module, occurrences) in result_lists_reverse_indices {
lists_reverse_indices
.entry(module)
.or_default()
.extend(occurrences);
}
for (module, occurrences) in result_intra_group_references_rev {
intra_group_references_rev
.entry(module)
.or_default()
.extend(occurrences);
}
reverse_index_parts.push(result_lists_reverse_indices);
intra_group_references_rev_parts.push(result_intra_group_references_rev);
}
let shard_count = turbo_tasks::parallel::available_parallelism().map_or(1, |n| n.get());
lists_reverse_indices = merge_index_maps_of_sets(reverse_index_parts, shard_count);
intra_group_references_rev =
merge_index_maps_of_sets(intra_group_references_rev_parts, shard_count);
}
drop(inner_span);
......@@ -857,4 +937,115 @@ mod tests {
all.dedup();
assert_eq!(all, vec![0, 1, 2]);
}
/// The serial merge that `merge_index_maps_of_sets` replaces.
fn serial_merge(
parts: Vec<FxIndexMap<u32, FxIndexSet<u32>>>,
) -> FxIndexMap<u32, FxIndexSet<u32>> {
let mut result: FxIndexMap<u32, FxIndexSet<u32>> = FxIndexMap::default();
for part in parts {
for (key, set) in part {
result.entry(key).or_default().extend(set);
}
}
result
}
/// Deterministic pseudo-random parts with overlapping keys, values repeated across parts and
/// some empty parts.
fn generate_parts(seed: u64, part_count: usize) -> Vec<FxIndexMap<u32, FxIndexSet<u32>>> {
let mut state = seed;
let mut next = move |bound: u32| {
// xorshift64
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state % bound as u64) as u32
};
(0..part_count)
.map(|_| {
let mut part: FxIndexMap<u32, FxIndexSet<u32>> = FxIndexMap::default();
if next(4) == 0 {
return part;
}
for _ in 0..next(40) {
let set = part.entry(next(50)).or_default();
for _ in 0..next(6) {
set.insert(next(20));
}
}
part
})
.collect()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn merge_index_maps_of_sets_matches_serial_merge() {
for seed in 1..=20 {
for shard_count in [0, 1, 3, 64] {
let parts = generate_parts(seed, 1 + seed as usize % 9);
let expected = serial_merge(parts.clone());
let actual = merge_index_maps_of_sets(parts, shard_count);
// Compare as vectors, so the key order and each set's order are checked too.
assert_eq!(
actual
.iter()
.map(|(k, v)| (*k, v.iter().copied().collect::<Vec<_>>()))
.collect::<Vec<_>>(),
expected
.iter()
.map(|(k, v)| (*k, v.iter().copied().collect::<Vec<_>>()))
.collect::<Vec<_>>(),
"seed {seed}, shard count {shard_count}"
);
}
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn merge_index_maps_of_sets_handles_empty_input() {
for shard_count in [0, 1, 4] {
let parts: Vec<FxIndexMap<u32, FxIndexSet<u32>>> = vec![Default::default(); 3];
assert!(merge_index_maps_of_sets(parts, shard_count).is_empty());
assert!(
merge_index_maps_of_sets(
Vec::<FxIndexMap<u32, FxIndexSet<u32>>>::new(),
shard_count
)
.is_empty()
);
}
}
/// With one shard the merge is serial, so it needs no runtime for parallelism.
#[test]
fn merge_index_maps_of_sets_single_shard_is_serial() {
for seed in 1..=20 {
for shard_count in [0, 1] {
let parts = generate_parts(seed, 1 + seed as usize % 9);
let expected = serial_merge(parts.clone());
let actual = merge_index_maps_of_sets(parts, shard_count);
assert_eq!(
actual
.iter()
.map(|(k, v)| (*k, v.iter().copied().collect::<Vec<_>>()))
.collect::<Vec<_>>(),
expected
.iter()
.map(|(k, v)| (*k, v.iter().copied().collect::<Vec<_>>()))
.collect::<Vec<_>>(),
"seed {seed}, shard count {shard_count}"
);
}
}
for shard_count in [0, 1] {
assert!(
merge_index_maps_of_sets(
Vec::<FxIndexMap<u32, FxIndexSet<u32>>>::new(),
shard_count
)
.is_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