Skip to main content

turbopack_core/module_graph/
module_batches.rs

1use std::{
2    collections::{VecDeque, hash_map::Entry},
3    hash::BuildHasherDefault,
4    mem::take,
5};
6
7use anyhow::{Context, Result, bail};
8use bincode::{Decode, Encode};
9use either::Either;
10use petgraph::graph::{DiGraph, EdgeIndex, NodeIndex};
11use rustc_hash::{FxHashMap, FxHashSet, FxHasher};
12use serde::{Deserialize, Serialize};
13use tracing::Instrument;
14use turbo_prehash::BuildHasherExt;
15use turbo_tasks::{
16    FxIndexMap, FxIndexSet, NonLocalValue, ResolvedVc, TaskInput, TryJoinIterExt, ValueToString,
17    Vc, trace::TraceRawVcs, turbobail,
18};
19
20use crate::{
21    chunk::{ChunkableModule, ChunkingType},
22    module::Module,
23    module_graph::{
24        GraphTraversalAction, ModuleGraph,
25        chunk_group_info::{ChunkGroupInfo, ChunkGroupKey, RoaringBitmapWrapper},
26        module_batch::{ModuleBatch, ModuleBatchGroup, ModuleOrBatch},
27        traced_di_graph::{TracedDiGraph, iter_neighbors_rev},
28    },
29};
30#[turbo_tasks::value]
31#[derive(Debug, Clone, Default, TaskInput, Hash)]
32pub struct BatchingConfig {
33    /// Use a heuristic based on the module path to create batches. It aims for batches of a good
34    /// size.
35    pub use_heuristic: bool,
36}
37
38#[turbo_tasks::value_impl]
39impl BatchingConfig {
40    #[turbo_tasks::function]
41    pub fn new(config: BatchingConfig) -> Vc<Self> {
42        config.cell()
43    }
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize, TraceRawVcs, NonLocalValue)]
47pub struct ModuleBatchesGraphEdge {
48    pub ty: ChunkingType,
49    pub module: Option<ResolvedVc<Box<dyn Module>>>,
50}
51
52#[derive(Debug, Clone, TraceRawVcs, NonLocalValue, Encode, Decode)]
53struct EntriesList(
54    #[bincode(with = "turbo_bincode::indexset")] pub FxIndexSet<ResolvedVc<Box<dyn Module>>>,
55);
56
57#[turbo_tasks::value(cell = "new", eq = "manual")]
58pub struct ModuleBatchesGraph {
59    graph: TracedDiGraph<ModuleOrBatch, ModuleBatchesGraphEdge>,
60
61    // NodeIndex isn't necessarily stable (because of swap_remove), but we never remove nodes.
62    //
63    // HashMaps have nondeterministic order, but this map is only used for lookups and not
64    // iteration.
65    //
66    // This contains Vcs, but they are already contained in the graph, so no need to trace this.
67    #[turbo_tasks(trace_ignore)]
68    #[bincode(with_serde)]
69    entries: FxHashMap<ResolvedVc<Box<dyn Module>>, NodeIndex>,
70    batch_groups: FxHashMap<ModuleOrBatch, ResolvedVc<ModuleBatchGroup>>,
71
72    /// For chunk groups where the postorder of entries is different than the order of the
73    /// `ChunkGroup::entries()` this contains Some with the postorder list of entries of that chunk
74    /// group. The index in this list corresponds to the index in the
75    /// chunk_group_info.chunk_groups.
76    ordered_entries: Vec<Option<EntriesList>>,
77}
78
79impl ModuleBatchesGraph {
80    pub async fn get_entry_index(&self, entry: ResolvedVc<Box<dyn Module>>) -> Result<NodeIndex> {
81        let Some(entry) = self.entries.get(&entry) else {
82            if cfg!(debug_assertions) {
83                let possible_entries = format!(
84                    "{:#?}",
85                    self.entries
86                        .keys()
87                        .map(|e| e.ident().to_string())
88                        .try_join()
89                        .await?
90                );
91                turbobail!(
92                    "Entry {} is not in graph (possible entries: {})",
93                    entry.ident(),
94                    possible_entries
95                );
96            } else {
97                bail!("Entry is not in graph");
98            }
99        };
100        Ok(*entry)
101    }
102
103    pub fn get_ordered_entries<'l>(
104        &'l self,
105        chunk_group_info: &'l ChunkGroupInfo,
106        idx: usize,
107    ) -> impl Iterator<Item = ResolvedVc<Box<dyn Module>>> + 'l {
108        if let Some(EntriesList(ordered_entries)) = self
109            .ordered_entries
110            .get(idx)
111            .as_ref()
112            .and_then(|o| o.as_ref())
113        {
114            if let Some(chunk_group) = chunk_group_info.chunk_groups.get_index(idx) {
115                debug_assert_eq!(ordered_entries.len(), chunk_group.entries_count());
116            }
117            Either::Left(Either::Left(ordered_entries.iter().copied()))
118        } else if let Some(chunk_group) = chunk_group_info.chunk_groups.get_index(idx) {
119            Either::Right(chunk_group.entries())
120        } else {
121            Either::Left(Either::Right(std::iter::empty()))
122        }
123    }
124
125    pub fn get_batch_group(
126        &self,
127        module_or_batch: &ModuleOrBatch,
128    ) -> Option<ResolvedVc<ModuleBatchGroup>> {
129        self.batch_groups.get(module_or_batch).copied()
130    }
131
132    pub async fn get_entry(&self, entry: ResolvedVc<Box<dyn Module>>) -> Result<ModuleOrBatch> {
133        let entry = self.get_entry_index(entry).await?;
134        Ok(*self.graph.node_weight(entry).unwrap())
135    }
136
137    // Clippy complains but there's a type error without the bound
138    #[allow(clippy::implied_bounds_in_impls)]
139    /// Traverses all reachable edges in dfs order. The preorder visitor can be used to
140    /// forward state down the graph, and to skip subgraphs
141    ///
142    /// Use this to collect batches/modules in evaluation order.
143    ///
144    /// Target nodes can be revisited (once per incoming edge).
145    /// Edges are traversed in normal order, so should correspond to reference order.
146    ///
147    /// * `entries` - The entry modules to start the traversal from
148    /// * `state` - The state to be passed to the visitors
149    /// * `visit_preorder` - Called before visiting the children of a node.
150    ///    - Receives: (originating &ModuleBatchesGraphNode, edge &ChunkingType), target
151    ///      &ModuleBatchesGraphNode, state &S
152    ///    - Can return [GraphTraversalAction]s to control the traversal
153    /// * `visit_postorder` - Called after visiting the children of a node. Return
154    ///    - Receives: (originating &ModuleBatchesGraphNode, edge &ChunkingType), target
155    ///      &ModuleBatchesGraphNode, state &S
156    pub fn traverse_edges_from_entries_dfs<'a, S>(
157        &'a self,
158        entries: impl IntoIterator<
159            Item = NodeIndex,
160            IntoIter = impl Iterator<Item = NodeIndex> + DoubleEndedIterator,
161        >,
162        state: &mut S,
163        mut visit_preorder: impl FnMut(
164            Option<(&'a ModuleOrBatch, &'a ModuleBatchesGraphEdge)>,
165            &'a ModuleOrBatch,
166            &mut S,
167        ) -> Result<GraphTraversalAction>,
168        mut visit_postorder: impl FnMut(
169            Option<(&'a ModuleOrBatch, &'a ModuleBatchesGraphEdge)>,
170            &'a ModuleOrBatch,
171            &mut S,
172        ),
173    ) -> Result<()> {
174        let graph = &self.graph;
175
176        enum ReverseDFSPass {
177            Visit,
178            ExpandAndVisit,
179        }
180
181        let entries = entries.into_iter();
182        #[allow(clippy::type_complexity)] // This is a temporary internal structure
183        let mut stack: Vec<(ReverseDFSPass, Option<(NodeIndex, EdgeIndex)>, NodeIndex)> = entries
184            .rev()
185            .map(|e| (ReverseDFSPass::ExpandAndVisit, None, e))
186            .collect();
187        let mut expanded = FxHashSet::default();
188        while let Some((pass, parent, current)) = stack.pop() {
189            let parent_arg = parent.map(|(node, edge)| {
190                (
191                    graph.node_weight(node).unwrap(),
192                    graph.edge_weight(edge).unwrap(),
193                )
194            });
195            match pass {
196                ReverseDFSPass::Visit => {
197                    let current_node = graph.node_weight(current).unwrap();
198                    visit_postorder(parent_arg, current_node, state);
199                }
200                ReverseDFSPass::ExpandAndVisit => {
201                    let current_node = graph.node_weight(current).unwrap();
202                    let action = visit_preorder(parent_arg, current_node, state)?;
203                    if action == GraphTraversalAction::Exclude {
204                        continue;
205                    }
206                    stack.push((ReverseDFSPass::Visit, parent, current));
207                    if action == GraphTraversalAction::Continue && expanded.insert(current) {
208                        stack.extend(iter_neighbors_rev(graph, current).map(|(edge, child)| {
209                            (ReverseDFSPass::ExpandAndVisit, Some((current, edge)), child)
210                        }));
211                    }
212                }
213            }
214        }
215
216        Ok(())
217    }
218}
219
220type PreBatchIndex = usize;
221
222#[derive(Hash, PartialEq, Eq, Clone, Debug)]
223enum PreBatchItem {
224    ParallelModule(ResolvedVc<Box<dyn Module>>),
225    ParallelReference(PreBatchIndex),
226    NonParallelEdge(ChunkingType, ResolvedVc<Box<dyn Module>>),
227}
228
229struct PreBatch {
230    items: FxIndexSet<PreBatchItem>,
231    chunk_groups: RoaringBitmapWrapper,
232}
233
234impl PreBatch {
235    fn new(chunk_groups: RoaringBitmapWrapper) -> Self {
236        Self {
237            items: FxIndexSet::default(),
238            chunk_groups,
239        }
240    }
241}
242
243struct TraversalState<'l> {
244    items: Vec<PreBatchItem>,
245    this: &'l mut PreBatches,
246}
247
248struct PreBatches {
249    boundary_modules: FxHashSet<ResolvedVc<Box<dyn Module>>>,
250    batches: Vec<PreBatch>,
251    entries: FxHashMap<ResolvedVc<Box<dyn Module>>, PreBatchIndex>,
252    single_module_entries: FxIndexSet<ResolvedVc<Box<dyn Module>>>,
253}
254
255impl PreBatches {
256    fn new() -> Self {
257        Self {
258            boundary_modules: FxHashSet::default(),
259            batches: Vec::new(),
260            entries: FxHashMap::default(),
261            single_module_entries: FxIndexSet::default(),
262        }
263    }
264
265    fn ensure_pre_batch_for_module(
266        &mut self,
267        module: ResolvedVc<Box<dyn Module>>,
268        module_chunk_groups: &FxHashMap<ResolvedVc<Box<dyn Module>>, RoaringBitmapWrapper>,
269        queue: &mut VecDeque<(ResolvedVc<Box<dyn Module>>, PreBatchIndex)>,
270    ) -> Result<PreBatchIndex> {
271        Ok(match self.entries.entry(module) {
272            Entry::Vacant(e) => {
273                let index = self.batches.len();
274                queue.push_back((module, index));
275                let chunk_groups = module_chunk_groups
276                    .get(&module)
277                    .context("all modules need to have chunk group info")?;
278                let batch = PreBatch::new((*chunk_groups).clone());
279                self.batches.push(batch);
280                e.insert(index);
281                index
282            }
283            Entry::Occupied(e) => *e.get(),
284        })
285    }
286
287    async fn get_pre_batch_items(
288        &mut self,
289        entry: ResolvedVc<Box<dyn Module>>,
290        module_chunk_groups: &FxHashMap<ResolvedVc<Box<dyn Module>>, RoaringBitmapWrapper>,
291        module_graph: &ModuleGraph,
292        queue: &mut VecDeque<(ResolvedVc<Box<dyn Module>>, PreBatchIndex)>,
293    ) -> Result<Vec<PreBatchItem>> {
294        let mut state = TraversalState {
295            items: Vec::new(),
296            this: self,
297        };
298        let mut visited = FxHashSet::default();
299        module_graph.traverse_edges_dfs(
300            std::iter::once(entry),
301            &mut state,
302            |parent_info, node, state| {
303                let ty = parent_info.map_or(
304                    &ChunkingType::Parallel {
305                        inherit_async: false,
306                        hoisted: false,
307                    },
308                    |(_, ty)| &ty.chunking_type,
309                );
310                let module = node;
311                if !ty.is_parallel() {
312                    state.items.push(PreBatchItem::NonParallelEdge(
313                        ty.without_inherit_async(),
314                        module,
315                    ));
316                    return Ok(GraphTraversalAction::Exclude);
317                }
318                if visited.insert(module) {
319                    if parent_info.is_some() && state.this.boundary_modules.contains(&module) {
320                        let idx = state.this.ensure_pre_batch_for_module(
321                            module,
322                            module_chunk_groups,
323                            queue,
324                        )?;
325                        state.items.push(PreBatchItem::ParallelReference(idx));
326                        return Ok(GraphTraversalAction::Exclude);
327                    }
328                    Ok(GraphTraversalAction::Continue)
329                } else {
330                    Ok(GraphTraversalAction::Exclude)
331                }
332            },
333            |_, node, state| {
334                let item = PreBatchItem::ParallelModule(node);
335                state.items.push(item);
336                Ok(())
337            },
338        )?;
339        Ok(state.items)
340    }
341}
342
343pub async fn compute_module_batches(
344    module_graph: Vc<ModuleGraph>,
345    _config: &BatchingConfig,
346) -> Result<Vc<ModuleBatchesGraph>> {
347    let outer_span = tracing::info_span!(
348        "compute module batches",
349        initial_pre_batch_items = tracing::field::Empty,
350        initial_pre_batches = tracing::field::Empty,
351        extracted_shared_items = tracing::field::Empty,
352        batches = tracing::field::Empty,
353        modules = tracing::field::Empty,
354        edges = tracing::field::Empty
355    );
356    let span = outer_span.clone();
357    async move {
358        let chunk_group_info = module_graph.chunk_group_info().await?;
359        let module_chunk_groups = chunk_group_info.module_chunk_groups.await?;
360        let module_graph = module_graph.await?;
361
362        let mut pre_batches = PreBatches::new();
363
364        // Walk the module graph and mark all modules that are boundary modules (referenced from a
365        // different chunk group bitmap)
366        module_graph.traverse_edges_unordered(|parent, node| {
367            if let Some((parent, ty)) = parent {
368                let std::collections::hash_set::Entry::Vacant(entry) =
369                    pre_batches.boundary_modules.entry(node)
370                else {
371                    // Already a boundary module, can skip check
372                    return Ok(());
373                };
374                if ty.chunking_type.is_parallel() {
375                    let parent_chunk_groups = module_chunk_groups
376                        .get(&parent)
377                        .context("all modules need to have chunk group info")?;
378                    let chunk_groups = module_chunk_groups
379                        .get(&node)
380                        .context("all modules need to have chunk group info")?;
381                    if parent_chunk_groups != chunk_groups {
382                        // This is a boundary module
383                        entry.insert();
384                    }
385                } else {
386                    entry.insert();
387                }
388            }
389            Ok(())
390        })?;
391
392        // All entries are boundary modules too
393        for chunk_group in &chunk_group_info.chunk_groups {
394            for entry in chunk_group.entries() {
395                pre_batches.boundary_modules.insert(entry);
396            }
397        }
398
399        // Pre batches would be incorrect with cycles, so we need to opt-out of pre batches for
400        // cycles that include boundary modules
401        module_graph.traverse_cycles(
402            |ref_data| ref_data.chunking_type.is_parallel(),
403            |cycle| {
404                if cycle.len() > 1
405                    && cycle
406                        .iter()
407                        .any(|node| pre_batches.boundary_modules.contains(node))
408                {
409                    pre_batches
410                        .boundary_modules
411                        .extend(cycle.iter().map(|node| **node));
412                }
413                Ok(())
414            },
415        )?;
416
417        let mut queue: VecDeque<(ResolvedVc<Box<dyn Module>>, PreBatchIndex)> = VecDeque::new();
418
419        let mut chunk_group_indices_with_merged_children = FxHashSet::default();
420
421        // Start with the entries
422        for chunk_group in &chunk_group_info.chunk_groups {
423            for entry in chunk_group.entries() {
424                pre_batches.ensure_pre_batch_for_module(entry, &module_chunk_groups, &mut queue)?;
425            }
426            if let Some(parent) = chunk_group.get_merged_parent() {
427                chunk_group_indices_with_merged_children.insert(parent);
428            }
429        }
430
431        let mut initial_pre_batch_items = 0;
432        // Fill all pre batches
433        while let Some((chunkable_module, idx)) = queue.pop_front() {
434            let items = pre_batches
435                .get_pre_batch_items(
436                    chunkable_module,
437                    &module_chunk_groups,
438                    &module_graph,
439                    &mut queue,
440                )
441                .await?;
442            initial_pre_batch_items += items.len();
443            let batch = &mut pre_batches.batches[idx];
444            batch.items.extend(items);
445        }
446        span.record("initial_pre_batch_items", initial_pre_batch_items);
447        span.record("initial_pre_batches", pre_batches.batches.len());
448
449        // Figure out the order of all merged groups
450        let mut ordered_entries: Vec<Option<EntriesList>> =
451            vec![None; chunk_group_info.chunk_groups.len()];
452        for (i, chunk_group) in chunk_group_info.chunk_groups.iter().enumerate() {
453            if !chunk_group_indices_with_merged_children.contains(&i) {
454                continue;
455            }
456            let mut merged_modules: FxHashMap<ChunkingType, FxIndexSet<_>> = FxHashMap::default();
457            let mut stack = ordered_entries[i]
458                .as_ref()
459                .map_or_else(
460                    || Either::Left(chunk_group.entries()),
461                    |v| Either::Right(v.0.iter().copied()),
462                )
463                .map(|module| {
464                    let idx = *pre_batches
465                        .entries
466                        .get(&module)
467                        .context("could not prebatch for module")?;
468                    Ok((idx, 0))
469                })
470                .collect::<Result<Vec<_>>>()?;
471            stack.reverse();
472            let mut visited = FxHashSet::default();
473            while let Some((idx, mut pos)) = stack.pop() {
474                let batch = &pre_batches.batches[idx];
475                while let Some(item) = batch.items.get_index(pos) {
476                    match item {
477                        PreBatchItem::ParallelModule(_) => {}
478                        PreBatchItem::ParallelReference(other_idx) => {
479                            if visited.insert(*other_idx) {
480                                stack.push((idx, pos + 1));
481                                stack.push((*other_idx, 0));
482                                break;
483                            }
484                        }
485                        PreBatchItem::NonParallelEdge(chunking_type, module) => {
486                            if chunking_type.is_merged() {
487                                merged_modules
488                                    .entry(chunking_type.clone())
489                                    .or_default()
490                                    .insert(*module);
491                            }
492                        }
493                    }
494                    pos += 1;
495                }
496            }
497            if !merged_modules.is_empty() {
498                for (ty, merged_modules) in merged_modules {
499                    let chunk_group_key = match ty {
500                        ChunkingType::Isolated {
501                            merge_tag: Some(merge_tag),
502                            ..
503                        } => ChunkGroupKey::IsolatedMerged {
504                            parent: i.into(),
505                            merge_tag: merge_tag.clone(),
506                        },
507                        ChunkingType::Shared {
508                            merge_tag: Some(merge_tag),
509                            ..
510                        } => ChunkGroupKey::SharedMerged {
511                            parent: i.into(),
512                            merge_tag: merge_tag.clone(),
513                        },
514                        _ => unreachable!(),
515                    };
516                    let idx = chunk_group_info
517                        .chunk_group_keys
518                        .get_index_of(&chunk_group_key)
519                        .context("could not find chunk group key for merged chunk group")?;
520                    ordered_entries[idx] = Some(EntriesList(merged_modules));
521                }
522            }
523        }
524
525        // Create a map of parallel module to the batches they are contained in.
526        let mut parallel_module_to_pre_batch: FxIndexMap<_, Vec<PreBatchIndex>> =
527            FxIndexMap::default();
528
529        // Fill the map and also fill up the single_module_entries
530        for (idx, pre_batch) in pre_batches.batches.iter().enumerate() {
531            for item in &pre_batch.items {
532                match item {
533                    PreBatchItem::ParallelModule(module) => {
534                        parallel_module_to_pre_batch
535                            .entry(*module)
536                            .or_default()
537                            .push(idx);
538                    }
539                    PreBatchItem::NonParallelEdge(_, module) => {
540                        if !pre_batches.entries.contains_key(module) {
541                            pre_batches.single_module_entries.insert(*module);
542                        }
543                    }
544                    PreBatchItem::ParallelReference(_) => {}
545                }
546            }
547        }
548
549        // We never want a module to occur in multiple batches.
550
551        let mut extracted_shared_items = 0;
552        // Extract shared modules into separate batches
553        for i in 0..parallel_module_to_pre_batch.len() {
554            let (&module, batches) = parallel_module_to_pre_batch
555                .get_index(i)
556                .context("could not find parallel module to pre batch index")?;
557            if batches.len() > 1 {
558                // Create a new batch for the shared modules
559                let batches_with_item_index = batches
560                    .iter()
561                    .map(|&idx| {
562                        let batch_items = &pre_batches.batches[idx].items;
563                        let item_idx = batch_items
564                            .get_index_of(&PreBatchItem::ParallelModule(module))
565                            .context("could not find batch item index for parallel module")?;
566                        Ok((idx, item_idx))
567                    })
568                    .collect::<Result<Vec<_>>>()?;
569                let mut selected_items = 1;
570                fn get_item_at(
571                    pre_batches: &PreBatches,
572                    batch_idx: PreBatchIndex,
573                    item_idx: usize,
574                ) -> Option<&PreBatchItem> {
575                    pre_batches.batches[batch_idx].items.get_index(item_idx)
576                }
577                // Select more matching items that are equal in all batches that contain the shared
578                // module(s)
579                loop {
580                    if let Some(PreBatchItem::ParallelModule(next_module)) = get_item_at(
581                        &pre_batches,
582                        batches_with_item_index[0].0,
583                        batches_with_item_index[0].1 + selected_items,
584                    ) && parallel_module_to_pre_batch
585                        .get(next_module)
586                        .context("could not find pre batch for parallel module")?
587                        .len()
588                        == batches.len()
589                        && batches_with_item_index[1..]
590                            .iter()
591                            .all(|&(batch_idx, item_idx)| {
592                                get_item_at(&pre_batches, batch_idx, item_idx + selected_items)
593                                    == Some(&PreBatchItem::ParallelModule(*next_module))
594                            })
595                    {
596                        selected_items += 1;
597                        continue;
598                    }
599                    break;
600                }
601                extracted_shared_items += selected_items;
602
603                // Check if a batch is completely selected. In that case we can replace all other
604                // occurrences with a reference to that batch
605                let exact_match = batches_with_item_index
606                    .iter()
607                    .find(|&&(batch_idx, item_idx)| {
608                        item_idx == 0
609                            && pre_batches.batches[batch_idx].items.len() == selected_items
610                    });
611                if let Some(&(exact_match, _)) = exact_match {
612                    // Replace all other occurrences with a reference to the exact match
613                    for &(batch_index, item_start) in batches_with_item_index.iter() {
614                        if batch_index != exact_match {
615                            pre_batches.batches[batch_index].items.splice(
616                                item_start..item_start + selected_items,
617                                std::iter::once(PreBatchItem::ParallelReference(exact_match)),
618                            );
619                        }
620                    }
621                    for item in pre_batches.batches[exact_match].items.iter() {
622                        if let PreBatchItem::ParallelModule(module) = item {
623                            parallel_module_to_pre_batch
624                                .get_mut(module)
625                                .context("could not find pre batch for parallel module")?
626                                .clear();
627                        }
628                    }
629                } else {
630                    // Create a new batch of the shared part and replace all occurrences with a
631                    // reference to that batch
632                    let first_batch_index = batches_with_item_index[0].0;
633                    let first_batch_item_index = batches_with_item_index[0].1;
634                    let new_batch_index = pre_batches.batches.len();
635                    let mut new_batch =
636                        PreBatch::new(pre_batches.batches[first_batch_index].chunk_groups.clone());
637                    new_batch
638                        .items
639                        .extend(pre_batches.batches[first_batch_index].items.splice(
640                            first_batch_item_index..first_batch_item_index + selected_items,
641                            std::iter::once(PreBatchItem::ParallelReference(new_batch_index)),
642                        ));
643                    for item in new_batch.items.iter() {
644                        if let PreBatchItem::ParallelModule(module) = item {
645                            parallel_module_to_pre_batch
646                                .get_mut(module)
647                                .context("could not find pre batch for parallel module")?
648                                .clear();
649                        }
650                    }
651                    pre_batches.batches.push(new_batch);
652                    for &(batch_index, item_start) in batches_with_item_index[1..].iter() {
653                        pre_batches.batches[batch_index].items.splice(
654                            item_start..item_start + selected_items,
655                            std::iter::once(PreBatchItem::ParallelReference(new_batch_index)),
656                        );
657                    }
658                }
659            }
660        }
661        span.record("extracted_shared_items", extracted_shared_items);
662
663        // Now every module is only in one batch
664
665        let mut edges_count = 0;
666
667        // Since batches can only have references followed by a list of parallel chunkable modules,
668        // we need to split batches that have modules before references.
669        for i in 0..pre_batches.batches.len() {
670            let items = take(&mut pre_batches.batches[i].items);
671            let mut new_items =
672                FxIndexSet::with_capacity_and_hasher(items.len(), Default::default());
673            enum Mode {
674                ParallelChunkableModule,
675                Other,
676            }
677            let mut mode = Mode::Other;
678            for item in items {
679                let chunkable_module = if let PreBatchItem::ParallelModule(module) = &item {
680                    ResolvedVc::try_downcast::<Box<dyn ChunkableModule>>(*module)
681                } else {
682                    None
683                };
684                let item = if let PreBatchItem::ParallelModule(module) = item {
685                    if chunkable_module.is_some() {
686                        PreBatchItem::ParallelModule(module)
687                    } else {
688                        pre_batches.single_module_entries.insert(module);
689                        PreBatchItem::NonParallelEdge(
690                            ChunkingType::Parallel {
691                                inherit_async: false,
692                                hoisted: false,
693                            },
694                            module,
695                        )
696                    }
697                } else {
698                    item
699                };
700                match (&mode, chunkable_module) {
701                    (_, Some(_)) => {
702                        mode = Mode::ParallelChunkableModule;
703                        new_items.insert(item);
704                    }
705                    (Mode::Other, _) => {
706                        edges_count += 1;
707                        new_items.insert(item);
708                    }
709                    (Mode::ParallelChunkableModule, _) => {
710                        // Split the batch
711                        let idx = pre_batches.batches.len();
712                        let mut new_batch =
713                            PreBatch::new(pre_batches.batches[i].chunk_groups.clone());
714                        new_batch.items.extend(new_items.drain(..));
715                        pre_batches.batches.push(new_batch);
716                        edges_count += 1;
717                        new_items.insert(PreBatchItem::ParallelReference(idx));
718                        if chunkable_module.is_some() {
719                            new_items.insert(item);
720                        } else {
721                            edges_count += 1;
722                            mode = Mode::Other;
723                            new_items.insert(item);
724                        }
725                    }
726                }
727            }
728            pre_batches.batches[i].items = new_items;
729        }
730        span.record("pre_batches", pre_batches.batches.len());
731
732        // Now batches are in the correct shape. We can create the real batches and the graph.
733
734        // Create the graph
735        let mut graph: DiGraph<ModuleOrBatch, ModuleBatchesGraphEdge, u32> =
736            petgraph::graph::DiGraph::with_capacity(
737                pre_batches.batches.len() + pre_batches.single_module_entries.len(),
738                edges_count,
739            );
740
741        // Create the Vc<ModuleBatch> instances
742        let batches = pre_batches
743            .batches
744            .iter_mut()
745            .enumerate()
746            .map(async |(i, pre_batch)| {
747                let mut modules = pre_batch.items.iter().filter_map(|item| {
748                    if let PreBatchItem::ParallelModule(module) = item {
749                        ResolvedVc::try_downcast(*module)
750                    } else {
751                        None
752                    }
753                });
754                let Some(first) = modules.next() else {
755                    return Ok(ModuleOrBatch::None(i));
756                };
757                if let Some(second) = modules.next() {
758                    let batch = ModuleBatch::new(
759                        [first, second]
760                            .into_iter()
761                            .chain(modules)
762                            .map(|m| *m)
763                            .collect::<Vec<_>>(),
764                        Some(pre_batch.chunk_groups.clone()),
765                    );
766                    Ok(ModuleOrBatch::Batch(batch.to_resolved().await?))
767                } else {
768                    Ok(ModuleOrBatch::Module(ResolvedVc::upcast(first)))
769                }
770            })
771            .try_join()
772            .await?;
773
774        // Create the batch groups by grouping batches with the same chunk groups
775        let mut batch_groups: FxHashMap<_, Vec<_>> = FxHashMap::default();
776        for (i, pre_batch) in pre_batches.batches.iter().enumerate() {
777            let key = BuildHasherDefault::<FxHasher>::default().prehash(&pre_batch.chunk_groups);
778            let batch = batches[i];
779            batch_groups.entry(key).or_default().push(batch);
780        }
781        for &module in &pre_batches.single_module_entries {
782            let chunk_groups = module_chunk_groups
783                .get(&module)
784                .context("all modules need to have chunk group info")?;
785            let key = BuildHasherDefault::<FxHasher>::default().prehash(chunk_groups);
786            batch_groups
787                .entry(key)
788                .or_default()
789                .push(ModuleOrBatch::Module(module));
790        }
791
792        // Create the batch group instances
793        let batch_groups = batch_groups
794            .into_iter()
795            .map(async |(key, items)| {
796                if items.len() == 1 {
797                    Ok(Either::Left(std::iter::empty()))
798                } else {
799                    let batch_group = ModuleBatchGroup::new(items.clone(), (*key).clone())
800                        .to_resolved()
801                        .await?;
802                    Ok(Either::Right(
803                        items.into_iter().map(move |item| (item, batch_group)),
804                    ))
805                }
806            })
807            .try_join()
808            .await?
809            .into_iter()
810            .flatten()
811            .collect::<FxHashMap<_, _>>();
812
813        // Insert batches into the graph and store the NodeIndices
814        let mut batches_count = 0;
815        let mut modules_count = 0;
816        let batch_indices = batches
817            .into_iter()
818            .map(|batch| {
819                match &batch {
820                    ModuleOrBatch::Batch(_) => batches_count += 1,
821                    ModuleOrBatch::Module(_) => modules_count += 1,
822                    ModuleOrBatch::None(_) => {}
823                }
824                graph.add_node(batch)
825            })
826            .collect::<Vec<_>>();
827
828        // Also insert single modules into the graph and store the NodeIndices
829        let single_module_indices = pre_batches
830            .single_module_entries
831            .iter()
832            .map(|module| graph.add_node(ModuleOrBatch::Module(*module)))
833            .collect::<Vec<_>>();
834
835        span.record("batches", batches_count);
836        modules_count += pre_batches.single_module_entries.len();
837        span.record("modules", modules_count);
838        span.record("edges", edges_count);
839
840        // Add all the edges to the graph
841        for (i, pre_batch) in pre_batches.batches.into_iter().enumerate() {
842            let index = batch_indices[i];
843            let items = pre_batch.items;
844            for item in items {
845                match item {
846                    PreBatchItem::ParallelReference(idx) => {
847                        graph.add_edge(
848                            index,
849                            batch_indices[idx],
850                            ModuleBatchesGraphEdge {
851                                ty: ChunkingType::Parallel {
852                                    inherit_async: false,
853                                    hoisted: false,
854                                },
855                                module: None,
856                            },
857                        );
858                    }
859                    PreBatchItem::NonParallelEdge(ty, module) => {
860                        if let Some(batch) = pre_batches.entries.get(&module).copied() {
861                            graph.add_edge(
862                                index,
863                                batch_indices[batch],
864                                ModuleBatchesGraphEdge {
865                                    ty,
866                                    module: Some(module),
867                                },
868                            );
869                            continue;
870                        }
871                        let idx = pre_batches
872                            .single_module_entries
873                            .get_index_of(&module)
874                            .context("could not find single module entry index")?;
875                        let idx = single_module_indices[idx];
876                        graph.add_edge(
877                            index,
878                            idx,
879                            ModuleBatchesGraphEdge {
880                                ty,
881                                module: Some(module),
882                            },
883                        );
884                    }
885                    PreBatchItem::ParallelModule(_) => {}
886                }
887            }
888        }
889
890        debug_assert_eq!(graph.capacity().0, graph.node_count());
891        debug_assert_eq!(graph.capacity().1, graph.edge_count());
892
893        // Find the NodeIndices for our entries of the graph
894        let mut entries = FxHashMap::default();
895        for chunk_group in &chunk_group_info.chunk_groups {
896            for module in chunk_group.entries() {
897                if let Some(batch) = pre_batches.entries.get(&module).copied() {
898                    entries.insert(module, batch_indices[batch]);
899                    continue;
900                }
901                let idx = pre_batches
902                    .single_module_entries
903                    .get_index_of(&module)
904                    .context("could not find single module entry index")?;
905                let idx = single_module_indices[idx];
906                entries.insert(module, idx);
907            }
908        }
909
910        Ok(ModuleBatchesGraph {
911            graph: TracedDiGraph(graph),
912            entries,
913            batch_groups,
914            ordered_entries,
915        }
916        .cell())
917    }
918    .instrument(outer_span)
919    .await
920}