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