Skip to main content

turbopack_core/module_graph/
mod.rs

1use std::{
2    collections::{BinaryHeap, VecDeque},
3    future::Future,
4    hash::{Hash, Hasher},
5    iter::FusedIterator,
6    ops::Deref,
7    sync::{Mutex, OnceLock},
8};
9
10use anyhow::{Context, Result, bail};
11use bincode::{Decode, Encode};
12use fixedbitset::FixedBitSet;
13use petgraph::{
14    Direction,
15    graph::{DiGraph, EdgeIndex, NodeIndex},
16    visit::{EdgeRef, IntoNodeReferences, NodeIndexable, Reversed},
17};
18use rustc_hash::{FxHashMap, FxHashSet};
19use serde::{Deserialize, Serialize};
20use tracing::{Instrument, Level, Span};
21use turbo_rcstr::{RcStr, rcstr};
22use turbo_tasks::{
23    CollectiblesSource, JoinIterExt, NonLocalValue, OperationVc, ReadRef, ResolvedVc,
24    TryFlatJoinIterExt, TryJoinIterExt, ValueToString, Vc,
25    debug::ValueDebugFormat,
26    graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow},
27    util::SharedError,
28};
29use turbo_tasks_fs::FileSystemPath;
30
31use crate::{
32    chunk::{AsyncModuleInfo, ChunkingContext, ChunkingType, MergeableModule, TracedMode},
33    ident::AssetIdent,
34    issue::{ImportTracer, ImportTraces, Issue, IssueExt, IssueSeverity, analyze::AnalyzeIssue},
35    module::{Module, ModuleSideEffects},
36    module_graph::{
37        async_module_info::{AsyncModulesInfo, compute_async_module_info},
38        binding_usage_info::{BindingUsageInfo, UnusedReferenceEdges},
39        chunk_group_info::{ChunkGroupEntry, ChunkGroupInfo, compute_chunk_group_info},
40        collect::{CollectedModules, collect_graph},
41        merged_modules::{MergedModuleInfo, compute_merged_modules},
42        module_batches::{ModuleBatchesGraph, compute_module_batches},
43        style_groups::{StyleGroups, StyleGroupsAlgorithm, StyleGroupsConfig},
44        style_groups_graph::compute_style_groups_graph,
45        style_groups_loose::compute_style_groups,
46        traced_di_graph::TracedDiGraph,
47    },
48    reference::{
49        ModuleReference, primary_chunkable_referenced_modules,
50        referenced_modules_and_affecting_sources,
51    },
52    resolve::BindingUsage,
53};
54
55pub mod async_module_info;
56pub mod binding_usage_info;
57pub mod chunk_group_info;
58pub mod collect;
59pub mod merged_modules;
60pub mod module_batch;
61pub(crate) mod module_batches;
62mod side_effect_module_info;
63pub mod style_groups;
64pub mod style_groups_graph;
65pub mod style_groups_loose;
66mod traced_di_graph;
67
68pub use self::module_batches::BatchingConfig;
69
70#[derive(
71    Debug, Copy, Clone, Eq, PartialOrd, Ord, Hash, PartialEq, Serialize, Deserialize, Encode, Decode,
72)]
73pub struct GraphNodeIndex {
74    graph_idx: u32,
75    #[bincode(with_serde)]
76    node_idx: NodeIndex,
77}
78impl GraphNodeIndex {
79    fn new(graph_idx: u32, node_idx: NodeIndex) -> Self {
80        Self {
81            graph_idx,
82            node_idx,
83        }
84    }
85}
86
87unsafe impl NonLocalValue for GraphNodeIndex {}
88
89#[derive(
90    Debug, Copy, Clone, Eq, PartialOrd, Ord, Hash, PartialEq, NonLocalValue, Encode, Decode,
91)]
92pub struct GraphEdgeIndex {
93    graph_idx: u32,
94    #[turbo_tasks(unsafe_ignore)]
95    #[bincode(with_serde)]
96    edge_idx: EdgeIndex,
97}
98
99impl GraphEdgeIndex {
100    fn new(graph_idx: u32, edge_idx: EdgeIndex) -> Self {
101        Self {
102            graph_idx,
103            edge_idx,
104        }
105    }
106}
107
108#[turbo_tasks::value]
109#[derive(Clone, Debug)]
110pub struct VisitedModules {
111    pub modules: FxHashMap<ResolvedVc<Box<dyn Module>>, GraphNodeIndex>,
112    next_graph_idx: u32,
113}
114
115#[turbo_tasks::value_impl]
116impl VisitedModules {
117    #[turbo_tasks::function(operation)]
118    pub fn empty() -> Vc<Self> {
119        Self {
120            modules: Default::default(),
121            next_graph_idx: 0,
122        }
123        .cell()
124    }
125
126    #[turbo_tasks::function(operation)]
127    pub async fn from_graph(graph: OperationVc<SingleModuleGraph>) -> Result<Vc<Self>> {
128        Ok(Self {
129            modules: graph
130                .connect()
131                .await?
132                .enumerate_nodes()
133                .flat_map(|(node_idx, module)| match module {
134                    SingleModuleGraphNode::Module(module) => Some((
135                        *module,
136                        GraphNodeIndex {
137                            graph_idx: 0,
138                            node_idx,
139                        },
140                    )),
141                    SingleModuleGraphNode::VisitedModule { .. } => None,
142                })
143                .collect(),
144            next_graph_idx: 1,
145        }
146        .cell())
147    }
148
149    #[turbo_tasks::function(operation)]
150    pub async fn with_incremented_index(this: OperationVc<Self>) -> Result<Vc<Self>> {
151        let this = this.connect().await?;
152        Ok(Self {
153            modules: this.modules.clone(),
154            next_graph_idx: this.next_graph_idx + 1,
155        }
156        .cell())
157    }
158
159    #[turbo_tasks::function(operation)]
160    pub async fn concatenate(
161        this: OperationVc<Self>,
162        graph: OperationVc<SingleModuleGraph>,
163    ) -> Result<Vc<Self>> {
164        let graph = graph.connect().await?;
165        let this = this.connect().await?;
166        let iter = this
167            .modules
168            .iter()
169            .map(|(module, idx)| (*module, *idx))
170            .chain(
171                graph
172                    .enumerate_nodes()
173                    .flat_map(|(node_idx, module)| match module {
174                        SingleModuleGraphNode::Module(module) => Some((
175                            *module,
176                            GraphNodeIndex {
177                                graph_idx: this.next_graph_idx,
178                                node_idx,
179                            },
180                        )),
181                        SingleModuleGraphNode::VisitedModule { .. } => None,
182                    }),
183            );
184
185        let mut map = FxHashMap::with_capacity_and_hasher(
186            this.modules.len() + graph.number_of_modules,
187            Default::default(),
188        );
189        for (k, v) in iter {
190            map.entry(k).or_insert(v);
191        }
192        map.shrink_to_fit();
193
194        Ok(Self {
195            modules: map,
196            next_graph_idx: this.next_graph_idx + 1,
197        }
198        .cell())
199    }
200}
201
202#[turbo_tasks::value(shared, task_input)]
203#[derive(Debug, Clone, Hash, Default)]
204pub struct GraphEntries {
205    /// The bundled chunk groups (listing their entry modules)
206    chunk_groups: Vec<ChunkGroupEntry>,
207    /// Traced top-level modules, which are not referenced by chunk_groups but should still be
208    /// considered as part of the graph.
209    traced_modules: Vec<ResolvedVc<Box<dyn Module>>>,
210}
211
212#[turbo_tasks::value_impl]
213impl GraphEntries {
214    #[turbo_tasks::function]
215    pub fn empty() -> Vc<Self> {
216        Self::default().cell()
217    }
218}
219
220impl GraphEntries {
221    pub fn new(
222        chunk_groups: Vec<ChunkGroupEntry>,
223        traced_modules: Vec<ResolvedVc<Box<dyn Module>>>,
224    ) -> Self {
225        Self {
226            chunk_groups,
227            traced_modules,
228        }
229    }
230    pub fn from_chunk_groups(chunk_groups: Vec<ChunkGroupEntry>) -> Self {
231        Self {
232            chunk_groups,
233            traced_modules: vec![],
234        }
235    }
236
237    pub fn concatenate(entries: impl IntoIterator<Item = GraphEntries>) -> Self {
238        let (chunk_groups, traced_modules): (Vec<_>, Vec<_>) = entries
239            .into_iter()
240            .map(|e| (e.chunk_groups, e.traced_modules))
241            .unzip();
242        Self {
243            chunk_groups: chunk_groups.into_iter().flatten().collect(),
244            traced_modules: traced_modules.into_iter().flatten().collect(),
245        }
246    }
247
248    /// Returns both chunk group modules and traced modules.
249    pub fn all_modules(&self) -> impl Iterator<Item = ResolvedVc<Box<dyn Module>>> + '_ {
250        self.chunk_groups
251            .iter()
252            .flat_map(|e| e.entries())
253            .chain(self.traced_modules.iter().cloned())
254    }
255
256    /// Like all_modules, but with a boolean whether the module came from `traced_modules`
257    pub fn all_modules_with_is_traced(
258        &self,
259    ) -> impl Iterator<Item = (ResolvedVc<Box<dyn Module>>, bool)> + '_ {
260        self.chunk_groups
261            .iter()
262            .flat_map(|e| e.entries().map(|m| (m, false)))
263            .chain(self.traced_modules.iter().cloned().map(|m| (m, true)))
264    }
265
266    /// Returns only the bundled modules, not the traced modules.
267    pub fn chunk_group_modules(&self) -> impl Iterator<Item = ResolvedVc<Box<dyn Module>>> + '_ {
268        self.chunk_groups.iter().flat_map(|e| e.entries())
269    }
270}
271
272/// Options controlling what data [`SingleModuleGraph`] collects while walking module references.
273/// Passed by value to the graph constructors.
274#[turbo_tasks::task_input]
275#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, Hash, Encode, Decode)]
276pub struct ModuleGraphOptions {
277    /// Eagerly resolve and store each module's `ident_string()` `Vc` in its graph node, so the
278    /// module-id strategy reads it from the in-memory graph instead of fanning out a
279    /// `module.ident_string()` (i.e. `ident().to_string()`) turbo-task launch per module. Only the
280    /// whole-app/CLI-build graphs that run the global module-id strategy
281    /// (`turbopack::global_module_ids::get_global_module_id_strategy`) need it; other graphs leave
282    /// it off to avoid the per-module `to_string` resolve.
283    ///
284    /// (`ident()` itself is always collected — see [`ModuleGraphSnapshot::module_ident`].)
285    pub include_ident_strings: bool,
286    /// Eagerly resolve and store each module's `side_effects()` `Vc` in its graph node, so the
287    /// side-effect-free aggregation reads it from the in-memory graph instead of fanning out a
288    /// `module.side_effects()` turbo-task launch per module. Required by
289    /// `compute_side_effect_free_module_info`: that pass `bail!`s on graphs built without this.
290    pub include_side_effects: bool,
291    /// Eagerly resolve and store each module's `MergeableModule::is_mergeable()` `Vc` in its graph
292    /// node, so module merging (scope hoisting) reads it from the in-memory graph instead of
293    /// fanning out a `module.is_mergeable()` turbo-task launch per module. Required by
294    /// [`compute_merged_modules`]: that pass `bail!`s on graphs built without this. Should be
295    /// enabled wherever the chunking context has module merging enabled
296    /// ([`ChunkingContext::is_module_merging_enabled`]).
297    ///
298    /// When set, every `Module` node stores `Some`: the module's real `is_mergeable()` for types
299    /// that implement [`MergeableModule`], or a resolved `false` for types that don't (so `None`
300    /// unambiguously means "this graph wasn't built with `include_mergeable`").
301    ///
302    /// [`compute_merged_modules`]: crate::module_graph::merged_modules::compute_merged_modules
303    /// [`MergeableModule`]: crate::chunk::MergeableModule
304    /// [`ChunkingContext::is_module_merging_enabled`]:
305    /// crate::chunk::ChunkingContext::is_module_merging_enabled
306    pub include_mergeable: bool,
307    /// Whether to walk `ChunkingType::Traced` references.
308    pub include_traced: bool,
309    /// Whether to read `ModuleReference::binding_usage()`.
310    pub include_binding_usage: bool,
311    /// Treat every [`ActivatableModule`] in this graph as if it were already activated. This is
312    /// for graphs whose consumer can't activate modules on demand, e.g. code evaluated during the
313    /// build.
314    ///
315    /// The graph then follows [`ActivatableModule::activated_references`] instead of
316    /// [`Module::references`], so it includes what the module would reference once activated.
317    /// Chunk items of activatable modules check [`ModuleGraph::force_activated`] and generate
318    /// the code of an active module.
319    ///
320    /// This only affects this graph. It doesn't change the activation state, so other graphs that
321    /// contain the same modules still see them as inactive until they are really activated.
322    ///
323    /// [`ActivatableModule`]: crate::module::ActivatableModule
324    /// [`ActivatableModule::activated_references`]: crate::module::ActivatableModule::activated_references
325    pub force_activated: bool,
326}
327
328#[turbo_tasks::value(cell = "new", eq = "manual")]
329#[derive(Default)]
330pub struct SingleModuleGraph {
331    pub graph: TracedDiGraph<SingleModuleGraphNode, RefData>,
332
333    /// The number of modules in the graph (excluding VisitedModule nodes)
334    pub number_of_modules: usize,
335
336    // Per-module data eagerly resolved at construction, stored as columns indexed by
337    // `NodeIndex::index()`. `new_inner` adds every `Module` node before any `VisitedModule` node,
338    // so the `Module` nodes are exactly `0..number_of_modules` and each column has one entry per
339    // `Module` node; an index past the end is a `VisitedModule` node, whose data lives in the
340    // graph that owns it. Consumers read these tracked: the producing tasks were already
341    // resolved here, so the read is cheap while still depending on the value.
342    /// Always collected: idents have many consumers (NFT, feature usage, module ids, import
343    /// tracing).
344    idents: Vec<ResolvedVc<AssetIdent>>,
345    /// Always collected: `async_module_info()` runs during chunking for every graph.
346    is_self_async: Vec<ResolvedVc<bool>>,
347    /// `ident().to_string()`, collected with [`ModuleGraphOptions::include_ident_strings`].
348    ident_strings: Option<Vec<ResolvedVc<RcStr>>>,
349    /// Collected with [`ModuleGraphOptions::include_side_effects`].
350    side_effects: Option<Vec<ResolvedVc<ModuleSideEffects>>>,
351    /// Collected with [`ModuleGraphOptions::include_mergeable`]: the module's `is_mergeable()`
352    /// for types that implement [`MergeableModule`], `false` for the others.
353    is_mergeable: Option<Vec<ResolvedVc<bool>>>,
354
355    // NodeIndex isn't necessarily stable (because of swap_remove), but we never remove nodes.
356    //
357    // HashMaps have nondeterministic order, but this map is only used for lookups (in
358    // `get_module`) and not iteration.
359    //
360    // This contains Vcs, but they are already contained in the graph.
361    #[turbo_tasks(unsafe_ignore)]
362    #[bincode(with_serde)]
363    modules: FxHashMap<ResolvedVc<Box<dyn Module>>, NodeIndex>,
364
365    entries: GraphEntries,
366
367    /// Built with [`ModuleGraphOptions::force_activated`].
368    force_activated: bool,
369
370    /// Derived from `entries` and `modules`. Both are immutable after graph construction, and node
371    /// indices are stable because graph nodes are never removed.
372    #[turbo_tasks(debug_ignore, unsafe_ignore)]
373    #[bincode(skip, default = "OnceLock::new")]
374    entry_nodes: OnceLock<FxHashSet<NodeIndex>>,
375}
376
377impl Clone for SingleModuleGraph {
378    fn clone(&self) -> Self {
379        Self {
380            graph: self.graph.clone(),
381            number_of_modules: self.number_of_modules,
382            idents: self.idents.clone(),
383            is_self_async: self.is_self_async.clone(),
384            ident_strings: self.ident_strings.clone(),
385            side_effects: self.side_effects.clone(),
386            is_mergeable: self.is_mergeable.clone(),
387            modules: self.modules.clone(),
388            entries: self.entries.clone(),
389            force_activated: self.force_activated,
390            // Never carry derived state into a clone that might be modified before being stored.
391            entry_nodes: OnceLock::new(),
392        }
393    }
394}
395
396#[derive(
397    Debug,
398    Clone,
399    Hash,
400    Serialize,
401    Deserialize,
402    Eq,
403    PartialEq,
404    ValueDebugFormat,
405    NonLocalValue,
406    Encode,
407    Decode,
408)]
409pub struct RefData {
410    pub chunking_type: ChunkingType,
411    pub binding_usage: BindingUsage,
412    pub reference: ResolvedVc<Box<dyn ModuleReference>>,
413}
414
415impl SingleModuleGraph {
416    /// Walks the graph starting from the given entries and collects all reachable nodes, skipping
417    /// nodes listed in `visited_modules`
418    /// The resulting graph's outgoing edges are in reverse order.
419    async fn new_inner(
420        entries: &GraphEntries,
421        visited_modules: &FxHashMap<ResolvedVc<Box<dyn Module>>, GraphNodeIndex>,
422        options: ModuleGraphOptions,
423    ) -> Result<Vc<Self>> {
424        let emit_spans = tracing::enabled!(Level::INFO);
425        let root_nodes = entries
426            .all_modules_with_is_traced()
427            .map(|(e, is_traced)| {
428                SingleModuleGraphBuilderNode::new_module(emit_spans, e, is_traced)
429            })
430            .try_join()
431            .await?;
432
433        let node_data = Mutex::new(FxHashMap::default());
434        let children_nodes_iter = AdjacencyMap::new()
435            .visit(
436                root_nodes,
437                SingleModuleGraphBuilder {
438                    visited_modules,
439                    node_data: &node_data,
440                    emit_spans,
441                    options,
442                },
443            )
444            .await
445            .completed()?;
446        let node_count = children_nodes_iter.len();
447
448        let edges = children_nodes_iter
449            .into_breadth_first_edges()
450            .collect::<Vec<_>>();
451        // The traversal resolved every module's node data in `edges()`.
452        let mut node_data = node_data.into_inner().unwrap();
453
454        let mut graph: DiGraph<SingleModuleGraphNode, RefData> = DiGraph::with_capacity(
455            node_count,
456            // From real world measurements each module has about 3-4 children
457            // If it has more this would cause an additional allocation, but that's fine
458            node_count * 4,
459        );
460
461        let mut modules: FxHashMap<ResolvedVc<Box<dyn Module>>, NodeIndex> =
462            FxHashMap::with_capacity_and_hasher(node_count, Default::default());
463        let module_count = node_data.len();
464        let mut idents = Vec::with_capacity(module_count);
465        let mut is_self_async = Vec::with_capacity(module_count);
466        let mut ident_strings = options
467            .include_ident_strings
468            .then(|| Vec::with_capacity(module_count));
469        let mut side_effects = options
470            .include_side_effects
471            .then(|| Vec::with_capacity(module_count));
472        let mut is_mergeable = options
473            .include_mergeable
474            .then(|| Vec::with_capacity(module_count));
475        {
476            let _span = tracing::info_span!("build module graph").entered();
477            // Synchronous: no `.await` here (the loop holds the `tracing` span guard and many
478            // mutable locals across iterations; the per-module `node_data` was resolved during the
479            // traversal).
480
481            // Nodes are added in breadth-first order, but all `Module` nodes before any
482            // `VisitedModule` node, so the per-module columns line up with `0..number_of_modules`.
483            for (_, current) in &edges {
484                if let &SingleModuleGraphBuilderNode::Module { module, .. } = current
485                    && !modules.contains_key(&module)
486                {
487                    let data = node_data
488                        .remove(&module)
489                        .context("the traversal resolves node data for every module it reaches")?;
490                    let node_idx = graph.add_node(SingleModuleGraphNode::Module(module));
491                    debug_assert_eq!(
492                        node_idx.index(),
493                        idents.len(),
494                        "node indices must line up with the per-module columns"
495                    );
496                    modules.insert(module, node_idx);
497                    idents.push(data.ident);
498                    is_self_async.push(data.is_self_async);
499                    push_collected(&mut ident_strings, data.ident_string);
500                    push_collected(&mut side_effects, data.side_effects);
501                    push_collected(&mut is_mergeable, data.is_mergeable);
502                }
503            }
504            for (_, current) in &edges {
505                if let &SingleModuleGraphBuilderNode::VisitedModule { module, idx } = current
506                    && !modules.contains_key(&module)
507                {
508                    modules.insert(
509                        module,
510                        graph.add_node(SingleModuleGraphNode::VisitedModule { idx, module }),
511                    );
512                }
513            }
514            for (parent, current) in edges {
515                if let Some((SingleModuleGraphBuilderNode::Module { module, .. }, ref_data)) =
516                    parent
517                {
518                    graph.add_edge(modules[&module], modules[&current.module()], ref_data);
519                }
520            }
521        }
522
523        graph.shrink_to_fit();
524
525        #[cfg(debug_assertions)]
526        {
527            use std::sync::LazyLock;
528            static CHECK_FOR_DUPLICATE_MODULES: LazyLock<bool> = LazyLock::new(|| {
529                match std::env::var_os("TURBOPACK_TEMP_DISABLE_DUPLICATE_MODULES_CHECK") {
530                    Some(v) => v != "1" && v != "true",
531                    None => true,
532                }
533            });
534            if *CHECK_FOR_DUPLICATE_MODULES {
535                let mut duplicates = FxHashSet::default();
536                let mut set = FxHashSet::default();
537                for &module in modules.keys() {
538                    let ident = module.ident_string().await?;
539                    if !set.insert(ident.clone()) {
540                        duplicates.insert(ident);
541                    }
542                }
543                if !duplicates.is_empty() {
544                    use turbo_tasks::TryFlatJoinIterExt;
545
546                    let duplicates_clone = duplicates.clone();
547                    let duplicate_modules = modules
548                        .iter()
549                        .map(async |(&m, &idx)| {
550                            let id = m.ident_string().await?;
551                            if duplicates_clone.contains(&id) {
552                                // 3 is arbitrary but it is enough to reveal a little bit
553                                // of detail.
554                                let debug = m.value_debug_format(3).try_to_string().await?;
555
556                                // Collect reverse dependencies (parents) to help
557                                // diagnose how this module entered the graph.
558                                let parent_modules: Vec<_> = graph
559                                    .edges_directed(idx, petgraph::Direction::Incoming)
560                                    .filter_map(|edge| match graph.node_weight(edge.source()) {
561                                        Some(SingleModuleGraphNode::Module(m)) => Some(*m),
562                                        Some(SingleModuleGraphNode::VisitedModule {
563                                            module,
564                                            ..
565                                        }) => Some(*module),
566                                        None => None,
567                                    })
568                                    .collect();
569                                let parents: Vec<String> = parent_modules
570                                    .iter()
571                                    .map(async |p| {
572                                        let ident = p.ident_string().await?;
573                                        Ok((*ident).to_string())
574                                    })
575                                    .try_join()
576                                    .await?;
577
578                                Ok(Some((id, debug, parents)))
579                            } else {
580                                Ok(None)
581                            }
582                        })
583                        .try_flat_join()
584                        .await?;
585                    // group by ident
586                    let mut map: FxHashMap<_, Vec<(String, Vec<String>)>> = FxHashMap::default();
587                    for (key, debug, parents) in duplicate_modules {
588                        map.entry(key).or_default().push((debug, parents));
589                    }
590                    let result = map
591                        .into_iter()
592                        .map(|(ident, modules)| {
593                            let modules = modules
594                                .into_iter()
595                                .map(|(debug, parents)| {
596                                    format!("Module: {debug}, Parents: {parents:?}")
597                                })
598                                .collect::<Vec<_>>()
599                                .join("\n");
600                            format!("Ident: {ident}\n{modules}")
601                        })
602                        .collect::<Vec<_>>()
603                        .join("\n\n");
604                    bail!("Duplicate module idents in graph: {result}");
605                }
606            }
607        }
608
609        let number_of_modules = idents.len();
610        debug_assert!(
611            graph
612                .node_indices()
613                .all(|idx| matches!(graph[idx], SingleModuleGraphNode::Module(_))
614                    == (idx.index() < number_of_modules)),
615            "all Module nodes must come before all VisitedModule nodes"
616        );
617        debug_assert!(
618            [
619                ident_strings.as_ref().map(Vec::len),
620                side_effects.as_ref().map(Vec::len),
621                is_mergeable.as_ref().map(Vec::len),
622            ]
623            .into_iter()
624            .flatten()
625            .all(|len| len == number_of_modules),
626            "collected columns must have one entry per Module node"
627        );
628        let graph = SingleModuleGraph {
629            graph: TracedDiGraph::new(graph),
630            number_of_modules,
631            idents,
632            is_self_async,
633            ident_strings,
634            side_effects,
635            is_mergeable,
636            modules,
637            entries: entries.clone(),
638            force_activated: options.force_activated,
639            entry_nodes: OnceLock::new(),
640        }
641        .cell();
642
643        turbo_tasks::emit(ResolvedVc::upcast::<Box<dyn ImportTracer>>(
644            ModuleGraphImportTracer::new(graph).to_resolved().await?,
645        ));
646        Ok(graph)
647    }
648
649    /// WARNING: using this is discouraged, as it doesn't filter out unused or traced references.
650    /// Use iter_reachable_modules or one of the .traverse_* functions instead.
651    pub fn iter_nodes(&self) -> impl Iterator<Item = ResolvedVc<Box<dyn Module>>> + '_ {
652        self.graph.node_weights().filter_map(|n| match n {
653            SingleModuleGraphNode::Module(module) => Some(*module),
654            SingleModuleGraphNode::VisitedModule { .. } => None,
655        })
656    }
657
658    /// Iterates the `Module` nodes with their eagerly-resolved idents. The `Module` nodes are the
659    /// first `number_of_modules` nodes, in the same order as the `idents` column.
660    pub fn iter_modules_with_idents(
661        &self,
662    ) -> impl Iterator<Item = (ResolvedVc<Box<dyn Module>>, ResolvedVc<AssetIdent>)> + '_ {
663        self.graph
664            .node_weights()
665            .zip(&self.idents)
666            .map(|(node, ident)| (node.module(), *ident))
667    }
668
669    fn entry_nodes(&self) -> &FxHashSet<NodeIndex> {
670        self.entry_nodes.get_or_init(|| {
671            self.entries
672                .all_modules()
673                .filter_map(|module| self.modules.get(&module).copied())
674                .collect()
675        })
676    }
677
678    /// Returns true if the given module is in this graph and is an entry module.
679    ///
680    /// Entry modules are tracked explicitly because an entry can have incoming edges when it is
681    /// part of a module cycle.
682    pub fn has_entry_module(&self, module: ResolvedVc<Box<dyn Module>>) -> bool {
683        self.modules
684            .get(&module)
685            .is_some_and(|index| self.entry_nodes().contains(index))
686    }
687
688    /// Iterate over graph entry points
689    pub fn chunk_group_modules(&self) -> impl Iterator<Item = ResolvedVc<Box<dyn Module>>> + '_ {
690        self.entries.chunk_group_modules()
691    }
692
693    /// WARNING: using this is discouraged, as it doesn't filter out unused or traced references.
694    /// Use iter_reachable_modules or one of the .traverse_* functions instead.
695    pub fn enumerate_nodes(
696        &self,
697    ) -> impl Iterator<Item = (NodeIndex, &'_ SingleModuleGraphNode)> + '_ {
698        self.graph.node_references()
699    }
700
701    fn traverse_cycles<'l>(
702        &'l self,
703        edge_filter: impl Fn(&'l RefData) -> bool,
704        mut visit_cycle: impl FnMut(&[&'l ResolvedVc<Box<dyn Module>>]) -> Result<()>,
705        graph_idx: u32,
706        unused_references_edges: &'l Option<ReadRef<UnusedReferenceEdges>>,
707    ) -> Result<()> {
708        // See https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm, but
709        // implemented iteratively instead of recursively.
710        //
711        // Compared to the standard Tarjan's, this also treated self-references (via
712        // `has_self_loop`) as SCCs.
713
714        #[derive(Clone)]
715        struct NodeState {
716            index: u32,
717            lowlink: u32,
718            on_stack: bool,
719            has_self_loop: bool,
720        }
721        enum VisitStep {
722            UnvisitedNode(NodeIndex),
723            EdgeAfterVisit { parent: NodeIndex, child: NodeIndex },
724            AfterVisit(NodeIndex),
725        }
726        let mut node_states = vec![None; self.graph.node_bound()];
727        let mut stack = Vec::new();
728        let mut visit_stack = Vec::new();
729        let mut index = 0;
730        let mut scc = Vec::new();
731        for initial_index in self.graph.node_indices() {
732            // Skip over already visited nodes
733            if node_states[initial_index.index()].is_some() {
734                continue;
735            }
736            visit_stack.push(VisitStep::UnvisitedNode(initial_index));
737            while let Some(step) = visit_stack.pop() {
738                match step {
739                    VisitStep::UnvisitedNode(node) => {
740                        node_states[node.index()] = Some(NodeState {
741                            index,
742                            lowlink: index,
743                            on_stack: true,
744                            has_self_loop: false,
745                        });
746                        index += 1;
747                        stack.push(node);
748                        visit_stack.push(VisitStep::AfterVisit(node));
749                        let mut neighbors = self.graph.neighbors(node).detach();
750                        while let Some((edge, succ)) = neighbors.next(&self.graph) {
751                            if unused_references_edges.as_ref().is_some_and(|edges| {
752                                edges.contains(&GraphEdgeIndex::new(graph_idx, edge))
753                            }) {
754                                continue;
755                            }
756
757                            let edge_weight = self.graph.edge_weight(edge).unwrap();
758                            if !edge_filter(edge_weight) {
759                                continue;
760                            }
761                            let node_state = &node_states[succ.index()];
762                            if let Some(node_state) = node_state {
763                                if node_state.on_stack {
764                                    let index = node_state.index;
765                                    let parent_state = node_states[node.index()].as_mut().unwrap();
766                                    parent_state.lowlink = parent_state.lowlink.min(index);
767                                    if succ == node {
768                                        parent_state.has_self_loop = true;
769                                    }
770                                }
771                            } else {
772                                visit_stack.push(VisitStep::EdgeAfterVisit {
773                                    parent: node,
774                                    child: succ,
775                                });
776                                visit_stack.push(VisitStep::UnvisitedNode(succ));
777                            }
778                        }
779                    }
780                    VisitStep::EdgeAfterVisit { parent, child } => {
781                        let child_state = node_states[child.index()].as_ref().unwrap();
782                        let lowlink = child_state.lowlink;
783
784                        let parent_state = node_states[parent.index()].as_mut().unwrap();
785                        parent_state.lowlink = parent_state.lowlink.min(lowlink);
786                    }
787                    VisitStep::AfterVisit(node) => {
788                        let node_state = node_states[node.index()].as_ref().unwrap();
789                        let node_has_self_loop = node_state.has_self_loop;
790                        if node_state.lowlink == node_state.index {
791                            loop {
792                                let poppped = stack.pop().unwrap();
793                                let popped_state = node_states[poppped.index()].as_mut().unwrap();
794                                popped_state.on_stack = false;
795                                if let SingleModuleGraphNode::Module(module) =
796                                    self.graph.node_weight(poppped).unwrap()
797                                {
798                                    scc.push(module);
799                                }
800                                if poppped == node {
801                                    break;
802                                }
803                            }
804                            if scc.len() > 1 || node_has_self_loop {
805                                visit_cycle(&scc)?;
806                            }
807                            scc.clear();
808                        }
809                    }
810                }
811            }
812        }
813        Ok(())
814    }
815}
816
817#[turbo_tasks::value]
818struct ModuleGraphImportTracer {
819    graph: ResolvedVc<SingleModuleGraph>,
820}
821
822#[turbo_tasks::value(shared)]
823struct PathToModulesMap {
824    map: FxHashMap<FileSystemPath, Vec<ResolvedVc<Box<dyn Module>>>>,
825}
826
827#[turbo_tasks::value_impl]
828impl ModuleGraphImportTracer {
829    #[turbo_tasks::function]
830    fn new(graph: ResolvedVc<SingleModuleGraph>) -> Vc<Self> {
831        Self::cell(Self { graph })
832    }
833
834    // Compute this mapping on demand since it might not always be needed.
835    #[turbo_tasks::function]
836    async fn path_to_modules(&self) -> Result<Vc<PathToModulesMap>> {
837        let graph = self.graph.await?;
838        let path_and_modules = graph
839            .graph
840            .node_references()
841            .map(async |(idx, n)| {
842                let (module, ident) = match n {
843                    SingleModuleGraphNode::Module(module) => (*module, graph.idents[idx.index()]),
844                    SingleModuleGraphNode::VisitedModule { module, .. } => {
845                        (*module, module.ident().to_resolved().await?)
846                    }
847                };
848                Ok((ident.await?.path.clone(), module))
849            })
850            .try_join()
851            .await?;
852        let mut map: FxHashMap<FileSystemPath, Vec<ResolvedVc<Box<dyn Module>>>> =
853            FxHashMap::default();
854        for (path, module) in path_and_modules {
855            map.entry(path).or_default().push(module)
856        }
857        Ok(PathToModulesMap::cell(PathToModulesMap { map }))
858    }
859}
860
861#[turbo_tasks::value_impl]
862impl ImportTracer for ModuleGraphImportTracer {
863    #[turbo_tasks::function]
864    async fn get_traces(self: Vc<Self>, path: FileSystemPath) -> Result<Vc<ImportTraces>> {
865        let path_to_modules = self.path_to_modules().await?;
866        let Some(modules) = path_to_modules.map.get(&path) else {
867            return Ok(Vc::default()); // This isn't unusual, the file just might not be in this
868            // graph.
869        };
870        debug_assert!(!modules.is_empty(), "modules should not be an empty vec");
871        let graph = &*self.await?.graph.await?;
872
873        let reversed_graph = Reversed(&graph.graph.0);
874        // A graph entry may have incoming edges when it participates in a cycle, so roots cannot
875        // be inferred from graph topology alone.
876        let root_nodes = graph.entry_nodes();
877        return Ok(ImportTraces::cell(ImportTraces(
878            modules
879                .iter()
880                .map(async |m| {
881                    let Some(&module_idx) = graph.modules.get(m) else {
882                        // The only way this could really happen is if `path_to_modules` is computed
883                        // from a different graph than graph`.  Just error out.
884                        bail!("inconsistent read?")
885                    };
886                    // Compute the path from this index to an explicit root of the graph.
887                    let path = match petgraph::algo::astar(
888                        &reversed_graph,
889                        module_idx,
890                        |n| root_nodes.contains(&n),
891                        // Edge weights
892                        |e| match e.weight().chunking_type {
893                            // Prefer following normal imports/requires when we can
894                            ChunkingType::Parallel { .. } => 0,
895                            _ => 1,
896                        },
897                        // `astar` can be accelerated with a distance estimation heuristic, as long
898                        // as our estimate is never > the actual distance.
899                        // However we don't have a mechanism, so just
900                        // estimate 0 which essentially makes this behave like
901                        // dijktra's shortest path algorithm.  `petgraph` has an implementation of
902                        // dijkstra's but it doesn't report  paths, just distances.
903                        // NOTE: dijkstra's with integer weights can be accelerated with incredibly
904                        // efficient priority queue structures (basically with only 0 and 1 as
905                        // weights you can use a `VecDeque`!).  However,
906                        // this is unlikely to be a performance concern.
907                        // Furthermore, if computing paths _does_ become a performance concern, the
908                        // solution would be a hand written implementation of dijkstras so we can
909                        // hoist redundant work out of this loop.
910                        |_| 0,
911                    ) {
912                        Some((_, path)) => path,
913                        None => {
914                            let module = graph
915                                .graph
916                                .node_weight(module_idx)
917                                .expect("module index must be present in the graph")
918                                .module();
919                            AnalyzeIssue::new(
920                                IssueSeverity::Bug,
921                                module.ident(),
922                                rcstr!("Module graph is missing an entry point"),
923                                rcstr!(
924                                    "The module cannot reach any of the explicit entry points in \
925                                     its module graph."
926                                ),
927                                None,
928                                None,
929                            )
930                            .to_resolved()
931                            .await?
932                            .emit();
933                            vec![module_idx]
934                        }
935                    };
936
937                    // Represent the path as a sequence of AssetIdents
938                    // TODO: consider hinting at various transitions (e.g. was this an
939                    // import/require/dynamic-import?)
940                    let path = path
941                        .into_iter()
942                        .map(|n| {
943                            graph
944                                .graph
945                                .node_weight(n)
946                                .unwrap() // This is safe since `astar`` only returns indices from the graph
947                                .module()
948                                .ident()
949                        })
950                        .try_join()
951                        .await?;
952                    Ok(path)
953                })
954                .try_join()
955                .await?,
956        )));
957    }
958}
959
960/// The ReadRef version of ModuleGraphBase. This is better for eventual consistency, as the graphs
961/// aren't awaited multiple times within the same task.
962#[turbo_tasks::value(shared, serialization = "skip", eq = "manual", cell = "new")]
963pub struct ModuleGraph {
964    input_graphs: Vec<OperationVc<SingleModuleGraph>>,
965    input_binding_usage: Option<OperationVc<BindingUsageInfo>>,
966
967    snapshot: ModuleGraphSnapshot,
968}
969
970#[turbo_tasks::value_impl]
971impl ModuleGraph {
972    /// Analyze the module graph and potentially remove unused references (by determining the used
973    /// exports and removing unused imports).
974    #[turbo_tasks::function(operation)]
975    pub async fn from_graphs(
976        graphs: Vec<OperationVc<SingleModuleGraph>>,
977        binding_usage: Option<OperationVc<BindingUsageInfo>>,
978    ) -> Result<Vc<Self>> {
979        let graph = Self::from_graphs_inner(graphs, binding_usage)
980            .read_strongly_consistent()
981            .await?;
982
983        Ok(ReadRef::cell(graph))
984    }
985
986    #[turbo_tasks::function(operation, root)]
987    async fn from_graphs_inner(
988        graphs: Vec<OperationVc<SingleModuleGraph>>,
989        binding_usage: Option<OperationVc<BindingUsageInfo>>,
990    ) -> Result<Vc<ModuleGraph>> {
991        Ok(ModuleGraph {
992            input_graphs: graphs.clone(),
993            input_binding_usage: binding_usage,
994            snapshot: ModuleGraphSnapshot {
995                graphs: graphs.iter().map(|g| g.connect()).try_join().await?,
996                skip_visited_module_children: false,
997                graph_idx_override: None,
998                unused_references_edges: if let Some(binding_usage) = binding_usage {
999                    Some(binding_usage.connect().unused_references_edges().await?)
1000                } else {
1001                    None
1002                },
1003                entry_ranks: OnceLock::new(),
1004            },
1005        }
1006        .cell())
1007    }
1008
1009    /// Whether the graph was built with [`ModuleGraphOptions::force_activated`], so its
1010    /// activatable modules have to generate the code of an active module. Errors if the graph
1011    /// combines graphs built with and without it, since activatable modules in the others would
1012    /// lack the references that active code needs.
1013    #[turbo_tasks::function]
1014    pub async fn force_activated(self: Vc<Self>) -> Result<Vc<bool>> {
1015        let this = self.await?;
1016        let graphs = &this.snapshot.graphs;
1017        let force_activated = graphs.iter().any(|graph| graph.force_activated);
1018        if force_activated && !graphs.iter().all(|graph| graph.force_activated) {
1019            bail!("graphs built with and without `force_activated` can't be combined");
1020        }
1021        Ok(Vc::cell(force_activated))
1022    }
1023
1024    #[turbo_tasks::function]
1025    pub async fn collected_modules(self: Vc<Self>) -> Result<Vc<CollectedModules>> {
1026        collect_graph(self).await
1027    }
1028
1029    #[turbo_tasks::function]
1030    pub async fn chunk_group_info(self: Vc<Self>) -> Result<Vc<ChunkGroupInfo>> {
1031        let collected_modules = self.collected_modules().await?;
1032        compute_chunk_group_info(&*self.await?, &collected_modules).await
1033    }
1034
1035    #[turbo_tasks::function]
1036    pub async fn merged_modules(self: Vc<Self>) -> Result<Vc<MergedModuleInfo>> {
1037        compute_merged_modules(self).await
1038    }
1039
1040    #[turbo_tasks::function]
1041    pub async fn module_batches(
1042        self: Vc<Self>,
1043        config: Vc<BatchingConfig>,
1044    ) -> Result<Vc<ModuleBatchesGraph>> {
1045        compute_module_batches(self, &*config.await?).await
1046    }
1047
1048    #[turbo_tasks::function]
1049    pub async fn style_groups(
1050        self: Vc<Self>,
1051        chunking_context: Vc<Box<dyn ChunkingContext>>,
1052        config: StyleGroupsConfig,
1053    ) -> Result<Vc<StyleGroups>> {
1054        match &config.algorithm {
1055            StyleGroupsAlgorithm::Default => {
1056                compute_style_groups(self, chunking_context, &config).await
1057            }
1058            StyleGroupsAlgorithm::Graph {
1059                weight_distribution,
1060                request_cost,
1061            } => {
1062                compute_style_groups_graph(
1063                    self,
1064                    chunking_context,
1065                    request_cost.get(),
1066                    weight_distribution.get(),
1067                    config.max_chunk_size as u64,
1068                )
1069                .await
1070            }
1071        }
1072    }
1073
1074    #[turbo_tasks::function(root)]
1075    pub async fn async_module_info(self: Vc<Self>) -> Result<Vc<AsyncModulesInfo>> {
1076        // `compute_async_module_info` calls `module.is_self_async()`, so we need to again ignore
1077        // all issues such that they aren't emitted multiple times.
1078        async move {
1079            let result_op = compute_async_module_info(self.to_resolved().await?);
1080            let result_vc = result_op.resolve().strongly_consistent().await?;
1081            result_op.drop_collectibles::<Box<dyn Issue>>();
1082            anyhow::Ok(*result_vc)
1083        }
1084        .instrument(tracing::info_span!("compute async module info"))
1085        .await
1086    }
1087
1088    /// Whether the graph contains any async module (see [`ModuleGraph::async_module_info`]).
1089    ///
1090    /// Prefer this over reading the whole [`AsyncModulesInfo`] set just to check emptiness: the
1091    /// result is a `bool` cell, so dependents are only invalidated when the set transitions
1092    /// between empty and nonempty, not on every change of its members.
1093    #[turbo_tasks::function]
1094    pub async fn has_async_modules(self: Vc<Self>) -> Result<Vc<bool>> {
1095        Ok(Vc::cell(!self.async_module_info().await?.is_empty()))
1096    }
1097
1098    #[turbo_tasks::function]
1099    pub async fn referenced_async_modules(
1100        self: Vc<Self>,
1101        module: ResolvedVc<Box<dyn Module>>,
1102    ) -> Result<Vc<AsyncModuleInfo>> {
1103        let graph_ref = self.await?;
1104        let async_module_info = self.async_module_info();
1105
1106        let entry = graph_ref.get_entry(module)?;
1107        let referenced_modules = graph_ref
1108            .iter_graphs_neighbors_rev(entry, Direction::Outgoing, false, false)
1109            .filter(|(edge_idx, _)| {
1110                let ty = graph_ref.get_edge(*edge_idx).unwrap();
1111                ty.chunking_type.is_inherit_async()
1112            })
1113            .map(|(_, child_idx)| anyhow::Ok(graph_ref.get_node(child_idx)?.module()))
1114            .collect::<Result<Vec<_>>>()?
1115            .into_iter()
1116            .rev()
1117            .map(async |m| Ok(async_module_info.is_async(m).await?.then_some(*m)))
1118            .try_flat_join()
1119            .await?;
1120
1121        Ok(AsyncModuleInfo::new(referenced_modules))
1122    }
1123
1124    /// Returns the underlying graphs as a list, to be used for individual graph traversals.
1125    #[turbo_tasks::function]
1126    pub fn iter_graphs(&self) -> Vc<ModuleGraphLayers> {
1127        Vc::cell(
1128            self.input_graphs
1129                .iter()
1130                .enumerate()
1131                .map(|(graph_idx, graph)| {
1132                    ModuleGraphLayer::new(*graph, graph_idx as u32, self.input_binding_usage)
1133                })
1134                .collect(),
1135        )
1136    }
1137}
1138
1139impl Deref for ModuleGraph {
1140    type Target = ModuleGraphSnapshot;
1141
1142    fn deref(&self) -> &Self::Target {
1143        &self.snapshot
1144    }
1145}
1146
1147#[turbo_tasks::value(shared, serialization = "skip", eq = "manual", cell = "new")]
1148pub struct ModuleGraphLayer {
1149    snapshot: ModuleGraphSnapshot,
1150}
1151
1152#[turbo_tasks::value_impl]
1153impl ModuleGraphLayer {
1154    #[turbo_tasks::function(operation, root)]
1155    async fn new(
1156        graph: OperationVc<SingleModuleGraph>,
1157        graph_idx: u32,
1158        binding_usage: Option<OperationVc<BindingUsageInfo>>,
1159    ) -> Result<Vc<Self>> {
1160        Ok(Self {
1161            snapshot: ModuleGraphSnapshot {
1162                graphs: vec![graph.connect().await?],
1163                skip_visited_module_children: true,
1164                graph_idx_override: Some(graph_idx),
1165                unused_references_edges: if let Some(binding_usage) = binding_usage {
1166                    Some(binding_usage.connect().unused_references_edges().await?)
1167                } else {
1168                    None
1169                },
1170                entry_ranks: OnceLock::new(),
1171            },
1172        }
1173        .cell())
1174    }
1175}
1176
1177impl Deref for ModuleGraphLayer {
1178    type Target = ModuleGraphSnapshot;
1179
1180    fn deref(&self) -> &Self::Target {
1181        &self.snapshot
1182    }
1183}
1184
1185#[turbo_tasks::value(transparent)]
1186pub struct ModuleGraphLayers(Vec<OperationVc<ModuleGraphLayer>>);
1187
1188/// The reverse postorder rank of each module, see [`ModuleGraphSnapshot::reverse_postorder_ranks`].
1189type ModuleRanks = FxHashMap<ResolvedVc<Box<dyn Module>>, usize>;
1190
1191/// This struct provides traversal functionality for the module graph.
1192///
1193/// Some edges might be ignored during traversal: unused references listed in
1194/// unused_references_edges and references with ChunkingType::Traced are skipped by default (can be
1195/// overridden in some functions via the include_unused and include_traced parameters).
1196///
1197/// The API across the functions is pretty consistent, apart from:
1198/// - traverse_edges_fixed_point_with_priority additionally provides the GraphEdgeIndex
1199/// - traverse_edges_dfs is the only function with include_traced and include_unused
1200#[derive(ValueDebugFormat, NonLocalValue)]
1201pub struct ModuleGraphSnapshot {
1202    // TODO make this non-public
1203    pub graphs: Vec<ReadRef<SingleModuleGraph>>,
1204    /// Whether to simply ignore SingleModuleGraphNode::VisitedModule during traversals. For single
1205    /// module graph usecases, this is what you want. For the whole graph, there should be an
1206    /// error.
1207    skip_visited_module_children: bool,
1208
1209    graph_idx_override: Option<u32>,
1210
1211    /// The edges of unused references (from [`BindingUsageInfo::unused_references_edges`]), which
1212    /// are skipped during traversals.
1213    unused_references_edges: Option<ReadRef<UnusedReferenceEdges>>,
1214
1215    /// Lazily computed [`Self::entry_ranks`] (or the error computing them). Derived from the
1216    /// immutable graphs, so it never needs to be invalidated.
1217    #[turbo_tasks(debug_ignore, unsafe_ignore)]
1218    entry_ranks: OnceLock<Result<ModuleRanks, SharedError>>,
1219}
1220
1221impl ModuleGraphSnapshot {
1222    fn get_entry(&self, entry: ResolvedVc<Box<dyn Module>>) -> Result<GraphNodeIndex> {
1223        if self.graph_idx_override.is_some() {
1224            debug_assert_eq!(self.graphs.len(), 1,);
1225        }
1226
1227        let Some(idx) = self
1228            .graphs
1229            .iter()
1230            .enumerate()
1231            .find_map(|(graph_idx, graph)| {
1232                graph.modules.get(&entry).map(|node_idx| GraphNodeIndex {
1233                    graph_idx: self.graph_idx_override.unwrap_or(graph_idx as u32),
1234                    node_idx: *node_idx,
1235                })
1236            })
1237        else {
1238            bail!("Couldn't find entry module {entry:?} in module graph");
1239        };
1240        Ok(idx)
1241    }
1242
1243    /// The entry modules of all chunk groups of all graphs.
1244    pub fn all_chunk_group_entries(&self) -> impl Iterator<Item = &ChunkGroupEntry> + '_ {
1245        self.graphs
1246            .iter()
1247            .flat_map(|g| g.entries.chunk_groups.iter())
1248    }
1249
1250    /// The entry modules of all chunk groups of all graphs.
1251    pub fn all_chunk_group_entry_modules(
1252        &self,
1253    ) -> impl Iterator<Item = ResolvedVc<Box<dyn Module>>> + '_ {
1254        self.graphs
1255            .iter()
1256            .flat_map(|g| g.entries.chunk_group_modules())
1257    }
1258
1259    /// The entry modules of all chunk groups of all graphs. Includes traced entry modules
1260    pub fn all_entry_modules(&self) -> impl Iterator<Item = ResolvedVc<Box<dyn Module>>> + '_ {
1261        self.graphs.iter().flat_map(|g| g.entries.all_modules())
1262    }
1263
1264    fn get_graph(&self, graph_idx: u32) -> &ReadRef<SingleModuleGraph> {
1265        if self.graph_idx_override.is_some() {
1266            self.graphs.first().unwrap()
1267        } else {
1268            &self.graphs[graph_idx as usize]
1269        }
1270    }
1271
1272    fn get_node(&self, node: GraphNodeIndex) -> Result<&SingleModuleGraphNode> {
1273        let graph = self.get_graph(node.graph_idx);
1274        graph
1275            .graph
1276            .node_weight(node.node_idx)
1277            .context("Expected graph node")
1278    }
1279
1280    fn get_edge(&self, edge: GraphEdgeIndex) -> Result<&RefData> {
1281        let graph = self.get_graph(edge.graph_idx);
1282        graph
1283            .graph
1284            .edge_weight(edge.edge_idx)
1285            .context("Expected graph node")
1286    }
1287
1288    fn should_visit_node(&self, node: &SingleModuleGraphNode, direction: Direction) -> bool {
1289        if self.skip_visited_module_children && direction == Direction::Outgoing {
1290            !matches!(node, SingleModuleGraphNode::VisitedModule { .. })
1291        } else {
1292            true
1293        }
1294    }
1295
1296    /// WARNING: using this is discouraged, as it doesn't filter out unused or traced references.
1297    /// Use iter_reachable_modules or one of the .traverse_* functions instead.
1298    pub fn enumerate_nodes(
1299        &self,
1300    ) -> impl Iterator<Item = (NodeIndex, &'_ SingleModuleGraphNode)> + '_ {
1301        self.graphs.iter().flat_map(|g| g.enumerate_nodes())
1302    }
1303
1304    /// WARNING: using this is discouraged, as it doesn't filter out unused or traced references.
1305    /// Use iter_reachable_modules or one of the .traverse_* functions instead.
1306    pub fn iter_nodes(&self) -> impl Iterator<Item = ResolvedVc<Box<dyn Module>>> + '_ {
1307        self.graphs.iter().flat_map(|g| g.iter_nodes())
1308    }
1309
1310    /// Iterate the edges of a node REVERSED!
1311    fn iter_graphs_neighbors_rev<'a>(
1312        &'a self,
1313        node: GraphNodeIndex,
1314        direction: Direction,
1315        include_traced: bool,
1316        include_unused: bool,
1317    ) -> impl Iterator<Item = (GraphEdgeIndex, GraphNodeIndex)> + 'a {
1318        let graph = &*self.get_graph(node.graph_idx).graph;
1319
1320        if cfg!(debug_assertions) && direction == Direction::Outgoing {
1321            let node_weight = graph.node_weight(node.node_idx).unwrap();
1322            if let SingleModuleGraphNode::VisitedModule { .. } = node_weight {
1323                panic!("iter_graphs_neighbors_rev called on VisitedModule node");
1324            }
1325        }
1326
1327        let mut walker = graph.neighbors_directed(node.node_idx, direction).detach();
1328        std::iter::from_fn(move || {
1329            while let Some((edge_idx, succ_idx)) = walker.next(graph) {
1330                let edge_idx = GraphEdgeIndex::new(node.graph_idx, edge_idx);
1331                if !include_unused
1332                    && self
1333                        .unused_references_edges
1334                        .as_ref()
1335                        .is_some_and(|edges| edges.contains(&edge_idx))
1336                {
1337                    // Don't just return None here, that would end the iterator
1338                    continue;
1339                }
1340
1341                if !include_traced && self.get_edge(edge_idx).unwrap().chunking_type.is_traced() {
1342                    continue;
1343                }
1344
1345                return Some((edge_idx, GraphNodeIndex::new(node.graph_idx, succ_idx)));
1346            }
1347            None
1348        })
1349    }
1350
1351    /// Returns a map of all modules in the graphs to their identifiers.
1352    /// This is primarily useful for debugging.
1353    pub async fn get_ids(&self) -> Result<FxHashMap<ResolvedVc<Box<dyn Module>>, ReadRef<RcStr>>> {
1354        self.iter_nodes()
1355            .map(async |n| Ok((n, n.ident_string().await?)))
1356            .join()
1357            .await
1358            .into_iter()
1359            .collect()
1360    }
1361
1362    /// Returns a module's eagerly-resolved `AssetIdent` `Vc`. Idents are always collected, and
1363    /// `get_entry` only resolves a module to its `Module` node, so this always finds one. The
1364    /// returned `ResolvedVc` is read tracked by callers.
1365    pub fn module_ident(
1366        &self,
1367        module: ResolvedVc<Box<dyn Module>>,
1368    ) -> Result<ResolvedVc<AssetIdent>> {
1369        let idx = self.get_entry(module)?;
1370        self.node_ident(idx)
1371            .context("get_entry resolves a module to its Module node")
1372    }
1373
1374    /// Returns a module's eagerly-resolved `ident_string()` `Vc`.
1375    ///
1376    /// Requires the graph to have been built with [`ModuleGraphOptions::include_ident_strings`];
1377    /// `bail!`s otherwise. Asking a graph for an ident string it never collected is a programming
1378    /// error — only the whole-app/CLI-build graphs that run the module-id strategy set the bit, and
1379    /// those are exactly the graphs this is called on.
1380    pub fn module_ident_string(
1381        &self,
1382        module: ResolvedVc<Box<dyn Module>>,
1383    ) -> Result<ResolvedVc<RcStr>> {
1384        let idx = self.get_entry(module)?;
1385        node_column(
1386            &self.get_graph(idx.graph_idx).ident_strings,
1387            idx,
1388            "module_ident_string() requires the module graph to be built with \
1389             `ModuleGraphOptions::include_ident_strings`",
1390        )?
1391        .context("get_entry resolves a module to its Module node")
1392    }
1393
1394    /// The eagerly-resolved ident of a `Module` node, or `None` for a `VisitedModule` node (whose
1395    /// ident lives in the graph that owns the module).
1396    pub fn node_ident(&self, node: GraphNodeIndex) -> Option<ResolvedVc<AssetIdent>> {
1397        self.get_graph(node.graph_idx)
1398            .idents
1399            .get(node.node_idx.index())
1400            .copied()
1401    }
1402
1403    /// The eagerly-resolved `is_self_async()` of a `Module` node, or `None` for a `VisitedModule`
1404    /// node.
1405    pub fn node_is_self_async(&self, node: GraphNodeIndex) -> Option<ResolvedVc<bool>> {
1406        self.get_graph(node.graph_idx)
1407            .is_self_async
1408            .get(node.node_idx.index())
1409            .copied()
1410    }
1411
1412    /// The eagerly-resolved `side_effects()` of a `Module` node, or `None` for a `VisitedModule`
1413    /// node. `bail!`s unless the graph was built with
1414    /// [`ModuleGraphOptions::include_side_effects`].
1415    pub fn node_side_effects(
1416        &self,
1417        node: GraphNodeIndex,
1418    ) -> Result<Option<ResolvedVc<ModuleSideEffects>>> {
1419        node_column(
1420            &self.get_graph(node.graph_idx).side_effects,
1421            node,
1422            "side effects require the module graph to be built with \
1423             `ModuleGraphOptions::include_side_effects`",
1424        )
1425    }
1426
1427    /// The eagerly-resolved `is_mergeable()` of a `Module` node (`false` for modules that don't
1428    /// implement [`MergeableModule`]), or `None` for a `VisitedModule` node. `bail!`s unless the
1429    /// graph was built with [`ModuleGraphOptions::include_mergeable`].
1430    pub fn node_is_mergeable(&self, node: GraphNodeIndex) -> Result<Option<ResolvedVc<bool>>> {
1431        node_column(
1432            &self.get_graph(node.graph_idx).is_mergeable,
1433            node,
1434            "mergeability requires the module graph to be built with \
1435             `ModuleGraphOptions::include_mergeable`",
1436        )
1437    }
1438
1439    /// Iterates every `Module` node of every graph with its eagerly-resolved ident. Unlike
1440    /// [`Self::module_ident`], this needs no lookup per module.
1441    pub fn iter_modules_with_idents(
1442        &self,
1443    ) -> impl Iterator<Item = (ResolvedVc<Box<dyn Module>>, ResolvedVc<AssetIdent>)> + '_ {
1444        self.graphs
1445            .iter()
1446            .flat_map(|g| g.iter_modules_with_idents())
1447    }
1448
1449    /// Traverses all reachable nodes exactly once and calls the visitor.
1450    ///
1451    /// * `entries` - The entry modules to start the traversal from
1452    /// * `state` mutable state to be shared across the visitors
1453    /// * `visit_preorder` - Called before visiting the children of a node.
1454    ///    - Receives the module and the `state`
1455    ///    - Can return [GraphTraversalAction]s to control the traversal
1456    /// * `visit_postorder` - Called after visiting children of a node.
1457    pub fn traverse_nodes_dfs<S>(
1458        &self,
1459        entries: impl IntoIterator<Item = ResolvedVc<Box<dyn Module>>>,
1460        state: &mut S,
1461        visit_preorder: impl Fn(ResolvedVc<Box<dyn Module>>, &mut S) -> Result<GraphTraversalAction>,
1462        mut visit_postorder: impl FnMut(ResolvedVc<Box<dyn Module>>, &mut S) -> Result<()>,
1463    ) -> Result<()> {
1464        let entries = entries.into_iter().collect::<Vec<_>>();
1465
1466        enum Pass {
1467            Visit,
1468            ExpandAndVisit,
1469        }
1470        let mut stack: Vec<(Pass, GraphNodeIndex)> = Vec::with_capacity(entries.len());
1471        for entry in entries.into_iter().rev() {
1472            stack.push((Pass::ExpandAndVisit, self.get_entry(entry)?));
1473        }
1474        let mut expanded = FxHashSet::default();
1475        while let Some((pass, current)) = stack.pop() {
1476            let current_node = self.get_node(current)?;
1477            match pass {
1478                Pass::Visit => {
1479                    visit_postorder(current_node.module(), state)?;
1480                }
1481                Pass::ExpandAndVisit => {
1482                    if !expanded.insert(current) {
1483                        continue;
1484                    }
1485                    let action = visit_preorder(current_node.module(), state)?;
1486                    if action == GraphTraversalAction::Exclude {
1487                        continue;
1488                    }
1489                    stack.push((Pass::Visit, current));
1490                    if action == GraphTraversalAction::Continue
1491                        && self.should_visit_node(current_node, Direction::Outgoing)
1492                    {
1493                        let current = current_node
1494                            .target_idx(Direction::Outgoing)
1495                            .unwrap_or(current);
1496                        stack.extend(
1497                            self.iter_graphs_neighbors_rev(
1498                                current,
1499                                Direction::Outgoing,
1500                                false,
1501                                false,
1502                            )
1503                            .map(|(_, child)| (Pass::ExpandAndVisit, child)),
1504                        );
1505                    }
1506                }
1507            }
1508        }
1509
1510        Ok(())
1511    }
1512
1513    /// Traverses all reachable edges exactly once and calls the visitor with the edge source and
1514    /// target.
1515    ///
1516    /// This means that target nodes can be revisited (once per incoming edge).
1517    ///
1518    /// * `entry` - The entry module to start the traversal from
1519    /// * `visitor` - Called before visiting the children of a node.
1520    ///    - Receives (originating &SingleModuleGraphNode, edge &ChunkingType), target
1521    ///      &SingleModuleGraphNode, state &S
1522    ///    - Can return [GraphTraversalAction]s to control the traversal
1523    pub fn traverse_edges_bfs(
1524        &self,
1525        entries: impl IntoIterator<Item = ResolvedVc<Box<dyn Module>>>,
1526        mut visitor: impl FnMut(
1527            Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
1528            ResolvedVc<Box<dyn Module>>,
1529        ) -> Result<GraphTraversalAction>,
1530    ) -> Result<()> {
1531        let mut queue = VecDeque::from(
1532            entries
1533                .into_iter()
1534                .map(|e| self.get_entry(e))
1535                .collect::<Result<Vec<_>>>()?,
1536        );
1537        let mut visited = FxHashSet::default();
1538        for entry_node in &queue {
1539            visitor(None, self.get_node(*entry_node)?.module())?;
1540        }
1541        while let Some(node) = queue.pop_front() {
1542            if visited.insert(node) {
1543                let node_weight = self.get_node(node)?;
1544                for (edge, succ) in
1545                    self.iter_graphs_neighbors_rev(node, Direction::Outgoing, false, false)
1546                {
1547                    let succ_weight = self.get_node(succ)?;
1548                    let action = visitor(
1549                        Some((node_weight.module(), self.get_edge(edge)?)),
1550                        succ_weight.module(),
1551                    )?;
1552                    if !self.should_visit_node(succ_weight, Direction::Outgoing) {
1553                        continue;
1554                    }
1555                    let succ = succ_weight.target_idx(Direction::Outgoing).unwrap_or(succ);
1556                    if !visited.contains(&succ) && action == GraphTraversalAction::Continue {
1557                        queue.push_back(succ);
1558                    }
1559                }
1560            }
1561        }
1562
1563        Ok(())
1564    }
1565
1566    /// Traverses all edges exactly once (in an unspecified order) and calls the visitor with the
1567    /// edge source and target.
1568    ///
1569    /// This means that target nodes can be revisited (once per incoming edge).
1570    ///
1571    /// * `visitor` - Called before visiting the children of a node.
1572    ///    - Receives (originating &SingleModuleGraphNode, edge &ChunkingType), target
1573    ///      &SingleModuleGraphNode
1574    pub fn traverse_edges_unordered(
1575        &self,
1576        mut visitor: impl FnMut(
1577            Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
1578            ResolvedVc<Box<dyn Module>>,
1579        ) -> Result<()>,
1580    ) -> Result<()> {
1581        // Despite the name we need to do a DFS to respect 'reachability' if an edge was trimmed we
1582        // should not follow it, and this is a reasonable way to do that.
1583        self.traverse_edges_dfs(
1584            self.all_chunk_group_entry_modules(),
1585            &mut (),
1586            |parent, target, _| {
1587                visitor(parent, target)?;
1588                Ok(GraphTraversalAction::Continue)
1589            },
1590            |_, _, _| Ok(()),
1591            false,
1592            false,
1593        )
1594    }
1595
1596    /// Traverses all reachable edges in dfs order. The preorder visitor can be used to
1597    /// forward state down the graph, and to skip subgraphs
1598    ///
1599    /// Use this to collect modules in evaluation order.
1600    ///
1601    /// Target nodes can be revisited (once per incoming edge) in the preorder_visitor, in the post
1602    /// order visitor they are visited exactly once with the first edge they were discovered with.
1603    /// Edges are traversed in normal order, so should correspond to reference order.
1604    ///
1605    /// * `entries` - The entry modules to start the traversal from
1606    /// * `state` - The state to be passed to the visitors
1607    /// * `visit_preorder` - Called before visiting the children of a node.
1608    ///    - Receives: (originating &SingleModuleGraphNode, edge &ChunkingType), target
1609    ///      &SingleModuleGraphNode, state &S
1610    ///    - Can return [GraphTraversalAction]s to control the traversal
1611    /// * `visit_postorder` - Called after visiting the children of a node. Return
1612    ///    - Receives: (originating &SingleModuleGraphNode, edge &ChunkingType), target
1613    ///      &SingleModuleGraphNode, state &S
1614    /// * `include_traced` - Include references with ChunkingType::Traced.
1615    /// * `include_unused` - Include references marked unused by binding usage.
1616    pub fn traverse_edges_dfs<S>(
1617        &self,
1618        entries: impl IntoIterator<Item = ResolvedVc<Box<dyn Module>>>,
1619        state: &mut S,
1620        visit_preorder: impl FnMut(
1621            Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
1622            ResolvedVc<Box<dyn Module>>,
1623            &mut S,
1624        ) -> Result<GraphTraversalAction>,
1625        visit_postorder: impl FnMut(
1626            Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
1627            ResolvedVc<Box<dyn Module>>,
1628            &mut S,
1629        ) -> Result<()>,
1630        include_traced: bool,
1631        include_unused: bool,
1632    ) -> Result<()> {
1633        self.traverse_edges_dfs_impl::<S>(
1634            entries,
1635            state,
1636            visit_preorder,
1637            visit_postorder,
1638            Direction::Outgoing,
1639            include_traced,
1640            include_unused,
1641        )
1642    }
1643
1644    /// Traverses all reachable edges in dfs order over the reversed graph. The preorder visitor can
1645    /// be used to forward state up the graph, and to skip subgraphs
1646    ///
1647    /// Target nodes can be revisited (once per incoming edge) in the preorder_visitor, in the post
1648    /// order visitor they are visited exactly once with the first edge they were discovered with.
1649    /// Edges are traversed in normal order, so should correspond to reference order.
1650    ///
1651    /// * `entries` - The entry modules to start the traversal from
1652    /// * `state` - The state to be passed to the visitors
1653    /// * `visit_preorder` - Called before visiting the children of a node.
1654    ///    - Receives: (originating &SingleModuleGraphNode, edge &ChunkingType), target
1655    ///      &SingleModuleGraphNode, state &S
1656    ///    - Can return [GraphTraversalAction]s to control the traversal
1657    /// * `visit_postorder` - Called after visiting the parents of a node. Return
1658    ///    - Receives: (originating &SingleModuleGraphNode, edge &ChunkingType), target
1659    ///      &SingleModuleGraphNode, state &S
1660    pub fn traverse_edges_reverse_dfs<S>(
1661        &self,
1662        entries: impl IntoIterator<Item = ResolvedVc<Box<dyn Module>>>,
1663        state: &mut S,
1664        visit_preorder: impl FnMut(
1665            Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
1666            ResolvedVc<Box<dyn Module>>,
1667            &mut S,
1668        ) -> Result<GraphTraversalAction>,
1669        visit_postorder: impl FnMut(
1670            Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
1671            ResolvedVc<Box<dyn Module>>,
1672            &mut S,
1673        ) -> Result<()>,
1674    ) -> Result<()> {
1675        self.traverse_edges_dfs_impl::<S>(
1676            entries,
1677            state,
1678            visit_preorder,
1679            visit_postorder,
1680            Direction::Incoming,
1681            false,
1682            false,
1683        )
1684    }
1685
1686    fn traverse_edges_dfs_impl<S>(
1687        &self,
1688        entries: impl IntoIterator<Item = ResolvedVc<Box<dyn Module>>>,
1689        state: &mut S,
1690        mut visit_preorder: impl FnMut(
1691            Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
1692            ResolvedVc<Box<dyn Module>>,
1693            &mut S,
1694        ) -> Result<GraphTraversalAction>,
1695        mut visit_postorder: impl FnMut(
1696            Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
1697            ResolvedVc<Box<dyn Module>>,
1698            &mut S,
1699        ) -> Result<()>,
1700        direction: Direction,
1701        include_traced: bool,
1702        include_unused: bool,
1703    ) -> Result<()> {
1704        if direction == Direction::Incoming {
1705            debug_assert!(
1706                self.skip_visited_module_children,
1707                "Can only trace reverse edges in a single layer graph. We do not model cross \
1708                 graph reverse edges"
1709            );
1710        }
1711        let entries = entries.into_iter().collect::<Vec<_>>();
1712
1713        enum Pass {
1714            Visit,
1715            ExpandAndVisit,
1716        }
1717        #[allow(clippy::type_complexity)] // This is a temporary internal structure
1718        let mut stack: Vec<(
1719            Pass,
1720            Option<(GraphNodeIndex, GraphEdgeIndex)>,
1721            GraphNodeIndex,
1722        )> = Vec::with_capacity(entries.len());
1723        for entry in entries.into_iter().rev() {
1724            stack.push((Pass::ExpandAndVisit, None, self.get_entry(entry)?));
1725        }
1726        let mut expanded = FxHashSet::default();
1727        while let Some((pass, parent, current)) = stack.pop() {
1728            let parent_arg = match parent {
1729                Some((parent_node, parent_edge)) => Some((
1730                    self.get_node(parent_node)?.module(),
1731                    self.get_edge(parent_edge)?,
1732                )),
1733                None => None,
1734            };
1735            let current_node = self.get_node(current)?;
1736            match pass {
1737                Pass::Visit => {
1738                    visit_postorder(parent_arg, current_node.module(), state)?;
1739                }
1740                Pass::ExpandAndVisit => {
1741                    let action = visit_preorder(parent_arg, current_node.module(), state)?;
1742                    if action == GraphTraversalAction::Exclude {
1743                        continue;
1744                    }
1745                    stack.push((Pass::Visit, parent, current));
1746                    if action == GraphTraversalAction::Continue
1747                        && expanded.insert(current)
1748                        && self.should_visit_node(current_node, direction)
1749                    {
1750                        let current = current_node.target_idx(direction).unwrap_or(current);
1751                        stack.extend(
1752                            self.iter_graphs_neighbors_rev(
1753                                current,
1754                                direction,
1755                                include_traced,
1756                                include_unused,
1757                            )
1758                            .map(|(edge, child)| {
1759                                (Pass::ExpandAndVisit, Some((current, edge)), child)
1760                            }),
1761                        );
1762                    }
1763                }
1764            }
1765        }
1766
1767        Ok(())
1768    }
1769
1770    /// Traverse all cycles in the graph (where the edge filter returns true for the whole cycle)
1771    /// and call the visitor with the nodes in the cycle.
1772    /// Notably, module self-references are also treated as cycles.
1773    pub fn traverse_cycles(
1774        &self,
1775        edge_filter: impl Fn(&RefData) -> bool,
1776        mut visit_cycle: impl FnMut(&[&ResolvedVc<Box<dyn Module>>]) -> Result<()>,
1777    ) -> Result<()> {
1778        for (graph_idx, graph) in self.graphs.iter().enumerate() {
1779            graph.traverse_cycles(
1780                &edge_filter,
1781                &mut visit_cycle,
1782                graph_idx as u32,
1783                &self.unused_references_edges,
1784            )?;
1785        }
1786        Ok(())
1787    }
1788
1789    /// Computes a priority for [`Self::traverse_edges_fixed_point_with_priority`] that
1790    /// minimizes the number of retraversals, as the *reverse postorder* of a depth-first search
1791    /// from `entries`.
1792    ///
1793    /// Every module reachable from `entries` (following the same edges as the fixed point
1794    /// traversal: traced and unused references are ignored) gets a unique rank. For every
1795    /// reference that is not a back edge of the depth-first search (every reference outside of a
1796    /// cycle is never a back edge), the importing module has a lower rank than the imported
1797    /// module. When the graph has no cycles, visiting lower ranks first (e.g. using
1798    /// [`std::cmp::Reverse`] as the priority, as the traversal visits high priorities first)
1799    /// therefore visits every module only after all of the modules importing it, so each module is
1800    /// visited exactly once. In contrast to using the BFS depth, a module is not revisited just
1801    /// because a longer path to it is processed later. Modules in or after a cycle can still be
1802    /// visited multiple times.
1803    ///
1804    /// Runs in linear time and without recursion.
1805    ///
1806    /// Must be called on the whole graph, not on an individual graph layer (where `VisitedModule`
1807    /// nodes can't be resolved).
1808    ///
1809    /// Use [`Self::entry_ranks`] for the ranks from the entries of the graph, which are computed
1810    /// once per snapshot. This is only for other roots, e.g. a subset of the entries.
1811    fn reverse_postorder_ranks(
1812        &self,
1813        entries: impl IntoIterator<Item = ResolvedVc<Box<dyn Module>>>,
1814    ) -> Result<FxHashMap<ResolvedVc<Box<dyn Module>>, usize>> {
1815        assert!(
1816            !self.skip_visited_module_children && self.graph_idx_override.is_none(),
1817            "reverse_postorder_ranks musn't be called on individual graphs"
1818        );
1819        // Nodes are identified by their canonical node (i.e. never a `VisitedModule`), which is
1820        // the node the fixed point traversal expands.
1821        let canonical = |node: GraphNodeIndex| -> Result<GraphNodeIndex> {
1822            Ok(self
1823                .get_node(node)?
1824                .target_idx(Direction::Outgoing)
1825                .unwrap_or(node))
1826        };
1827
1828        // Node indices of a `DiGraph` are dense, so a bitset per graph tracks the visited nodes.
1829        let mut visited = self
1830            .graphs
1831            .iter()
1832            .map(|g| FixedBitSet::with_capacity(g.graph.node_count()))
1833            .collect::<Vec<_>>();
1834        // Marks `node` as visited, returns whether it wasn't visited before.
1835        let mut visit =
1836            |node: GraphNodeIndex| !visited[node.graph_idx as usize].put(node.node_idx.index());
1837
1838        let mut postorder: Vec<GraphNodeIndex> = Vec::with_capacity(
1839            self.graphs
1840                .iter()
1841                .map(|g| g.graph.node_count())
1842                .sum::<usize>(),
1843        );
1844        let mut stack = Vec::new();
1845        for entry in entries {
1846            let entry = canonical(self.get_entry(entry)?)?;
1847            if !visit(entry) {
1848                continue;
1849            }
1850            stack.push((
1851                entry,
1852                self.iter_graphs_neighbors_rev(entry, Direction::Outgoing, false, false),
1853            ));
1854            while let Some((node, children)) = stack.last_mut() {
1855                if let Some((_, child)) = children.next() {
1856                    let child = canonical(child)?;
1857                    if visit(child) {
1858                        stack.push((
1859                            child,
1860                            self.iter_graphs_neighbors_rev(
1861                                child,
1862                                Direction::Outgoing,
1863                                false,
1864                                false,
1865                            ),
1866                        ));
1867                    }
1868                } else {
1869                    postorder.push(*node);
1870                    stack.pop();
1871                }
1872            }
1873        }
1874
1875        let count = postorder.len();
1876        let mut ranks = FxHashMap::with_capacity_and_hasher(count, Default::default());
1877        for (i, node) in postorder.into_iter().enumerate() {
1878            ranks.insert(self.get_node(node)?.module(), count - 1 - i);
1879        }
1880        Ok(ranks)
1881    }
1882
1883    /// A priority for [`Self::traverse_edges_fixed_point_with_priority`] that minimizes the number
1884    /// of retraversals: the rank of every module reachable from the entries of the graph, i.e. the
1885    /// entries of its chunk groups ([`Self::all_chunk_group_entry_modules`]), in the *reverse
1886    /// postorder* of a depth-first search from them.
1887    ///
1888    /// Traced and unused references are ignored, like in the fixed point traversal. For every
1889    /// reference outside of a cycle, the importing module has a lower rank than the imported
1890    /// module. So when the graph has no cycles, visiting lower ranks first (e.g. using
1891    /// [`std::cmp::Reverse`] as the priority, as the traversal visits high priorities first) visits
1892    /// every module only after all of the modules importing it, i.e. exactly once. Modules in or
1893    /// after a cycle can still be visited multiple times.
1894    ///
1895    /// They are computed on the first call and cached in this snapshot, so that all analyses of
1896    /// the same graph that need exactly these ranks share one computation. As the snapshot is
1897    /// immutable, the cached ranks always match the graph. They are computed only once, even with
1898    /// concurrent callers (which wait for the first one). An error is cached as well and returned
1899    /// to every caller.
1900    pub fn entry_ranks(&self) -> Result<&FxHashMap<ResolvedVc<Box<dyn Module>>, usize>> {
1901        self.entry_ranks
1902            .get_or_init(|| {
1903                self.reverse_postorder_ranks(self.all_chunk_group_entry_modules())
1904                    .map_err(SharedError::new)
1905            })
1906            .as_ref()
1907            .map_err(|err| err.clone().into())
1908    }
1909
1910    /// Traverses all reachable nodes and also continue revisiting them as long the visitor returns
1911    /// GraphTraversalAction::Continue. The visitor is responsible for the runtime complexity and
1912    /// eventual termination of the traversal. This corresponds to computing a fixed point state for
1913    /// the graph.
1914    ///
1915    /// Nodes are (re)visited according to the returned priority of the node, prioritizing high
1916    /// values. This priority is intended to be used a heuristic to reduce the number of
1917    /// retraversals. [`ModuleGraphSnapshot::entry_ranks`] computes a priority that
1918    /// avoids retraversals for all modules not in or after a cycle.
1919    ///
1920    /// * `entries` - The entry modules to start the traversal from
1921    /// * `state` - The state to be passed to the callbacks
1922    /// * `visit` - Called for a specific edge
1923    ///    - Receives: (originating &SingleModuleGraphNode, edge &ChunkingType), target
1924    ///      &SingleModuleGraphNode, state &S
1925    ///    - Return [GraphTraversalAction]s to control the traversal
1926    /// * `priority` - Called for before visiting the children of a node to determine its priority.
1927    ///    - Receives: target &SingleModuleGraphNode, state &S
1928    ///    - Return a priority value for the node
1929    ///
1930    /// Returns the number of node visits (i.e. higher than the node count if there are
1931    /// retraversals).
1932    pub fn traverse_edges_fixed_point_with_priority<'graph, S, P: Ord>(
1933        &'graph self,
1934        entries: impl IntoIterator<Item = (ResolvedVc<Box<dyn Module>>, P)>,
1935        state: &mut S,
1936        mut visit: impl FnMut(
1937            Option<(ResolvedVc<Box<dyn Module>>, &'graph RefData, GraphEdgeIndex)>,
1938            ResolvedVc<Box<dyn Module>>,
1939            GraphNodeIndex,
1940            &mut S,
1941        ) -> Result<GraphTraversalAction>,
1942        priority: impl Fn(ResolvedVc<Box<dyn Module>>, &mut S) -> Result<P>,
1943    ) -> Result<usize> {
1944        if self.skip_visited_module_children {
1945            panic!(
1946                "traverse_edges_fixed_point_with_priority musn't be called on individual graphs"
1947            );
1948        }
1949
1950        let mut visit_order = 0usize;
1951        let mut order = || {
1952            let order = visit_order;
1953            visit_order += 1;
1954            order
1955        };
1956        #[derive(PartialEq, Eq)]
1957        struct NodeWithPriority<T: Ord> {
1958            node: GraphNodeIndex,
1959            priority: T,
1960            visit_order: usize,
1961        }
1962        impl<T: Ord> PartialOrd for NodeWithPriority<T> {
1963            fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1964                Some(self.cmp(other))
1965            }
1966        }
1967        impl<T: Ord> Ord for NodeWithPriority<T> {
1968            fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1969                // BinaryHeap prioritizes high values
1970
1971                self.priority
1972                    .cmp(&other.priority)
1973                    // Use visit_order, so when there are ties we prioritize earlier discovered
1974                    // nodes, reverting to a BFS in the the case where all priorities are equal
1975                    .then(self.visit_order.cmp(&other.visit_order))
1976            }
1977        }
1978
1979        let mut queue_set = FxHashSet::default();
1980        let mut queue = BinaryHeap::new();
1981        for (m, priority) in entries {
1982            let node = self.get_entry(m)?;
1983            // Entries are tracked in `queue_set` like any other queued node, so that an entry
1984            // that is also reachable from another entry isn't queued (and visited) twice, and
1985            // duplicate entries are ignored.
1986            if queue_set.insert(node) {
1987                queue.push(NodeWithPriority {
1988                    node,
1989                    priority,
1990                    visit_order: order(),
1991                });
1992            }
1993        }
1994
1995        for entry_node in &queue {
1996            visit(
1997                None,
1998                self.get_node(entry_node.node)?.module(),
1999                entry_node.node,
2000                state,
2001            )?;
2002        }
2003
2004        let mut visit_count = 0usize;
2005        while let Some(NodeWithPriority { node, .. }) = queue.pop() {
2006            queue_set.remove(&node);
2007            let node_weight = self.get_node(node)?;
2008            let node = node_weight.target_idx(Direction::Outgoing).unwrap_or(node);
2009
2010            visit_count += 1;
2011
2012            for (edge, succ) in
2013                self.iter_graphs_neighbors_rev(node, Direction::Outgoing, false, false)
2014            {
2015                let succ_weight = self.get_node(succ)?;
2016
2017                let action = visit(
2018                    Some((node_weight.module(), self.get_edge(edge)?, edge)),
2019                    succ_weight.module(),
2020                    succ,
2021                    state,
2022                )?;
2023
2024                let succ = succ_weight.target_idx(Direction::Outgoing).unwrap_or(succ);
2025                if action == GraphTraversalAction::Continue && queue_set.insert(succ) {
2026                    queue.push(NodeWithPriority {
2027                        node: succ,
2028                        priority: priority(succ_weight.module(), state)?,
2029                        visit_order: order(),
2030                    });
2031                }
2032            }
2033        }
2034
2035        Ok(visit_count)
2036    }
2037
2038    /// Iterates all reachable modules in the graph, ignoring unused and traced references.
2039    pub fn iter_reachable_modules(
2040        &self,
2041    ) -> Result<impl Iterator<Item = ResolvedVc<Box<dyn Module>>>> {
2042        Ok(self.iter_reachable_nodes()?.filter_map(|(_, n)| match n {
2043            SingleModuleGraphNode::Module(m) => Some(*m),
2044            SingleModuleGraphNode::VisitedModule { .. } => None,
2045        }))
2046    }
2047
2048    /// Iterates all reachable nodes in the graph, ignoring unused and traced references.
2049    /// This includes VisitedModule nodes (which means that some modules are returned twice).
2050    pub fn iter_reachable_nodes<'a>(
2051        &'a self,
2052    ) -> Result<impl Iterator<Item = (GraphNodeIndex, &'a SingleModuleGraphNode)> + 'a> {
2053        ModuleGraphSnapshotNodeIterator::new(self)
2054    }
2055}
2056
2057struct ModuleGraphSnapshotNodeIterator<'a> {
2058    graph: &'a ModuleGraphSnapshot,
2059    visited: FxHashSet<GraphNodeIndex>,
2060    visit_queue: VecDeque<GraphNodeIndex>,
2061}
2062
2063impl<'a> ModuleGraphSnapshotNodeIterator<'a> {
2064    fn new(graph: &'a ModuleGraphSnapshot) -> Result<Self> {
2065        let entries = graph
2066            .graphs
2067            .iter()
2068            .flat_map(|g| g.chunk_group_modules())
2069            .map(|e| graph.get_entry(e))
2070            .collect::<Result<VecDeque<_>>>()?;
2071
2072        Ok(Self {
2073            graph,
2074            visited: FxHashSet::default(),
2075            visit_queue: entries,
2076        })
2077    }
2078}
2079impl<'a> Iterator for ModuleGraphSnapshotNodeIterator<'a> {
2080    type Item = (GraphNodeIndex, &'a SingleModuleGraphNode);
2081
2082    fn next(&mut self) -> Option<Self::Item> {
2083        while let Some(node_idx) = self.visit_queue.pop_front() {
2084            if self.visited.insert(node_idx) {
2085                let node_weight = self.graph.get_node(node_idx).unwrap();
2086                if self
2087                    .graph
2088                    .should_visit_node(node_weight, Direction::Outgoing)
2089                {
2090                    let node = node_weight
2091                        .target_idx(Direction::Outgoing)
2092                        .unwrap_or(node_idx);
2093                    self.visit_queue.extend(
2094                        self.graph
2095                            .iter_graphs_neighbors_rev(node, Direction::Outgoing, false, false)
2096                            .map(|(_, succ)| succ)
2097                            .filter(|succ| !self.visited.contains(succ)),
2098                    );
2099                }
2100                return Some((node_idx, node_weight));
2101            }
2102        }
2103        None
2104    }
2105}
2106impl FusedIterator for ModuleGraphSnapshotNodeIterator<'_> {}
2107
2108#[turbo_tasks::value_impl]
2109impl SingleModuleGraph {
2110    #[turbo_tasks::function(operation)]
2111    pub async fn new_with_entry(
2112        entry: ChunkGroupEntry,
2113        options: ModuleGraphOptions,
2114    ) -> Result<Vc<Self>> {
2115        SingleModuleGraph::new_inner(
2116            &GraphEntries::from_chunk_groups(vec![entry]),
2117            &Default::default(),
2118            options,
2119        )
2120        .await
2121    }
2122
2123    #[turbo_tasks::function(operation)]
2124    pub async fn new_with_entries(
2125        entries: ResolvedVc<GraphEntries>,
2126        options: ModuleGraphOptions,
2127    ) -> Result<Vc<Self>> {
2128        SingleModuleGraph::new_inner(&*entries.await?, &Default::default(), options).await
2129    }
2130
2131    #[turbo_tasks::function(operation)]
2132    pub async fn new_with_entries_visited(
2133        entries: ResolvedVc<GraphEntries>,
2134        visited_modules: OperationVc<VisitedModules>,
2135        options: ModuleGraphOptions,
2136    ) -> Result<Vc<Self>> {
2137        SingleModuleGraph::new_inner(
2138            &*entries.await?,
2139            &visited_modules.connect().await?.modules,
2140            options,
2141        )
2142        .await
2143    }
2144
2145    #[turbo_tasks::function(operation)]
2146    pub async fn new_with_entries_visited_intern(
2147        // This must not be a Vc<Vec<_>> to ensure layout segment optimization hits the cache
2148        entries: GraphEntries,
2149        visited_modules: OperationVc<VisitedModules>,
2150        options: ModuleGraphOptions,
2151    ) -> Result<Vc<Self>> {
2152        SingleModuleGraph::new_inner(&entries, &visited_modules.connect().await?.modules, options)
2153            .await
2154    }
2155
2156    #[turbo_tasks::function]
2157    pub async fn module_count(&self) -> Vc<u64> {
2158        Vc::cell(self.number_of_modules as u64)
2159    }
2160
2161    #[turbo_tasks::function]
2162    pub async fn edge_count(&self) -> Vc<u64> {
2163        Vc::cell(self.graph.edge_count() as u64)
2164    }
2165}
2166
2167#[derive(Clone, Debug, Serialize, Deserialize, NonLocalValue)]
2168pub enum SingleModuleGraphNode {
2169    Module(ResolvedVc<Box<dyn Module>>),
2170    // Models a module that is referenced but has already been visited by an earlier graph.
2171    VisitedModule {
2172        idx: GraphNodeIndex,
2173        module: ResolvedVc<Box<dyn Module>>,
2174    },
2175}
2176#[cfg(test)]
2177mod size_test {
2178    use crate::module_graph::SingleModuleGraphNode;
2179
2180    /// Guards the per-module node size — there is one of these per module in the graph, so growth
2181    /// here is multiplied across the whole app. Per-module data belongs in the
2182    /// `SingleModuleGraph` columns instead.
2183    #[test]
2184    pub fn test_size() {
2185        assert_eq!(16, size_of::<SingleModuleGraphNode>());
2186    }
2187}
2188
2189impl SingleModuleGraphNode {
2190    pub fn module(&self) -> ResolvedVc<Box<dyn Module>> {
2191        match self {
2192            SingleModuleGraphNode::Module(module) => *module,
2193            SingleModuleGraphNode::VisitedModule { module, .. } => *module,
2194        }
2195    }
2196
2197    pub fn target_idx(&self, direction: Direction) -> Option<GraphNodeIndex> {
2198        match self {
2199            SingleModuleGraphNode::VisitedModule { idx, .. } => match direction {
2200                Direction::Outgoing => Some(*idx),
2201                Direction::Incoming => None,
2202            },
2203            SingleModuleGraphNode::Module(_) => None,
2204        }
2205    }
2206}
2207
2208#[derive(PartialEq, Eq, Debug)]
2209pub enum GraphTraversalAction {
2210    /// Continue visiting children
2211    Continue,
2212    /// Skip the immediate children, but visit the node in postorder
2213    Skip,
2214    /// Skip the immediate children and the node in postorder
2215    Exclude,
2216}
2217
2218// These nodes are created while walking the Turbopack modules references, and are used to then
2219// afterwards build the SingleModuleGraph.
2220#[derive(Clone)]
2221enum SingleModuleGraphBuilderNode {
2222    /// A regular module
2223    Module {
2224        module: ResolvedVc<Box<dyn Module>>,
2225        /// The module's `ident().to_string()`, read (untracked) only when `emit_spans` so [`span`]
2226        /// can use it as the span name synchronously. Transient (never reaches the graph node) and
2227        /// excluded from `Hash`/`Eq`.
2228        ///
2229        /// [`span`]: SingleModuleGraphBuilder::span
2230        span_name: Option<ReadRef<RcStr>>,
2231        /// whether this module is a tracing context
2232        is_traced: bool,
2233    },
2234    /// A reference to a module that is already listed in visited_modules
2235    VisitedModule {
2236        module: ResolvedVc<Box<dyn Module>>,
2237        idx: GraphNodeIndex,
2238    },
2239}
2240
2241// `Hash`/`Eq` are implemented manually over the identity-determining fields only (`module` +
2242// `is_traced` / `idx`), deliberately excluding `ident`. This node is the `AdjacencyMap` visit dedup
2243// key; `ident` is fully determined by `module`, so including it would only waste cycles hashing a
2244// full `AssetIdent` per insert.
2245impl PartialEq for SingleModuleGraphBuilderNode {
2246    fn eq(&self, other: &Self) -> bool {
2247        match (self, other) {
2248            (
2249                SingleModuleGraphBuilderNode::Module {
2250                    module: l_module,
2251                    is_traced: l_is_traced,
2252                    ..
2253                },
2254                SingleModuleGraphBuilderNode::Module {
2255                    module: r_module,
2256                    is_traced: r_is_traced,
2257                    ..
2258                },
2259            ) => l_module == r_module && l_is_traced == r_is_traced,
2260            (
2261                SingleModuleGraphBuilderNode::VisitedModule {
2262                    module: l_module,
2263                    idx: l_idx,
2264                },
2265                SingleModuleGraphBuilderNode::VisitedModule {
2266                    module: r_module,
2267                    idx: r_idx,
2268                },
2269            ) => l_module == r_module && l_idx == r_idx,
2270            _ => false,
2271        }
2272    }
2273}
2274impl Eq for SingleModuleGraphBuilderNode {}
2275impl Hash for SingleModuleGraphBuilderNode {
2276    fn hash<H: Hasher>(&self, state: &mut H) {
2277        core::mem::discriminant(self).hash(state);
2278        match self {
2279            SingleModuleGraphBuilderNode::Module {
2280                module, is_traced, ..
2281            } => {
2282                module.hash(state);
2283                is_traced.hash(state);
2284            }
2285            SingleModuleGraphBuilderNode::VisitedModule { module, idx } => {
2286                module.hash(state);
2287                idx.hash(state);
2288            }
2289        }
2290    }
2291}
2292
2293/// Reads a node's entry from a per-module column of [`SingleModuleGraph`]: `None` for a
2294/// `VisitedModule` node, which sits past the end of every column. `bail!`s with `missing` when the
2295/// graph was built without collecting the column.
2296fn node_column<T: Copy>(
2297    column: &Option<Vec<T>>,
2298    node: GraphNodeIndex,
2299    missing: &'static str,
2300) -> Result<Option<T>> {
2301    Ok(column
2302        .as_ref()
2303        .context(missing)?
2304        .get(node.node_idx.index())
2305        .copied())
2306}
2307
2308/// Appends to a per-module column of [`SingleModuleGraph`] if the graph collects it.
2309fn push_collected<T>(column: &mut Option<Vec<T>>, value: Option<T>) {
2310    if let (Some(column), Some(value)) = (column, value) {
2311        column.push(value);
2312    }
2313}
2314
2315/// The eagerly-resolved per-module data, stored in the per-module columns of [`SingleModuleGraph`].
2316struct ModuleGraphNodeData {
2317    ident: ResolvedVc<AssetIdent>,
2318    ident_string: Option<ResolvedVc<RcStr>>,
2319    is_self_async: ResolvedVc<bool>,
2320    side_effects: Option<ResolvedVc<ModuleSideEffects>>,
2321    is_mergeable: Option<ResolvedVc<bool>>,
2322}
2323
2324/// Resolves a module's graph-node data. Each `to_resolved()` resolves the pointer chain (executing
2325/// the producing task, without reading the cell content).
2326///
2327/// This is deliberately a plain `async fn` rather than a `#[turbo_tasks::function]`: the producing
2328/// tasks become children of the graph-construction task instead of a new task per module. On a
2329/// large app the extra edges added little to the construction task's batched connect, while a task
2330/// per module costs a creation, an execution and a connect of its own.
2331///
2332/// All calls are issued before the first `.await`: calling a turbo-tasks function schedules its
2333/// task, so they execute concurrently rather than one after another.
2334async fn module_graph_node_data(
2335    module: ResolvedVc<Box<dyn Module>>,
2336    ModuleGraphOptions {
2337        include_ident_strings,
2338        include_side_effects,
2339        include_mergeable,
2340        ..
2341    }: ModuleGraphOptions,
2342) -> Result<ModuleGraphNodeData> {
2343    // Always collected: idents have many consumers (NFT, feature usage, module-id strategy, import
2344    // tracer).
2345    let ident = module.ident();
2346    // Always collected: `async_module_info()` runs during chunking for every graph. Cheap to
2347    // resolve (trait default `Vc::cell(false)`; ecma reads already-cached `references()`).
2348    let is_self_async = module.is_self_async();
2349    let side_effects = include_side_effects.then(|| module.side_effects());
2350    // When collecting mergeability, store `Some` for *every* module so that `None` at the node
2351    // level unambiguously means "graph not built with `include_mergeable`". Types that implement
2352    // `MergeableModule` get their real `is_mergeable()`; others get a resolved `false` (the
2353    // interned `false` cell, so this is cheap and deduped).
2354    let is_mergeable = include_mergeable.then(|| {
2355        match ResolvedVc::try_downcast::<Box<dyn MergeableModule>>(module) {
2356            Some(mergeable) => mergeable.is_mergeable(),
2357            None => Vc::<bool>::default(),
2358        }
2359    });
2360
2361    let ident = ident.to_resolved().await?;
2362    Ok(ModuleGraphNodeData {
2363        ident,
2364        // Only the module-id strategy needs the stringified ident, and only on the graphs that set
2365        // this bit. `ident_string()` is real work (recursive stringify), so it's gated.
2366        ident_string: if include_ident_strings {
2367            Some(ident.to_string().to_resolved().await?)
2368        } else {
2369            None
2370        },
2371        is_self_async: is_self_async.to_resolved().await?,
2372        side_effects: match side_effects {
2373            Some(side_effects) => Some(side_effects.to_resolved().await?),
2374            None => None,
2375        },
2376        is_mergeable: match is_mergeable {
2377            Some(is_mergeable) => Some(is_mergeable.to_resolved().await?),
2378            None => None,
2379        },
2380    })
2381}
2382
2383impl SingleModuleGraphBuilderNode {
2384    fn module(&self) -> ResolvedVc<Box<dyn Module>> {
2385        match self {
2386            SingleModuleGraphBuilderNode::Module { module, .. } => *module,
2387            SingleModuleGraphBuilderNode::VisitedModule { module, .. } => *module,
2388        }
2389    }
2390
2391    async fn new_module(
2392        emit_spans: bool,
2393        module: ResolvedVc<Box<dyn Module>>,
2394        is_traced: bool,
2395    ) -> Result<Self> {
2396        Ok(Self::Module {
2397            module,
2398            // The span name needs the ident string synchronously. Read it (untracked — its value is
2399            // non-load-bearing for correctness) only when spans are enabled. Stays on the builder
2400            // node; never reaches the graph node.
2401            span_name: if emit_spans {
2402                // INVALIDATION: This ident is only used for tracing
2403                Some(module.ident_string().untracked().await?)
2404            } else {
2405                None
2406            },
2407            is_traced,
2408        })
2409    }
2410    fn new_visited_module(module: ResolvedVc<Box<dyn Module>>, idx: GraphNodeIndex) -> Self {
2411        Self::VisitedModule { module, idx }
2412    }
2413}
2414
2415struct SingleModuleGraphBuilder<'a> {
2416    visited_modules: &'a FxHashMap<ResolvedVc<Box<dyn Module>>, GraphNodeIndex>,
2417
2418    /// Filled by `edges()`, which the traversal calls once per unique module, so each module's
2419    /// node data is resolved exactly once and concurrently with the traversal.
2420    node_data: &'a Mutex<FxHashMap<ResolvedVc<Box<dyn Module>>, ModuleGraphNodeData>>,
2421
2422    emit_spans: bool,
2423
2424    options: ModuleGraphOptions,
2425}
2426impl Visit<SingleModuleGraphBuilderNode, RefData> for SingleModuleGraphBuilder<'_> {
2427    type EdgesIntoIter = Vec<(SingleModuleGraphBuilderNode, RefData)>;
2428    type EdgesFuture = impl Future<Output = Result<Self::EdgesIntoIter>>;
2429
2430    fn visit(
2431        &mut self,
2432        node: &SingleModuleGraphBuilderNode,
2433        _edge: Option<&RefData>,
2434    ) -> VisitControlFlow {
2435        match node {
2436            SingleModuleGraphBuilderNode::Module { .. } => VisitControlFlow::Continue,
2437            // Module was already visited previously
2438            SingleModuleGraphBuilderNode::VisitedModule { .. } => VisitControlFlow::Skip,
2439        }
2440    }
2441
2442    fn edges(&mut self, node: &SingleModuleGraphBuilderNode) -> Self::EdgesFuture {
2443        // Destructure beforehand to not have to clone the whole node when entering the async block
2444        let &SingleModuleGraphBuilderNode::Module {
2445            module, is_traced, ..
2446        } = node
2447        else {
2448            // These are always skipped in `visit()`
2449            unreachable!()
2450        };
2451        let visited_modules = self.visited_modules;
2452        let node_data = self.node_data;
2453        let emit_spans = self.emit_spans;
2454        let options = self.options;
2455        let ModuleGraphOptions {
2456            include_traced,
2457            include_binding_usage,
2458            force_activated,
2459            ..
2460        } = options;
2461        async move {
2462            // Issued before resolving the node data so both run concurrently.
2463            let refs_cell = if !is_traced {
2464                primary_chunkable_referenced_modules(
2465                    *module,
2466                    include_traced,
2467                    include_binding_usage,
2468                    force_activated,
2469                )
2470            } else {
2471                // Currently we don't care about the binding usage of traced references
2472                referenced_modules_and_affecting_sources(*module, false)
2473            };
2474            let data = module_graph_node_data(module, options).await?;
2475            node_data.lock().unwrap().insert(module, data);
2476            let refs = match refs_cell.await {
2477                Ok(refs) => refs,
2478                Err(e) => {
2479                    return Err(e.context(module.ident_string().await?));
2480                }
2481            };
2482
2483            refs.iter()
2484                .flat_map(|(reference, resolved)| {
2485                    resolved.modules.iter().map(|m| {
2486                        (
2487                            *reference,
2488                            resolved.chunking_type.clone(),
2489                            resolved.binding_usage.clone(),
2490                            *m,
2491                        )
2492                    })
2493                })
2494                .filter(|(_, ty, _, _)| {
2495                    // Ignore non-entry traced reference if not already in tracing mode.
2496                    //
2497                    // ChunkingType::Traced{TracedMode::Entry}
2498                    // ==> target is always traced
2499                    // ChunkingType::Traced{TracedMode::Transitive}
2500                    // ==> target only traced if parent is traced
2501                    // ChunkingType::*
2502                    // ==> target only traced if parent is traced
2503                    !matches!(
2504                        ty,
2505                        ChunkingType::Traced {
2506                            mode: TracedMode::Transitive
2507                        }
2508                    ) || is_traced
2509                })
2510                .map(async |(reference, ty, binding_usage, target)| {
2511                    let to = if let Some(idx) = visited_modules.get(&target) {
2512                        SingleModuleGraphBuilderNode::new_visited_module(target, *idx)
2513                    } else {
2514                        SingleModuleGraphBuilderNode::new_module(
2515                            emit_spans,
2516                            target,
2517                            is_traced || ty.is_traced(),
2518                        )
2519                        .await?
2520                    };
2521                    Ok((
2522                        to,
2523                        RefData {
2524                            chunking_type: ty,
2525                            binding_usage,
2526                            reference,
2527                        },
2528                    ))
2529                })
2530                .try_join()
2531                .await
2532        }
2533    }
2534
2535    fn span(
2536        &mut self,
2537        node: &SingleModuleGraphBuilderNode,
2538        edge: Option<&RefData>,
2539    ) -> tracing::Span {
2540        if !self.emit_spans {
2541            return Span::none();
2542        }
2543
2544        let mut span = match node {
2545            SingleModuleGraphBuilderNode::Module {
2546                span_name: Some(span_name),
2547                ..
2548            } => {
2549                // Use the precomputed `ident().to_string()` (read untracked in `new_module`).
2550                // `span_name` is populated whenever `emit_spans`, so this arm is taken for every
2551                // `Module` node here.
2552                tracing::info_span!("module", name = display(span_name))
2553            }
2554            SingleModuleGraphBuilderNode::Module {
2555                span_name: None, ..
2556            } => {
2557                tracing::info_span!("module")
2558            }
2559            SingleModuleGraphBuilderNode::VisitedModule { .. } => {
2560                tracing::info_span!("visited module")
2561            }
2562        };
2563
2564        if let Some(edge) = edge {
2565            match &edge.chunking_type {
2566                ChunkingType::Parallel {
2567                    inherit_async: _,
2568                    hoisted: _,
2569                } => {}
2570                ChunkingType::Traced { .. } => {
2571                    let _span = span.entered();
2572                    span = tracing::info_span!("traced reference");
2573                }
2574                ChunkingType::Async => {
2575                    let _span = span.entered();
2576                    span = tracing::info_span!("async reference");
2577                }
2578                ChunkingType::PerEntry => {
2579                    let _span = span.entered();
2580                    span = tracing::info_span!("per-entry reference");
2581                }
2582                ChunkingType::Emitted { namespace, .. } => {
2583                    let _span = span.entered();
2584                    span = tracing::info_span!("emitted reference", namespace = debug(&namespace));
2585                }
2586                ChunkingType::Collected { namespace, .. } => {
2587                    let _span = span.entered();
2588                    span =
2589                        tracing::info_span!("collected reference", namespace = debug(&namespace));
2590                }
2591                ChunkingType::Isolated { _ty: ty, merge_tag } => {
2592                    let _span = span.entered();
2593                    span = tracing::info_span!(
2594                        "isolated reference",
2595                        ty = debug(&ty),
2596                        merge_tag = debug(&merge_tag)
2597                    );
2598                }
2599                ChunkingType::Shared {
2600                    inherit_async: _,
2601                    merge_tag,
2602                } => {
2603                    let _span = span.entered();
2604                    span = tracing::info_span!("shared reference", merge_tag = debug(&merge_tag));
2605                }
2606            };
2607        }
2608
2609        span
2610    }
2611}
2612
2613#[cfg(test)]
2614pub mod tests {
2615    use anyhow::Result;
2616    use rustc_hash::FxHashMap;
2617    use turbo_bitset::Bitset;
2618    use turbo_rcstr::{RcStr, rcstr};
2619    use turbo_tasks::{
2620        ReadRef, ResolvedVc, State, TryFlatJoinIterExt, TryJoinIterExt, ValueToString, Vc,
2621    };
2622    use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
2623    use turbo_tasks_fs::{FileSystem, FileSystemPath, VirtualFileSystem};
2624
2625    use super::*;
2626    use crate::{
2627        asset::{Asset, AssetContent},
2628        chunk::{ChunkItem, availability_info::AvailabilityInfo},
2629        emit_collect::CollectingModule,
2630        ident::AssetIdent,
2631        issue::{CollectibleIssuesExt, IssueSeverity},
2632        module::{ActivatableModule, Module, ModuleSideEffects, Modules},
2633        module_graph::chunk_group_info::{
2634            AsyncLoaderRelevantChunkGroups, AsyncLoaderRelevantChunkGroupsMap, ChunkGroup,
2635            ChunkGroupKey, ChunkGroupKind, EntryHeuristics, chunk_group_at,
2636        },
2637        reference::{ModuleReference, ModuleReferences},
2638        resolve::ModuleResolveResult,
2639    };
2640
2641    #[turbo_tasks::value(shared)]
2642    struct ImportTraceTestResult {
2643        has_entry: bool,
2644        traces: Vec<Vec<RcStr>>,
2645        missing_traces: Vec<Vec<RcStr>>,
2646    }
2647
2648    #[turbo_tasks::function(operation, root)]
2649    async fn import_trace_test_operation(rootless: bool) -> Result<Vc<ImportTraceTestResult>> {
2650        let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
2651        let root = fs.root().await?;
2652        let repo = TestRepo::new(
2653            &root,
2654            [
2655                ("entry.js", vec!["dependency.js"]),
2656                ("dependency.js", vec!["entry.js"]),
2657            ],
2658        );
2659        let entry = Vc::upcast::<Box<dyn Module>>(MockModule::new(root.join("entry.js")?, repo))
2660            .to_resolved()
2661            .await?;
2662        let graph = SingleModuleGraph::new_with_entries(
2663            GraphEntries::resolved_cell(GraphEntries::new(
2664                vec![ChunkGroupEntry::Entry {
2665                    modules: vec![entry],
2666                    heuristics: EntryHeuristics::default(),
2667                }],
2668                vec![],
2669            )),
2670            ModuleGraphOptions::default(),
2671        )
2672        .connect()
2673        .to_resolved()
2674        .await?;
2675        let graph = if rootless {
2676            // Initialize the source graph's cache before cloning to ensure clones reset derived
2677            // state instead of retaining entry indices that could become stale after modification.
2678            let _ = graph.await?.entry_nodes();
2679            let mut graph = (*graph.await?).clone();
2680            graph.entries = GraphEntries::default();
2681            graph.resolved_cell()
2682        } else {
2683            graph
2684        };
2685
2686        let has_entry = graph.await?.has_entry_module(entry);
2687        let tracer = ModuleGraphImportTracer::new(*graph);
2688        let traces = tracer
2689            .get_traces(root.join("dependency.js")?)
2690            .await?
2691            .0
2692            .iter()
2693            .map(|trace| trace.iter().map(|ident| ident.path.path.clone()).collect())
2694            .collect();
2695        let missing_traces = tracer
2696            .get_traces(root.join("missing.js")?)
2697            .await?
2698            .0
2699            .iter()
2700            .map(|trace| trace.iter().map(|ident| ident.path.path.clone()).collect())
2701            .collect();
2702
2703        Ok(ImportTraceTestResult {
2704            has_entry,
2705            traces,
2706            missing_traces,
2707        }
2708        .cell())
2709    }
2710
2711    #[turbo_tasks::value(shared)]
2712    struct ImportTraceIssues {
2713        issues: Vec<(IssueSeverity, RcStr)>,
2714    }
2715
2716    #[turbo_tasks::function(operation, root)]
2717    async fn import_trace_issues_operation(
2718        trace_operation: OperationVc<ImportTraceTestResult>,
2719    ) -> Result<Vc<ImportTraceIssues>> {
2720        // Collectibles are only stable after a strongly consistent read of their source.
2721        let _ = trace_operation.read_strongly_consistent().await?;
2722        let issues = trace_operation
2723            .peek_issues()
2724            .iter()
2725            .map(async |issue| {
2726                let issue = issue.into_trait_ref().await?;
2727                Ok((
2728                    issue.severity(),
2729                    issue.title().await?.to_unstyled_string().into(),
2730                ))
2731            })
2732            .try_join()
2733            .await?;
2734        Ok(ImportTraceIssues { issues }.cell())
2735    }
2736
2737    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2738    async fn test_import_trace_uses_explicit_entry_as_cycle_root() {
2739        let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
2740            BackendOptions::default(),
2741            noop_backing_storage(),
2742        ));
2743        tt.run_once(async {
2744            let result = import_trace_test_operation(false)
2745                .read_strongly_consistent()
2746                .await?;
2747            assert!(result.has_entry);
2748            assert_eq!(
2749                result.traces,
2750                vec![vec![rcstr!("dependency.js"), rcstr!("entry.js")]]
2751            );
2752            assert!(result.missing_traces.is_empty());
2753            Ok(())
2754        })
2755        .await
2756        .unwrap();
2757    }
2758
2759    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2760    async fn test_cloned_rootless_import_trace_resets_cache_and_emits_bug_issue() {
2761        let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
2762            BackendOptions::default(),
2763            noop_backing_storage(),
2764        ));
2765        tt.run_once(async {
2766            let trace_operation = import_trace_test_operation(true);
2767            let result = trace_operation.read_strongly_consistent().await?;
2768            assert!(!result.has_entry);
2769            assert_eq!(result.traces, vec![vec![rcstr!("dependency.js")]]);
2770            assert!(result.missing_traces.is_empty());
2771
2772            let issues = import_trace_issues_operation(trace_operation)
2773                .read_strongly_consistent()
2774                .await?;
2775            assert_eq!(
2776                issues.issues,
2777                vec![(
2778                    IssueSeverity::Bug,
2779                    rcstr!("Module graph is missing an entry point")
2780                )]
2781            );
2782            Ok(())
2783        })
2784        .await
2785        .unwrap();
2786    }
2787
2788    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2789    async fn test_traverse_dfs_from_entries_diamond() {
2790        run_graph_test(
2791            vec![rcstr!("a.js")],
2792            {
2793                let mut deps = FxHashMap::default();
2794                // A classic diamond dependency on d
2795                deps.insert(rcstr!("a.js"), vec![rcstr!("b.js"), rcstr!("c.js")]);
2796                deps.insert(rcstr!("b.js"), vec![rcstr!("d.js")]);
2797                deps.insert(rcstr!("c.js"), vec![rcstr!("d.js")]);
2798                deps
2799            },
2800            |graph, entry_modules, module_to_name| {
2801                let mut preorder_visits = Vec::new();
2802                let mut postorder_visits = Vec::new();
2803
2804                graph.traverse_edges_dfs(
2805                    entry_modules,
2806                    &mut (),
2807                    |parent, target, _| {
2808                        preorder_visits.push((
2809                            parent.map(|(node, _)| module_to_name.get(&node).unwrap().clone()),
2810                            module_to_name.get(&target).unwrap().clone(),
2811                        ));
2812                        Ok(GraphTraversalAction::Continue)
2813                    },
2814                    |parent, target, _| {
2815                        postorder_visits.push((
2816                            parent.map(|(node, _)| module_to_name.get(&node).unwrap().clone()),
2817                            module_to_name.get(&target).unwrap().clone(),
2818                        ));
2819                        Ok(())
2820                    },
2821                    false,
2822                    false,
2823                )?;
2824                assert_eq!(
2825                    vec![
2826                        (None, rcstr!("a.js")),
2827                        (Some(rcstr!("a.js")), rcstr!("b.js")),
2828                        (Some(rcstr!("b.js")), rcstr!("d.js")),
2829                        (Some(rcstr!("a.js")), rcstr!("c.js")),
2830                        (Some(rcstr!("c.js")), rcstr!("d.js"))
2831                    ],
2832                    preorder_visits
2833                );
2834                assert_eq!(
2835                    vec![
2836                        (Some(rcstr!("b.js")), rcstr!("d.js")),
2837                        (Some(rcstr!("a.js")), rcstr!("b.js")),
2838                        (Some(rcstr!("c.js")), rcstr!("d.js")),
2839                        (Some(rcstr!("a.js")), rcstr!("c.js")),
2840                        (None, rcstr!("a.js"))
2841                    ],
2842                    postorder_visits
2843                );
2844                Ok(())
2845            },
2846        )
2847        .await;
2848    }
2849
2850    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2851    async fn test_traverse_dfs_from_entries_cycle() {
2852        run_graph_test(
2853            vec![rcstr!("a.js")],
2854            {
2855                let mut deps = FxHashMap::default();
2856                // A cycle of length 3
2857                deps.insert(rcstr!("a.js"), vec![rcstr!("b.js")]);
2858                deps.insert(rcstr!("b.js"), vec![rcstr!("c.js")]);
2859                deps.insert(rcstr!("c.js"), vec![rcstr!("a.js")]);
2860                deps
2861            },
2862            |graph, entry_modules, module_to_name| {
2863                let mut preorder_visits = Vec::new();
2864                let mut postorder_visits = Vec::new();
2865
2866                graph.traverse_edges_dfs(
2867                    entry_modules,
2868                    &mut (),
2869                    |parent, target, _| {
2870                        preorder_visits.push((
2871                            parent.map(|(node, _)| module_to_name.get(&node).unwrap().clone()),
2872                            module_to_name.get(&target).unwrap().clone(),
2873                        ));
2874                        Ok(GraphTraversalAction::Continue)
2875                    },
2876                    |parent, target, _| {
2877                        postorder_visits.push((
2878                            parent.map(|(node, _)| module_to_name.get(&node).unwrap().clone()),
2879                            module_to_name.get(&target).unwrap().clone(),
2880                        ));
2881                        Ok(())
2882                    },
2883                    false,
2884                    false,
2885                )?;
2886                assert_eq!(
2887                    vec![
2888                        (None, rcstr!("a.js")),
2889                        (Some(rcstr!("a.js")), rcstr!("b.js")),
2890                        (Some(rcstr!("b.js")), rcstr!("c.js")),
2891                        (Some(rcstr!("c.js")), rcstr!("a.js")),
2892                    ],
2893                    preorder_visits
2894                );
2895                assert_eq!(
2896                    vec![
2897                        (Some(rcstr!("c.js")), rcstr!("a.js")),
2898                        (Some(rcstr!("b.js")), rcstr!("c.js")),
2899                        (Some(rcstr!("a.js")), rcstr!("b.js")),
2900                        (None, rcstr!("a.js"))
2901                    ],
2902                    postorder_visits
2903                );
2904                Ok(())
2905            },
2906        )
2907        .await;
2908    }
2909
2910    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2911    async fn test_traverse_edges_fixed_point_with_priority_cycle() {
2912        run_graph_test(
2913            vec![rcstr!("a.js")],
2914            {
2915                let mut deps = FxHashMap::default();
2916                // A cycle of length 3
2917                deps.insert(rcstr!("a.js"), vec![rcstr!("b.js")]);
2918                deps.insert(rcstr!("b.js"), vec![rcstr!("c.js")]);
2919                deps.insert(rcstr!("c.js"), vec![rcstr!("a.js")]);
2920                deps
2921            },
2922            |graph, entry_modules, module_to_name| {
2923                let mut visits = Vec::new();
2924                let mut count = 0;
2925
2926                graph.traverse_edges_fixed_point_with_priority(
2927                    entry_modules.into_iter().map(|m| (m, 0)),
2928                    &mut (),
2929                    |parent, target, _, _| {
2930                        visits.push((
2931                            parent.map(|(node, _, _)| module_to_name.get(&node).unwrap().clone()),
2932                            module_to_name.get(&target).unwrap().clone(),
2933                        ));
2934                        count += 1;
2935
2936                        // We are a cycle so we need to break the loop eventually
2937                        Ok(if count < 6 {
2938                            GraphTraversalAction::Continue
2939                        } else {
2940                            GraphTraversalAction::Skip
2941                        })
2942                    },
2943                    |_, _| Ok(0),
2944                )?;
2945                assert_eq!(
2946                    vec![
2947                        (None, rcstr!("a.js")),
2948                        (Some(rcstr!("a.js")), rcstr!("b.js")),
2949                        (Some(rcstr!("b.js")), rcstr!("c.js")),
2950                        (Some(rcstr!("c.js")), rcstr!("a.js")),
2951                        // we start following the cycle again
2952                        (Some(rcstr!("a.js")), rcstr!("b.js")),
2953                        (Some(rcstr!("b.js")), rcstr!("c.js")),
2954                    ],
2955                    visits
2956                );
2957
2958                Ok(())
2959            },
2960        )
2961        .await;
2962    }
2963
2964    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2965    async fn test_traverse_edges_fixed_point_no_priority_is_bfs() {
2966        run_graph_test(
2967            vec![rcstr!("a.js")],
2968            {
2969                let mut deps = FxHashMap::default();
2970                // a simple triangle
2971                //        a
2972                //      b   c
2973                //   d    e    f
2974                deps.insert(rcstr!("a.js"), vec![rcstr!("b.js"), rcstr!("c.js")]);
2975                deps.insert(rcstr!("b.js"), vec![rcstr!("d.js"), rcstr!("e.js")]);
2976                deps.insert(rcstr!("c.js"), vec![rcstr!("e.js"), rcstr!("f.js")]);
2977                deps
2978            },
2979            |graph, entry_modules, module_to_name| {
2980                let mut visits = Vec::new();
2981                let mut count = 0;
2982
2983                graph.traverse_edges_fixed_point_with_priority(
2984                    entry_modules.into_iter().map(|m| (m, 0)),
2985                    &mut (),
2986                    |parent, target, _, _| {
2987                        visits.push((
2988                            parent.map(|(node, _, _)| module_to_name.get(&node).unwrap().clone()),
2989                            module_to_name.get(&target).unwrap().clone(),
2990                        ));
2991                        count += 1;
2992
2993                        // We are a cycle so we need to break the loop eventually
2994                        Ok(if count < 6 {
2995                            GraphTraversalAction::Continue
2996                        } else {
2997                            GraphTraversalAction::Skip
2998                        })
2999                    },
3000                    |_, _| Ok(0),
3001                )?;
3002
3003                assert_eq!(
3004                    vec![
3005                        (None, rcstr!("a.js")),
3006                        (Some(rcstr!("a.js")), rcstr!("c.js")),
3007                        (Some(rcstr!("a.js")), rcstr!("b.js")),
3008                        (Some(rcstr!("b.js")), rcstr!("e.js")),
3009                        (Some(rcstr!("b.js")), rcstr!("d.js")),
3010                        (Some(rcstr!("c.js")), rcstr!("f.js")),
3011                        (Some(rcstr!("c.js")), rcstr!("e.js")),
3012                    ],
3013                    visits
3014                );
3015
3016                Ok(())
3017            },
3018        )
3019        .await;
3020    }
3021
3022    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3023    async fn test_traverse_cycles() {
3024        run_graph_test(
3025            vec![rcstr!("a.js")],
3026            {
3027                let mut deps = FxHashMap::default();
3028                // The cycles are: (i, j, k), and (s) which a self-import
3029                //          a
3030                //      /   |    \
3031                //     /i   s-\   x
3032                //     |j   \-/
3033                //     \k
3034                deps.insert(
3035                    rcstr!("a.js"),
3036                    vec![rcstr!("i.js"), rcstr!("s.js"), rcstr!("x.js")],
3037                );
3038                deps.insert(rcstr!("i.js"), vec![rcstr!("j.js")]);
3039                deps.insert(rcstr!("j.js"), vec![rcstr!("k.js")]);
3040                deps.insert(rcstr!("k.js"), vec![rcstr!("i.js")]);
3041                deps.insert(rcstr!("s.js"), vec![rcstr!("s.js")]);
3042                deps
3043            },
3044            |graph, _, module_to_name| {
3045                let mut cycles = vec![];
3046
3047                graph.traverse_cycles(
3048                    |_| true,
3049                    |cycle| {
3050                        cycles.push(
3051                            cycle
3052                                .iter()
3053                                .map(|n| module_to_name.get(*n).unwrap().clone())
3054                                .collect::<Vec<_>>(),
3055                        );
3056                        Ok(())
3057                    },
3058                )?;
3059
3060                assert_eq!(
3061                    cycles,
3062                    vec![
3063                        vec![rcstr!("k.js"), rcstr!("j.js"), rcstr!("i.js")],
3064                        vec![rcstr!("s.js")]
3065                    ],
3066                );
3067
3068                Ok(())
3069            },
3070        )
3071        .await;
3072    }
3073
3074    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3075    async fn test_reverse_edges_through_layered_graph() {
3076        let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
3077            BackendOptions::default(),
3078            noop_backing_storage(),
3079        ));
3080        tt.run_once(async move {
3081            #[turbo_tasks::value]
3082            struct ReverseTraversalResults {
3083                forward: Vec<RcStr>,
3084                reverse_from_d: Vec<RcStr>,
3085                reverse_from_b: Vec<RcStr>,
3086            }
3087
3088            #[turbo_tasks::function(operation, root)]
3089            async fn reverse_traversal_results_operation() -> Result<Vc<ReverseTraversalResults>> {
3090                let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
3091                let root = fs.root().await?;
3092
3093                // a simple linear graph a -> b ->c
3094                // but b->c is in a parent graph and a is in the child
3095                let repo = TestRepo::new(
3096                    &root,
3097                    [("a.js", vec!["b.js", "d.js"]), ("b.js", vec!["c.js"])],
3098                );
3099                let make_module = |name| {
3100                    Vc::upcast::<Box<dyn Module>>(MockModule::new(root.join(name).unwrap(), repo))
3101                        .to_resolved()
3102                };
3103                let a_module = make_module("a.js").await?;
3104                let b_module = make_module("b.js").await?;
3105
3106                let parent_graph = SingleModuleGraph::new_with_entries(
3107                    GraphEntries::from_chunk_groups(vec![ChunkGroupEntry::Entry {
3108                        modules: vec![b_module],
3109                        heuristics: EntryHeuristics::default(),
3110                    }])
3111                    .resolved_cell(),
3112                    ModuleGraphOptions::default(),
3113                );
3114
3115                let module_graph = ModuleGraph::from_graphs(
3116                    vec![
3117                        parent_graph,
3118                        SingleModuleGraph::new_with_entries_visited(
3119                            GraphEntries::from_chunk_groups(vec![ChunkGroupEntry::Entry {
3120                                modules: vec![a_module],
3121                                heuristics: EntryHeuristics::default(),
3122                            }])
3123                            .resolved_cell(),
3124                            VisitedModules::from_graph(parent_graph),
3125                            ModuleGraphOptions::default(),
3126                        ),
3127                    ],
3128                    None,
3129                )
3130                .connect();
3131                let child_graph = module_graph
3132                    .iter_graphs()
3133                    .await?
3134                    .get(1)
3135                    .unwrap()
3136                    .connect()
3137                    .await?;
3138
3139                // test traversing forward from a in the child graph
3140                let mut visited_forward = Vec::new();
3141                child_graph.traverse_edges_dfs(
3142                    vec![a_module],
3143                    &mut (),
3144                    |_parent, child, _state_| {
3145                        visited_forward.push(child);
3146                        Ok(GraphTraversalAction::Continue)
3147                    },
3148                    |_, _, _| Ok(()),
3149                    false,
3150                    false,
3151                )?;
3152                let forward = visited_forward
3153                    .iter()
3154                    .map(|m| m.ident_string().owned())
3155                    .try_join()
3156                    .await?;
3157
3158                // test traversing backwards from 'd' which is only in the child graph
3159                let d_module = child_graph
3160                    .enumerate_nodes()
3161                    .map(async |(_index, module)| {
3162                        Ok(match module {
3163                            crate::module_graph::SingleModuleGraphNode::Module(module) => {
3164                                if module.ident_string().owned().await? == "[test]/d.js" {
3165                                    Some(*module)
3166                                } else {
3167                                    None
3168                                }
3169                            }
3170                            crate::module_graph::SingleModuleGraphNode::VisitedModule {
3171                                ..
3172                            } => None,
3173                        })
3174                    })
3175                    .try_flat_join()
3176                    .await?
3177                    .into_iter()
3178                    .next()
3179                    .unwrap();
3180
3181                async fn get_reverse_from(
3182                    graph: &ModuleGraphLayer,
3183                    module: ResolvedVc<Box<dyn Module>>,
3184                ) -> Result<Vec<RcStr>> {
3185                    let mut visited = Vec::new();
3186                    graph.traverse_edges_reverse_dfs(
3187                        vec![module],
3188                        &mut (),
3189                        |_parent, child, _state_| {
3190                            visited.push(child);
3191                            Ok(GraphTraversalAction::Continue)
3192                        },
3193                        |_, _, _| Ok(()),
3194                    )?;
3195                    visited
3196                        .iter()
3197                        .map(|m| m.ident_string().owned())
3198                        .try_join()
3199                        .await
3200                }
3201
3202                Ok(ReverseTraversalResults {
3203                    forward,
3204                    reverse_from_d: get_reverse_from(&child_graph, d_module).await?,
3205                    reverse_from_b: get_reverse_from(&child_graph, b_module).await?,
3206                }
3207                .cell())
3208            }
3209
3210            let traversal_results = reverse_traversal_results_operation()
3211                .read_strongly_consistent()
3212                .await?;
3213
3214            assert_eq!(
3215                traversal_results.forward,
3216                vec![
3217                    rcstr!("[test]/a.js"),
3218                    rcstr!("[test]/b.js"),
3219                    rcstr!("[test]/d.js")
3220                ]
3221            );
3222
3223            assert_eq!(
3224                traversal_results.reverse_from_d,
3225                vec![rcstr!("[test]/d.js"), rcstr!("[test]/a.js")]
3226            );
3227
3228            assert_eq!(
3229                traversal_results.reverse_from_b,
3230                vec![rcstr!("[test]/b.js"), rcstr!("[test]/a.js")]
3231            );
3232
3233            Ok(())
3234        })
3235        .await
3236        .unwrap();
3237    }
3238
3239    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3240    async fn test_iter_nodes_modules_through_layered_graph() {
3241        let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
3242            BackendOptions::default(),
3243            noop_backing_storage(),
3244        ));
3245        tt.run_once(async move {
3246            #[turbo_tasks::value]
3247            struct Results {
3248                iter_nodes: Vec<RcStr>,
3249                iter_modules: Vec<RcStr>,
3250                iter_nodes_single: Vec<Vec<RcStr>>,
3251                iter_modules_single: Vec<Vec<RcStr>>,
3252            }
3253
3254            #[turbo_tasks::function(operation, root)]
3255            async fn reverse_traversal_results_operation() -> Result<Vc<Results>> {
3256                let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
3257                let root = fs.root().await?;
3258
3259                // a simple linear graph a -> b -> c -> x -> y -> z
3260                // but x -> y -> z is in a parent graph
3261
3262                let repo = TestRepo::new_with_chunking_types(
3263                    &root,
3264                    [
3265                        ("a.js", vec!["b.js"]),
3266                        ("b.js", vec!["c.js"]),
3267                        ("c.js", vec!["x.js"]),
3268                        ("x.js", vec!["y.js", "traced.js"]),
3269                        ("y.js", vec!["z.js"]),
3270                    ],
3271                    [(
3272                        "x.js",
3273                        "traced.js",
3274                        ChunkingType::Traced {
3275                            mode: TracedMode::Entry,
3276                        },
3277                    )],
3278                );
3279                let make_module = |name| {
3280                    Vc::upcast::<Box<dyn Module>>(MockModule::new(root.join(name).unwrap(), repo))
3281                        .to_resolved()
3282                };
3283                let x_module = make_module("x.js").await?;
3284                let a_module = make_module("a.js").await?;
3285
3286                let parent_graph = SingleModuleGraph::new_with_entries(
3287                    GraphEntries::from_chunk_groups(vec![ChunkGroupEntry::Entry {
3288                        modules: vec![x_module],
3289                        heuristics: EntryHeuristics::default(),
3290                    }])
3291                    .resolved_cell(),
3292                    ModuleGraphOptions {
3293                        include_traced: true,
3294                        ..Default::default()
3295                    },
3296                );
3297
3298                let module_graph = ModuleGraph::from_graphs(
3299                    vec![
3300                        parent_graph,
3301                        SingleModuleGraph::new_with_entries_visited(
3302                            GraphEntries::from_chunk_groups(vec![ChunkGroupEntry::Entry {
3303                                modules: vec![a_module],
3304                                heuristics: EntryHeuristics::default(),
3305                            }])
3306                            .resolved_cell(),
3307                            VisitedModules::from_graph(parent_graph),
3308                            ModuleGraphOptions {
3309                                include_traced: true,
3310                                ..Default::default()
3311                            },
3312                        ),
3313                    ],
3314                    None,
3315                )
3316                .connect();
3317                let graph_layers = module_graph.iter_graphs().await?;
3318
3319                Ok(Results {
3320                    iter_nodes: module_graph
3321                        .await?
3322                        .iter_reachable_nodes()?
3323                        .map(async |(_, node)| {
3324                            Ok(match node {
3325                                SingleModuleGraphNode::Module(module) => {
3326                                    module.ident_string().owned().await?
3327                                }
3328                                SingleModuleGraphNode::VisitedModule { module, .. } => {
3329                                    format!("visited {}", module.ident_string().owned().await?)
3330                                        .into()
3331                                }
3332                            })
3333                        })
3334                        .try_join()
3335                        .await?,
3336                    iter_modules: module_graph
3337                        .await?
3338                        .iter_reachable_modules()?
3339                        .map(|m| m.ident_string().owned())
3340                        .try_join()
3341                        .await?,
3342                    iter_nodes_single: graph_layers
3343                        .iter()
3344                        .map(async |layer| {
3345                            layer
3346                                .connect()
3347                                .await?
3348                                .iter_reachable_nodes()?
3349                                .map(async |(_, node)| {
3350                                    Ok(match node {
3351                                        SingleModuleGraphNode::Module(module) => {
3352                                            module.ident_string().owned().await?
3353                                        }
3354                                        SingleModuleGraphNode::VisitedModule { module, .. } => {
3355                                            format!(
3356                                                "visited {}",
3357                                                module.ident_string().owned().await?
3358                                            )
3359                                            .into()
3360                                        }
3361                                    })
3362                                })
3363                                .try_join()
3364                                .await
3365                        })
3366                        .try_join()
3367                        .await?,
3368                    iter_modules_single: graph_layers
3369                        .iter()
3370                        .map(async |layer| {
3371                            layer
3372                                .connect()
3373                                .await?
3374                                .iter_reachable_modules()?
3375                                .map(|m| m.ident_string().owned())
3376                                .try_join()
3377                                .await
3378                        })
3379                        .try_join()
3380                        .await?,
3381                }
3382                .cell())
3383            }
3384
3385            let traversal_results = reverse_traversal_results_operation()
3386                .read_strongly_consistent()
3387                .await?;
3388
3389            assert_eq!(
3390                traversal_results.iter_nodes,
3391                vec![
3392                    rcstr!("[test]/x.js"),
3393                    rcstr!("[test]/a.js"),
3394                    rcstr!("[test]/y.js"),
3395                    rcstr!("[test]/b.js"),
3396                    rcstr!("[test]/z.js"),
3397                    rcstr!("[test]/c.js"),
3398                    rcstr!("visited [test]/x.js")
3399                ]
3400            );
3401            assert_eq!(
3402                traversal_results.iter_modules,
3403                vec![
3404                    rcstr!("[test]/x.js"),
3405                    rcstr!("[test]/a.js"),
3406                    rcstr!("[test]/y.js"),
3407                    rcstr!("[test]/b.js"),
3408                    rcstr!("[test]/z.js"),
3409                    rcstr!("[test]/c.js")
3410                ]
3411            );
3412            assert_eq!(
3413                traversal_results.iter_nodes_single,
3414                vec![
3415                    vec![
3416                        rcstr!("[test]/x.js"),
3417                        rcstr!("[test]/y.js"),
3418                        rcstr!("[test]/z.js")
3419                    ],
3420                    vec![
3421                        rcstr!("[test]/a.js"),
3422                        rcstr!("[test]/b.js"),
3423                        rcstr!("[test]/c.js"),
3424                        rcstr!("visited [test]/x.js")
3425                    ]
3426                ]
3427            );
3428            assert_eq!(
3429                traversal_results.iter_modules_single,
3430                vec![
3431                    vec![
3432                        rcstr!("[test]/x.js"),
3433                        rcstr!("[test]/y.js"),
3434                        rcstr!("[test]/z.js")
3435                    ],
3436                    vec![
3437                        rcstr!("[test]/a.js"),
3438                        rcstr!("[test]/b.js"),
3439                        rcstr!("[test]/c.js")
3440                    ]
3441                ]
3442            );
3443
3444            Ok(())
3445        })
3446        .await
3447        .unwrap();
3448    }
3449
3450    #[turbo_tasks::value(shared)]
3451    struct TestRepo {
3452        repo: FxHashMap<FileSystemPath, Vec<FileSystemPath>>,
3453        chunking_types: FxHashMap<(FileSystemPath, FileSystemPath), ChunkingType>,
3454    }
3455
3456    impl TestRepo {
3457        fn new(
3458            root: &FileSystemPath,
3459            dependencies: impl IntoIterator<Item = (impl AsRef<str>, Vec<impl AsRef<str>>)>,
3460        ) -> Vc<Self> {
3461            Self::new_with_chunking_types(
3462                root,
3463                dependencies,
3464                std::iter::empty::<(RcStr, RcStr, ChunkingType)>(),
3465            )
3466        }
3467
3468        fn new_with_chunking_types(
3469            root: &FileSystemPath,
3470            dependencies: impl IntoIterator<Item = (impl AsRef<str>, Vec<impl AsRef<str>>)>,
3471            chunking_types: impl IntoIterator<Item = (impl AsRef<str>, impl AsRef<str>, ChunkingType)>,
3472        ) -> Vc<Self> {
3473            let chunking_types = chunking_types
3474                .into_iter()
3475                .map(|(from, to, ty)| {
3476                    (
3477                        (
3478                            root.join(from.as_ref()).unwrap(),
3479                            root.join(to.as_ref()).unwrap(),
3480                        ),
3481                        ty,
3482                    )
3483                })
3484                .collect::<FxHashMap<_, _>>();
3485            Self {
3486                repo: dependencies
3487                    .into_iter()
3488                    .map(|(k, v)| {
3489                        (
3490                            root.join(k.as_ref()).unwrap(),
3491                            v.iter().map(|f| root.join(f.as_ref()).unwrap()).collect(),
3492                        )
3493                    })
3494                    .collect(),
3495                chunking_types,
3496            }
3497            .cell()
3498        }
3499    }
3500
3501    #[turbo_tasks::value]
3502    struct MockModule {
3503        path: FileSystemPath,
3504        repo: ResolvedVc<TestRepo>,
3505    }
3506    #[turbo_tasks::value_impl]
3507    impl MockModule {
3508        #[turbo_tasks::function]
3509        fn new(path: FileSystemPath, repo: ResolvedVc<TestRepo>) -> Vc<Self> {
3510            Self { path, repo }.cell()
3511        }
3512    }
3513
3514    #[turbo_tasks::value_impl]
3515    impl Asset for MockModule {
3516        #[turbo_tasks::function]
3517        fn content(&self) -> Vc<AssetContent> {
3518            panic!("MockModule::content shouldn't be called")
3519        }
3520    }
3521
3522    #[turbo_tasks::value_impl]
3523    impl Module for MockModule {
3524        #[turbo_tasks::function]
3525        fn ident(&self) -> Vc<AssetIdent> {
3526            AssetIdent::from_path(self.path.clone()).into_vc()
3527        }
3528
3529        #[turbo_tasks::function]
3530        fn source(&self) -> Vc<crate::source::OptionSource> {
3531            Vc::cell(None)
3532        }
3533
3534        #[turbo_tasks::function]
3535        async fn references(&self) -> Result<Vc<ModuleReferences>> {
3536            let repo = self.repo.await?;
3537            let references = match repo.repo.get(&self.path) {
3538                Some(deps) => {
3539                    deps.iter()
3540                        .map(async |p| {
3541                            Vc::upcast::<Box<dyn ModuleReference>>(MockModuleReference::new(
3542                                mock_module(p.clone(), *self.repo).to_resolved().await?,
3543                                rcstr!("normal-dep"),
3544                                repo.chunking_types
3545                                    .get(&(self.path.clone(), p.clone()))
3546                                    .cloned()
3547                                    .unwrap_or(ChunkingType::Parallel {
3548                                        inherit_async: true,
3549                                        hoisted: false,
3550                                    }),
3551                            ))
3552                            .to_resolved()
3553                            .await
3554                        })
3555                        .try_join()
3556                        .await?
3557                }
3558                None => vec![],
3559            };
3560
3561            Ok(Vc::cell(references))
3562        }
3563        #[turbo_tasks::function]
3564        fn side_effects(self: Vc<Self>) -> Vc<ModuleSideEffects> {
3565            ModuleSideEffects::SideEffectful.cell()
3566        }
3567    }
3568
3569    /// Creates the mock module for `path`. Files named `collect*.js` become collecting modules
3570    /// (namespace `ns`), files named `proxy*.js` activatable modules, everything else a plain
3571    /// [`MockModule`].
3572    fn mock_module(path: FileSystemPath, repo: Vc<TestRepo>) -> Vc<Box<dyn Module>> {
3573        if path.file_name().starts_with("collect") {
3574            Vc::upcast(MockCollectingModule::new(path, repo))
3575        } else if path.file_name().starts_with("proxy") {
3576            Vc::upcast(MockActivatableModule::new(path, repo))
3577        } else {
3578            Vc::upcast(MockModule::new(path, repo))
3579        }
3580    }
3581
3582    /// A [`MockModule`] that is also an [`ActivatableModule`].
3583    #[turbo_tasks::value]
3584    struct MockActivatableModule {
3585        inner: ResolvedVc<MockModule>,
3586    }
3587
3588    #[turbo_tasks::value_impl]
3589    impl MockActivatableModule {
3590        #[turbo_tasks::function]
3591        async fn new(path: FileSystemPath, repo: ResolvedVc<TestRepo>) -> Result<Vc<Self>> {
3592            Ok(Self {
3593                inner: MockModule::new(path, *repo).to_resolved().await?,
3594            }
3595            .cell())
3596        }
3597    }
3598
3599    #[turbo_tasks::value_impl]
3600    impl Asset for MockActivatableModule {
3601        #[turbo_tasks::function]
3602        fn content(&self) -> Vc<AssetContent> {
3603            panic!("MockActivatableModule::content shouldn't be called")
3604        }
3605    }
3606
3607    #[turbo_tasks::value_impl]
3608    impl Module for MockActivatableModule {
3609        #[turbo_tasks::function]
3610        fn ident(&self) -> Vc<AssetIdent> {
3611            self.inner.ident()
3612        }
3613
3614        #[turbo_tasks::function]
3615        fn source(&self) -> Vc<crate::source::OptionSource> {
3616            Vc::cell(None)
3617        }
3618
3619        #[turbo_tasks::function]
3620        fn references(&self) -> Vc<ModuleReferences> {
3621            self.inner.references()
3622        }
3623
3624        #[turbo_tasks::function]
3625        fn side_effects(self: Vc<Self>) -> Vc<ModuleSideEffects> {
3626            ModuleSideEffects::SideEffectful.cell()
3627        }
3628    }
3629
3630    #[turbo_tasks::value_impl]
3631    impl ActivatableModule for MockActivatableModule {
3632        #[turbo_tasks::function]
3633        fn activated_references(&self) -> Vc<ModuleReferences> {
3634            self.inner.references()
3635        }
3636    }
3637
3638    /// A [`MockModule`] that is also a [`CollectingModule`].
3639    #[turbo_tasks::value]
3640    struct MockCollectingModule {
3641        inner: ResolvedVc<MockModule>,
3642    }
3643
3644    #[turbo_tasks::value_impl]
3645    impl MockCollectingModule {
3646        #[turbo_tasks::function]
3647        async fn new(path: FileSystemPath, repo: ResolvedVc<TestRepo>) -> Result<Vc<Self>> {
3648            Ok(Self {
3649                inner: MockModule::new(path, *repo).to_resolved().await?,
3650            }
3651            .cell())
3652        }
3653    }
3654
3655    #[turbo_tasks::value_impl]
3656    impl Asset for MockCollectingModule {
3657        #[turbo_tasks::function]
3658        fn content(&self) -> Vc<AssetContent> {
3659            panic!("MockCollectingModule::content shouldn't be called")
3660        }
3661    }
3662
3663    #[turbo_tasks::value_impl]
3664    impl Module for MockCollectingModule {
3665        #[turbo_tasks::function]
3666        fn ident(&self) -> Vc<AssetIdent> {
3667            self.inner.ident()
3668        }
3669
3670        #[turbo_tasks::function]
3671        fn source(&self) -> Vc<crate::source::OptionSource> {
3672            Vc::cell(None)
3673        }
3674
3675        #[turbo_tasks::function]
3676        fn references(&self) -> Vc<ModuleReferences> {
3677            self.inner.references()
3678        }
3679
3680        #[turbo_tasks::function]
3681        fn side_effects(self: Vc<Self>) -> Vc<ModuleSideEffects> {
3682            ModuleSideEffects::SideEffectful.cell()
3683        }
3684    }
3685
3686    #[turbo_tasks::value_impl]
3687    impl CollectingModule for MockCollectingModule {
3688        #[turbo_tasks::function]
3689        fn namespace(&self) -> Vc<RcStr> {
3690            Vc::cell(rcstr!("ns"))
3691        }
3692
3693        #[turbo_tasks::function]
3694        fn as_chunk_item(
3695            &self,
3696            _module_graph: Vc<ModuleGraph>,
3697            _chunking_context: Vc<Box<dyn ChunkingContext>>,
3698            _entry_chunk_group: Vc<Modules>,
3699        ) -> Vc<Box<dyn ChunkItem>> {
3700            panic!("MockCollectingModule::as_chunk_item shouldn't be called")
3701        }
3702    }
3703
3704    #[turbo_tasks::value]
3705    #[derive(ValueToString)]
3706    #[value_to_string(self.description)]
3707    struct MockModuleReference {
3708        asset: ResolvedVc<Box<dyn Module>>,
3709        description: RcStr,
3710        chunking_type: ChunkingType,
3711    }
3712
3713    impl MockModuleReference {
3714        pub fn new(
3715            asset: ResolvedVc<Box<dyn Module>>,
3716            description: RcStr,
3717            chunking_type: ChunkingType,
3718        ) -> Vc<Self> {
3719            MockModuleReference {
3720                asset,
3721                description,
3722                chunking_type,
3723            }
3724            .cell()
3725        }
3726    }
3727
3728    #[turbo_tasks::value_impl]
3729    impl ModuleReference for MockModuleReference {
3730        #[turbo_tasks::function]
3731        fn resolve_reference(&self) -> Vc<ModuleResolveResult> {
3732            *ModuleResolveResult::module(self.asset)
3733        }
3734
3735        fn chunking_type(&self) -> Option<ChunkingType> {
3736            Some(self.chunking_type.clone())
3737        }
3738    }
3739
3740    /// Constructs a graph based on the provided dependency adjacency lists and calls the given test
3741    /// function.
3742    ///
3743    /// # Parameters
3744    /// - `entries`: A vector of entry module names (as `RcStr`). These are the starting points for
3745    ///   the graph.
3746    /// - `graph`: A map from module name (`RcStr`) to a vector of its dependency module names
3747    ///   (`RcStr`). Represents the adjacency list of the graph.
3748    /// - `test_fn`: A function that is called with:
3749    ///     - `ReadRef<SingleModuleGraph>`: The constructed module graph.
3750    ///     - `Vec<ResolvedVc<Box<dyn Module>>>`: The resolved entry modules.
3751    ///     - `FxHashMap<ResolvedVc<Box<dyn Module>>, RcStr>`: A mapping from module to its name for
3752    ///       easier analysis in tests.
3753    async fn run_graph_test(
3754        entries: Vec<RcStr>,
3755        graph: FxHashMap<RcStr, Vec<RcStr>>,
3756        test_fn: impl FnOnce(
3757            &ModuleGraph,
3758            Vec<ResolvedVc<Box<dyn Module>>>,
3759            FxHashMap<ResolvedVc<Box<dyn Module>>, RcStr>,
3760        ) -> Result<()>
3761        + Send
3762        + 'static,
3763    ) {
3764        #[turbo_tasks::value(serialization = "skip", eq = "manual", cell = "new")]
3765        struct SetupGraph {
3766            module_graph: ReadRef<ModuleGraph>,
3767            entry_modules: Vec<ResolvedVc<Box<dyn Module>>>,
3768            module_to_name: FxHashMap<ResolvedVc<Box<dyn Module>>, RcStr>,
3769        }
3770
3771        #[turbo_tasks::function(operation, root)]
3772        async fn setup_graph(
3773            entries: Vec<RcStr>,
3774            graph_entries: Vec<(RcStr, Vec<RcStr>)>,
3775        ) -> Result<Vc<SetupGraph>> {
3776            let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
3777            let root = fs.root().await?;
3778
3779            let repo = TestRepo::new(&root, graph_entries);
3780            let entry_modules = entries
3781                .iter()
3782                .map(|e| {
3783                    Vc::upcast::<Box<dyn Module>>(MockModule::new(root.join(e).unwrap(), repo))
3784                        .to_resolved()
3785                })
3786                .try_join()
3787                .await?;
3788            let graph = SingleModuleGraph::new_with_entries(
3789                GraphEntries::resolved_cell(GraphEntries::new(
3790                    vec![ChunkGroupEntry::Entry {
3791                        modules: entry_modules.clone(),
3792                        heuristics: EntryHeuristics::default(),
3793                    }],
3794                    vec![],
3795                )),
3796                ModuleGraphOptions::default(),
3797            );
3798
3799            // Create a simple name mapping to make analyzing the visitors easier.
3800            // Technically they could always pull this name off of the
3801            // `module.ident().await?.path.path` themselves but you cannot `await` in visitors.
3802            let module_to_name = graph
3803                .connect()
3804                .await?
3805                .modules
3806                .keys()
3807                .map(async |m| Ok((*m, m.ident().await?.path.path.clone())))
3808                .try_join()
3809                .await?
3810                .into_iter()
3811                .collect();
3812            let module_graph = ModuleGraph::from_graphs(vec![graph], None)
3813                .connect()
3814                .await?;
3815
3816            Ok(SetupGraph {
3817                module_graph,
3818                entry_modules,
3819                module_to_name,
3820            }
3821            .cell())
3822        }
3823
3824        let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
3825            BackendOptions::default(),
3826            noop_backing_storage(),
3827        ));
3828        let graph_entries = graph.into_iter().collect::<Vec<_>>();
3829        tt.run_once(async move {
3830            let setup = setup_graph(entries, graph_entries)
3831                .read_strongly_consistent()
3832                .await?;
3833
3834            test_fn(
3835                &setup.module_graph,
3836                setup.entry_modules.clone(),
3837                setup.module_to_name.clone(),
3838            )
3839        })
3840        .await
3841        .unwrap();
3842    }
3843
3844    /// Asserts that the ranks are a permutation of `0..n` and that every (non back-) edge in
3845    /// `edges` goes from a lower to a higher rank.
3846    fn assert_ranks(
3847        ranks: &FxHashMap<ResolvedVc<Box<dyn Module>>, usize>,
3848        module_to_name: &FxHashMap<ResolvedVc<Box<dyn Module>>, RcStr>,
3849        edges: &[(&str, &str)],
3850    ) -> FxHashMap<RcStr, usize> {
3851        let by_name: FxHashMap<RcStr, usize> = ranks
3852            .iter()
3853            .map(|(m, r)| (module_to_name[m].clone(), *r))
3854            .collect();
3855        assert_eq!(by_name.len(), ranks.len(), "modules must be ranked once");
3856        let mut sorted = ranks.values().copied().collect::<Vec<_>>();
3857        sorted.sort();
3858        assert_eq!(sorted, (0..ranks.len()).collect::<Vec<_>>());
3859        for (from, to) in edges {
3860            assert!(
3861                by_name[*from] < by_name[*to],
3862                "expected rank({from}) < rank({to}), ranks: {by_name:?}"
3863            );
3864        }
3865        by_name
3866    }
3867
3868    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3869    async fn test_reverse_postorder_ranks_diamond() {
3870        run_graph_test(
3871            vec![rcstr!("a.js")],
3872            {
3873                // d is reachable via paths of length 1, 2 and 3
3874                let mut deps = FxHashMap::default();
3875                deps.insert(
3876                    rcstr!("a.js"),
3877                    vec![rcstr!("b.js"), rcstr!("d.js"), rcstr!("e.js")],
3878                );
3879                deps.insert(rcstr!("b.js"), vec![rcstr!("c.js")]);
3880                deps.insert(rcstr!("c.js"), vec![rcstr!("d.js")]);
3881                deps.insert(rcstr!("e.js"), vec![rcstr!("d.js")]);
3882                deps
3883            },
3884            |graph, entry_modules, module_to_name| {
3885                let ranks = graph.reverse_postorder_ranks(entry_modules.clone())?;
3886                assert_eq!(ranks.len(), 5);
3887                assert_ranks(
3888                    &ranks,
3889                    &module_to_name,
3890                    &[
3891                        ("a.js", "b.js"),
3892                        ("a.js", "d.js"),
3893                        ("a.js", "e.js"),
3894                        ("b.js", "c.js"),
3895                        ("c.js", "d.js"),
3896                        ("e.js", "d.js"),
3897                    ],
3898                );
3899
3900                // Using the ranks as priority, every module is visited exactly once, even if the
3901                // visitor always continues.
3902                let visit_count = graph.traverse_edges_fixed_point_with_priority(
3903                    entry_modules
3904                        .iter()
3905                        .map(|m| (*m, std::cmp::Reverse(ranks[m])))
3906                        .collect::<Vec<_>>(),
3907                    &mut (),
3908                    |_, _, _, _| Ok(GraphTraversalAction::Continue),
3909                    |m, _| Ok(std::cmp::Reverse(ranks[&m])),
3910                )?;
3911                assert_eq!(visit_count, 5);
3912                Ok(())
3913            },
3914        )
3915        .await;
3916    }
3917
3918    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3919    async fn test_reverse_postorder_ranks_cycle() {
3920        run_graph_test(
3921            vec![rcstr!("a.js")],
3922            {
3923                let mut deps = FxHashMap::default();
3924                deps.insert(rcstr!("a.js"), vec![rcstr!("b.js")]);
3925                deps.insert(rcstr!("b.js"), vec![rcstr!("c.js")]);
3926                deps.insert(rcstr!("c.js"), vec![rcstr!("a.js"), rcstr!("d.js")]);
3927                deps
3928            },
3929            |graph, entry_modules, module_to_name| {
3930                let ranks = graph.reverse_postorder_ranks(entry_modules)?;
3931                assert_eq!(ranks.len(), 4);
3932                // c -> a is the back edge
3933                assert_ranks(
3934                    &ranks,
3935                    &module_to_name,
3936                    &[("a.js", "b.js"), ("b.js", "c.js"), ("c.js", "d.js")],
3937                );
3938                Ok(())
3939            },
3940        )
3941        .await;
3942    }
3943
3944    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3945    async fn test_reverse_postorder_ranks_multiple_entries() {
3946        run_graph_test(
3947            vec![rcstr!("a.js"), rcstr!("b.js")],
3948            {
3949                let mut deps = FxHashMap::default();
3950                deps.insert(rcstr!("a.js"), vec![rcstr!("b.js")]);
3951                deps.insert(rcstr!("b.js"), vec![rcstr!("c.js")]);
3952                deps
3953            },
3954            |graph, entry_modules, module_to_name| {
3955                let [a, b] = entry_modules[..] else {
3956                    panic!("expected two entries");
3957                };
3958                // The importing entry `a` must be ranked before `b`, independent of the order of
3959                // the entries, and duplicate entries are ignored.
3960                for entries in [vec![a, b], vec![b, a], vec![b, a, b, a]] {
3961                    let ranks = graph.reverse_postorder_ranks(entries)?;
3962                    assert_eq!(ranks.len(), 3);
3963                    assert_ranks(
3964                        &ranks,
3965                        &module_to_name,
3966                        &[("a.js", "b.js"), ("b.js", "c.js")],
3967                    );
3968                }
3969                Ok(())
3970            },
3971        )
3972        .await;
3973    }
3974
3975    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3976    async fn test_reverse_postorder_ranks_through_layered_graph() {
3977        let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
3978            BackendOptions::default(),
3979            noop_backing_storage(),
3980        ));
3981        tt.run_once(async move {
3982            #[turbo_tasks::value]
3983            struct Results {
3984                ranks_from_child_entry: Vec<(RcStr, usize)>,
3985                ranks_from_all_entries: Vec<(RcStr, usize)>,
3986            }
3987
3988            #[turbo_tasks::function(operation, root)]
3989            async fn layered_ranks_operation() -> Result<Vc<Results>> {
3990                let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
3991                let root = fs.root().await?;
3992
3993                // a -> b -> c -> x -> y -> z, but x -> y -> z is in a parent graph, so the child
3994                // graph only contains a `VisitedModule` node for x
3995                let repo = TestRepo::new(
3996                    &root,
3997                    [
3998                        ("a.js", vec!["b.js"]),
3999                        ("b.js", vec!["c.js"]),
4000                        ("c.js", vec!["x.js"]),
4001                        ("x.js", vec!["y.js"]),
4002                        ("y.js", vec!["z.js"]),
4003                    ],
4004                );
4005                let make_module = |name| {
4006                    Vc::upcast::<Box<dyn Module>>(MockModule::new(root.join(name).unwrap(), repo))
4007                        .to_resolved()
4008                };
4009                let x_module = make_module("x.js").await?;
4010                let a_module = make_module("a.js").await?;
4011
4012                let parent_graph = SingleModuleGraph::new_with_entries(
4013                    GraphEntries::from_chunk_groups(vec![ChunkGroupEntry::Entry {
4014                        modules: vec![x_module],
4015                        heuristics: EntryHeuristics::default(),
4016                    }])
4017                    .resolved_cell(),
4018                    ModuleGraphOptions::default(),
4019                );
4020                let module_graph = ModuleGraph::from_graphs(
4021                    vec![
4022                        parent_graph,
4023                        SingleModuleGraph::new_with_entries_visited(
4024                            GraphEntries::from_chunk_groups(vec![ChunkGroupEntry::Entry {
4025                                modules: vec![a_module],
4026                                heuristics: EntryHeuristics::default(),
4027                            }])
4028                            .resolved_cell(),
4029                            VisitedModules::from_graph(parent_graph),
4030                            ModuleGraphOptions::default(),
4031                        ),
4032                    ],
4033                    None,
4034                )
4035                .connect()
4036                .await?;
4037
4038                async fn named(
4039                    ranks: FxHashMap<ResolvedVc<Box<dyn Module>>, usize>,
4040                ) -> Result<Vec<(RcStr, usize)>> {
4041                    let mut ranks = ranks
4042                        .into_iter()
4043                        .map(async |(m, r)| Ok((m.ident().await?.path.path.clone(), r)))
4044                        .try_join()
4045                        .await?;
4046                    ranks.sort_by_key(|(_, r)| *r);
4047                    Ok(ranks)
4048                }
4049
4050                Ok(Results {
4051                    ranks_from_child_entry: named(
4052                        module_graph.reverse_postorder_ranks([a_module])?,
4053                    )
4054                    .await?,
4055                    ranks_from_all_entries: named(
4056                        module_graph.reverse_postorder_ranks([x_module, a_module])?,
4057                    )
4058                    .await?,
4059                }
4060                .cell())
4061            }
4062
4063            let results = layered_ranks_operation().read_strongly_consistent().await?;
4064
4065            // Every module is ranked exactly once, with the `VisitedModule` x resolved to the
4066            // module in the parent graph, and the ranks follow the edges across the graphs.
4067            let expected = ["a.js", "b.js", "c.js", "x.js", "y.js", "z.js"]
4068                .into_iter()
4069                .enumerate()
4070                .map(|(i, name)| (RcStr::from(name), i))
4071                .collect::<Vec<_>>();
4072            assert_eq!(results.ranks_from_child_entry, expected);
4073            assert_eq!(results.ranks_from_all_entries, expected);
4074
4075            Ok(())
4076        })
4077        .await
4078        .unwrap();
4079    }
4080
4081    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4082    async fn test_entry_ranks_cached() {
4083        run_graph_test(
4084            vec![rcstr!("a.js"), rcstr!("e.js")],
4085            {
4086                // A diamond (a -> b, c -> d) and a cycle (d -> a)
4087                let mut deps = FxHashMap::default();
4088                deps.insert(rcstr!("a.js"), vec![rcstr!("b.js"), rcstr!("c.js")]);
4089                deps.insert(rcstr!("b.js"), vec![rcstr!("d.js")]);
4090                deps.insert(rcstr!("c.js"), vec![rcstr!("d.js")]);
4091                deps.insert(rcstr!("d.js"), vec![rcstr!("a.js")]);
4092                deps.insert(rcstr!("e.js"), vec![rcstr!("c.js")]);
4093                deps
4094            },
4095            |graph, _, _| {
4096                let shared = graph.entry_ranks()?;
4097                let expected =
4098                    graph.reverse_postorder_ranks(graph.all_chunk_group_entry_modules())?;
4099                assert_eq!(shared, &expected);
4100                assert_eq!(shared.len(), 5);
4101                // The second call returns the cached map
4102                assert!(std::ptr::eq(shared, graph.entry_ranks()?));
4103                Ok(())
4104            },
4105        )
4106        .await;
4107    }
4108
4109    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4110    async fn test_entry_ranks_new_snapshot() {
4111        let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
4112            BackendOptions::default(),
4113            noop_backing_storage(),
4114        ));
4115        tt.run_once(async move {
4116            #[turbo_tasks::value]
4117            struct Results {
4118                old_len_before: usize,
4119                old_len_after: usize,
4120                old_unchanged: bool,
4121                new_len: usize,
4122                new_matches_fresh: bool,
4123                new_contains_c: bool,
4124                old_contains_c: bool,
4125            }
4126
4127            #[turbo_tasks::function(operation, root)]
4128            async fn new_snapshot_operation() -> Result<Vc<Results>> {
4129                let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
4130                let root = fs.root().await?;
4131
4132                async fn graph_for(
4133                    root: &FileSystemPath,
4134                    deps: Vec<(&'static str, Vec<&'static str>)>,
4135                ) -> Result<(ReadRef<ModuleGraph>, ResolvedVc<Box<dyn Module>>)> {
4136                    let repo = TestRepo::new(root, deps);
4137                    let module = |name| {
4138                        Vc::upcast::<Box<dyn Module>>(MockModule::new(
4139                            root.join(name).unwrap(),
4140                            repo,
4141                        ))
4142                        .to_resolved()
4143                    };
4144                    let a = module("a.js").await?;
4145                    let c = module("c.js").await?;
4146                    let graph = SingleModuleGraph::new_with_entries(
4147                        GraphEntries::from_chunk_groups(vec![ChunkGroupEntry::Entry {
4148                            modules: vec![a],
4149                            heuristics: EntryHeuristics::default(),
4150                        }])
4151                        .resolved_cell(),
4152                        ModuleGraphOptions::default(),
4153                    );
4154                    let graph = ModuleGraph::from_graphs(vec![graph], None)
4155                        .connect()
4156                        .await?;
4157                    Ok((graph, c))
4158                }
4159
4160                // The first graph: a -> b
4161                let (old_graph, old_c_module) =
4162                    graph_for(&root, vec![("a.js", vec!["b.js"])]).await?;
4163                let old_ranks = old_graph.entry_ranks()?;
4164                let old_len_before = old_ranks.len();
4165
4166                // The edited graph: a -> b -> c
4167                let (new_graph, c_module) =
4168                    graph_for(&root, vec![("a.js", vec!["b.js"]), ("b.js", vec!["c.js"])]).await?;
4169                let new_ranks = new_graph.entry_ranks()?;
4170                let fresh =
4171                    new_graph.reverse_postorder_ranks(new_graph.all_chunk_group_entry_modules())?;
4172
4173                Ok(Results {
4174                    old_len_before,
4175                    old_len_after: old_graph.entry_ranks()?.len(),
4176                    old_unchanged: std::ptr::eq(old_ranks, old_graph.entry_ranks()?),
4177                    new_len: new_ranks.len(),
4178                    new_matches_fresh: new_ranks == &fresh,
4179                    new_contains_c: new_ranks.contains_key(&c_module),
4180                    old_contains_c: old_ranks.contains_key(&old_c_module),
4181                }
4182                .cell())
4183            }
4184
4185            let results = new_snapshot_operation().read_strongly_consistent().await?;
4186            assert_eq!(results.old_len_before, 2);
4187            assert_eq!(results.old_len_after, 2);
4188            assert!(results.old_unchanged);
4189            assert!(!results.old_contains_c);
4190            assert_eq!(results.new_len, 3);
4191            assert!(results.new_matches_fresh);
4192            assert!(results.new_contains_c);
4193            Ok(())
4194        })
4195        .await
4196        .unwrap();
4197    }
4198
4199    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4200    async fn test_reverse_postorder_ranks_layer_snapshot_panics() {
4201        let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
4202            BackendOptions::default(),
4203            noop_backing_storage(),
4204        ));
4205        tt.run_once(async move {
4206            #[turbo_tasks::function(operation, root)]
4207            async fn layer_panics_operation() -> Result<Vc<bool>> {
4208                let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
4209                let root = fs.root().await?;
4210                let repo = TestRepo::new(&root, [("a.js", vec!["b.js"])]);
4211                let a = Vc::upcast::<Box<dyn Module>>(MockModule::new(
4212                    root.join("a.js").unwrap(),
4213                    repo,
4214                ))
4215                .to_resolved()
4216                .await?;
4217                let graph = SingleModuleGraph::new_with_entries(
4218                    GraphEntries::from_chunk_groups(vec![ChunkGroupEntry::Entry {
4219                        modules: vec![a],
4220                        heuristics: EntryHeuristics::default(),
4221                    }])
4222                    .resolved_cell(),
4223                    ModuleGraphOptions::default(),
4224                );
4225                let layers = ModuleGraph::from_graphs(vec![graph], None)
4226                    .connect()
4227                    .iter_graphs()
4228                    .await?;
4229                let layer = layers[0].connect().await?;
4230                let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4231                    let _ = layer.reverse_postorder_ranks([a]);
4232                }))
4233                .is_err();
4234                Ok(Vc::cell(panicked))
4235            }
4236
4237            assert!(*layer_panics_operation().read_strongly_consistent().await?);
4238            Ok(())
4239        })
4240        .await
4241        .unwrap();
4242    }
4243
4244    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4245    async fn test_traverse_edges_fixed_point_dedups_entries() {
4246        run_graph_test(
4247            vec![rcstr!("a.js"), rcstr!("b.js")],
4248            {
4249                let mut deps = FxHashMap::default();
4250                deps.insert(rcstr!("a.js"), vec![rcstr!("b.js")]);
4251                deps
4252            },
4253            |graph, entry_modules, _| {
4254                let [a, b] = entry_modules[..] else {
4255                    panic!("expected two entries");
4256                };
4257                let mut root_visits = 0;
4258                // `b` is an entry and reachable from the entry `a`, and `a` is passed twice. `a`
4259                // is visited first, its reference to the already queued entry `b` must not queue
4260                // `b` a second time.
4261                let visit_count = graph.traverse_edges_fixed_point_with_priority(
4262                    [(a, 1), (b, 0), (a, 1)],
4263                    &mut (),
4264                    |parent, _, _, _| {
4265                        if parent.is_none() {
4266                            root_visits += 1;
4267                        }
4268                        Ok(GraphTraversalAction::Continue)
4269                    },
4270                    |_, _| Ok(0),
4271                )?;
4272                assert_eq!(root_visits, 2);
4273                assert_eq!(visit_count, 2);
4274                Ok(())
4275            },
4276        )
4277        .await;
4278    }
4279
4280    #[turbo_tasks::value]
4281    struct EntryOrder {
4282        swapped: turbo_tasks::State<bool>,
4283    }
4284
4285    #[turbo_tasks::value(transparent)]
4286    struct ChunkGroupDescriptions(Vec<RcStr>);
4287
4288    /// Builds a graph with two entries that each have an async child, in the order given by
4289    /// `order`, and describes the chunk groups that `get_chunk_groups_for_module` returns for
4290    /// `page1.js` and `lazy1.js`.
4291    ///
4292    /// ```text
4293    /// page1 -async-> lazy1
4294    /// page2 -async-> lazy2
4295    /// ```
4296    #[turbo_tasks::function(operation, root)]
4297    async fn chunk_groups_by_entry_order(
4298        order: ResolvedVc<EntryOrder>,
4299    ) -> Result<Vc<ChunkGroupDescriptions>> {
4300        let swapped = *order.await?.swapped.get();
4301        let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
4302        let root = fs.root().await?;
4303        let repo = TestRepo::new_with_chunking_types(
4304            &root,
4305            [
4306                ("page1.js", vec!["lazy1.js"]),
4307                ("page2.js", vec!["lazy2.js"]),
4308            ],
4309            [
4310                ("page1.js", "lazy1.js", ChunkingType::Async),
4311                ("page2.js", "lazy2.js", ChunkingType::Async),
4312            ],
4313        );
4314        let module = |name: &str| {
4315            Vc::upcast::<Box<dyn Module>>(MockModule::new(root.join(name).unwrap(), repo))
4316                .to_resolved()
4317        };
4318        let page1 = module("page1.js").await?;
4319        let page2 = module("page2.js").await?;
4320        let lazy1 = module("lazy1.js").await?;
4321        let entry = |module| ChunkGroupEntry::Entry {
4322            modules: vec![module],
4323            heuristics: EntryHeuristics::default(),
4324        };
4325        let mut entries = vec![entry(page1), entry(page2)];
4326        if swapped {
4327            entries.reverse();
4328        }
4329        let graph = SingleModuleGraph::new_with_entries(
4330            GraphEntries::resolved_cell(GraphEntries::new(entries, vec![])),
4331            ModuleGraphOptions::default(),
4332        );
4333        let chunk_group_info = ModuleGraph::from_graphs(vec![graph], None)
4334            .connect()
4335            .chunk_group_info();
4336
4337        let mut descriptions = Vec::new();
4338        for module in [page1, lazy1] {
4339            let module_name = module.ident().await?.path.path.clone();
4340            for group in chunk_group_info
4341                .get_chunk_groups_for_module(*module)
4342                .await?
4343                .iter()
4344            {
4345                let kind = match &group.kind {
4346                    ChunkGroupKind::Entry => "entry",
4347                    ChunkGroupKind::Async(_) => "async",
4348                    _ => "other",
4349                };
4350                let chunk_group = chunk_group_info
4351                    .chunk_groups()
4352                    .get(&(group.index as usize))
4353                    .await?
4354                    .context("chunk group index out of range")?;
4355                let entry_names = chunk_group
4356                    .entries()
4357                    .map(async |entry| Ok(entry.ident().await?.path.path.clone()))
4358                    .try_join()
4359                    .await?;
4360                descriptions
4361                    .push(format!("{module_name}: {kind} {}", entry_names.join(",")).into());
4362            }
4363        }
4364        Ok(Vc::cell(descriptions))
4365    }
4366
4367    /// Reordering the graph entries renumbers the chunk groups but keeps the same set of them.
4368    /// The recomputed `ChunkGroupInfo` must not compare equal to the old one: if it did, the cell
4369    /// would keep the old order while `module_chunk_groups` takes the new indices, and modules
4370    /// would map to another entry's chunk groups.
4371    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4372    async fn test_chunk_group_info_reordered_entries() {
4373        let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
4374            BackendOptions::default(),
4375            noop_backing_storage(),
4376        ));
4377        tt.run_once(async move {
4378            let order = EntryOrder {
4379                swapped: turbo_tasks::State::new(false),
4380            }
4381            .resolved_cell();
4382            let expected = vec![
4383                rcstr!("page1.js: entry page1.js"),
4384                rcstr!("lazy1.js: async lazy1.js"),
4385            ];
4386
4387            let descriptions = chunk_groups_by_entry_order(order)
4388                .read_strongly_consistent()
4389                .await?;
4390            assert_eq!(*descriptions, expected);
4391
4392            order.await?.swapped.set(true);
4393            let descriptions = chunk_groups_by_entry_order(order)
4394                .read_strongly_consistent()
4395                .await?;
4396            assert_eq!(*descriptions, expected);
4397            Ok(())
4398        })
4399        .await
4400        .unwrap();
4401    }
4402
4403    #[turbo_tasks::value(serialization = "skip", eq = "manual", cell = "new")]
4404    struct ChunkGroupInfoTestGraph {
4405        chunk_group_info: ReadRef<ChunkGroupInfo>,
4406        module_to_name: FxHashMap<ResolvedVc<Box<dyn Module>>, RcStr>,
4407    }
4408
4409    /// Two entries with heuristics, a diamond with paths of different lengths into a shared
4410    /// module, an async reference and an isolated reference with a merge tag:
4411    ///
4412    /// ```text
4413    /// page1 (clusters [0])                 page2 (clusters [1], high priority)
4414    ///  |-> a1 -> a2 -> shared <-------------|
4415    ///  |-> shared -> lib                    |-isolated(merge_tag "m")-> iso -> lib
4416    ///  |-async-> lazy -> lib
4417    /// ```
4418    #[turbo_tasks::function(operation, root)]
4419    async fn chunk_group_info_test_graph() -> Result<Vc<ChunkGroupInfoTestGraph>> {
4420        let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
4421        let root = fs.root().await?;
4422        let repo = TestRepo::new_with_chunking_types(
4423            &root,
4424            [
4425                ("page1.js", vec!["a1.js", "shared.js", "lazy.js"]),
4426                ("a1.js", vec!["a2.js"]),
4427                ("a2.js", vec!["shared.js"]),
4428                ("page2.js", vec!["shared.js", "iso.js"]),
4429                ("shared.js", vec!["lib.js"]),
4430                ("lazy.js", vec!["lib.js"]),
4431                ("iso.js", vec!["lib.js"]),
4432            ],
4433            [
4434                ("page1.js", "lazy.js", ChunkingType::Async),
4435                (
4436                    "page2.js",
4437                    "iso.js",
4438                    ChunkingType::Isolated {
4439                        _ty: crate::chunk::ChunkGroupType::Entry,
4440                        merge_tag: Some(rcstr!("m")),
4441                    },
4442                ),
4443            ],
4444        );
4445        let module = |name: &str| {
4446            Vc::upcast::<Box<dyn Module>>(MockModule::new(root.join(name).unwrap(), repo))
4447                .to_resolved()
4448        };
4449        let entries = vec![
4450            ChunkGroupEntry::Entry {
4451                modules: vec![module("page1.js").await?],
4452                heuristics: EntryHeuristics {
4453                    clusters: vec![0],
4454                    high_priority: false,
4455                },
4456            },
4457            ChunkGroupEntry::Entry {
4458                modules: vec![module("page2.js").await?],
4459                heuristics: EntryHeuristics {
4460                    clusters: vec![1],
4461                    high_priority: true,
4462                },
4463            },
4464        ];
4465        let graph = SingleModuleGraph::new_with_entries(
4466            GraphEntries::resolved_cell(GraphEntries::new(entries, vec![])),
4467            ModuleGraphOptions::default(),
4468        );
4469        let module_to_name = graph
4470            .connect()
4471            .await?
4472            .modules
4473            .keys()
4474            .map(async |m| Ok((*m, m.ident().await?.path.path.clone())))
4475            .try_join()
4476            .await?
4477            .into_iter()
4478            .collect();
4479        let chunk_group_info = ModuleGraph::from_graphs(vec![graph], None)
4480            .connect()
4481            .chunk_group_info()
4482            .await?;
4483        Ok(ChunkGroupInfoTestGraph {
4484            chunk_group_info,
4485            module_to_name,
4486        }
4487        .cell())
4488    }
4489
4490    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4491    async fn test_chunk_group_info_semantics() {
4492        let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
4493            BackendOptions::default(),
4494            noop_backing_storage(),
4495        ));
4496        tt.run_once(async move {
4497            let setup = chunk_group_info_test_graph()
4498                .read_strongly_consistent()
4499                .await?;
4500            let names = &setup.module_to_name;
4501            let name = |m: &ResolvedVc<Box<dyn Module>>| names[m].to_string();
4502            let info = setup.chunk_group_info.clone();
4503            let chunk_groups = info.chunk_groups.await?;
4504            let chunking_heuristics = info.chunking_heuristics.await?;
4505
4506            // Describe chunk groups by name, independent of their index.
4507            fn describe(
4508                info: &[ChunkGroup],
4509                index: usize,
4510                names: &FxHashMap<ResolvedVc<Box<dyn Module>>, RcStr>,
4511            ) -> String {
4512                let list = |modules: &[ResolvedVc<Box<dyn Module>>]| {
4513                    modules
4514                        .iter()
4515                        .map(|m| names[m].to_string())
4516                        .collect::<Vec<_>>()
4517                        .join(",")
4518                };
4519                match chunk_group_at(info, index).unwrap() {
4520                    ChunkGroup::Entry(modules) => format!("entry {}", list(modules)),
4521                    ChunkGroup::Async(module) => format!("async {}", names[module]),
4522                    ChunkGroup::IsolatedMerged {
4523                        parent,
4524                        merge_tag,
4525                        entries,
4526                    } => format!(
4527                        "isolated merged {merge_tag} [{}] of ({})",
4528                        list(entries),
4529                        describe(info, *parent, names)
4530                    ),
4531                    other => panic!("unexpected chunk group {other:?}"),
4532                }
4533            }
4534
4535            let mut membership = info
4536                .module_chunk_groups
4537                .await?
4538                .iter()
4539                .map(|(module, groups)| {
4540                    let mut groups = groups
4541                        .iter()
4542                        .map(|i| describe(&chunk_groups, i as usize, names))
4543                        .collect::<Vec<_>>();
4544                    groups.sort();
4545                    (name(module), groups)
4546                })
4547                .collect::<Vec<_>>();
4548            membership.sort();
4549
4550            let page1 = "entry page1.js";
4551            let page2 = "entry page2.js";
4552            let lazy = "async lazy.js";
4553            let iso = "isolated merged m [iso.js] of (entry page2.js)";
4554            let expected = |groups: &[&str]| {
4555                let mut groups = groups.iter().map(|s| s.to_string()).collect::<Vec<_>>();
4556                groups.sort();
4557                groups
4558            };
4559            assert_eq!(
4560                membership,
4561                vec![
4562                    ("a1.js".to_string(), expected(&[page1])),
4563                    ("a2.js".to_string(), expected(&[page1])),
4564                    ("iso.js".to_string(), expected(&[iso])),
4565                    ("lazy.js".to_string(), expected(&[lazy])),
4566                    ("lib.js".to_string(), expected(&[page1, page2, lazy, iso])),
4567                    ("page1.js".to_string(), expected(&[page1])),
4568                    ("page2.js".to_string(), expected(&[page2])),
4569                    ("shared.js".to_string(), expected(&[page1, page2])),
4570                ]
4571            );
4572
4573            // Heuristics: async groups inherit from the groups of the referencing module, merged
4574            // groups from their parent group.
4575            let mut heuristics = (0..chunk_groups.len())
4576                .map(|i| {
4577                    (
4578                        describe(&chunk_groups, i, names),
4579                        chunking_heuristics.clusters[i].clone(),
4580                        chunking_heuristics.priority_routes.contains(i as u32),
4581                    )
4582                })
4583                .collect::<Vec<_>>();
4584            heuristics.sort();
4585            assert_eq!(
4586                heuristics,
4587                vec![
4588                    (lazy.to_string(), vec![0], false),
4589                    (page1.to_string(), vec![0], false),
4590                    (page2.to_string(), vec![1], true),
4591                    (iso.to_string(), vec![1], true),
4592                ]
4593            );
4594
4595            Ok(())
4596        })
4597        .await
4598        .unwrap();
4599    }
4600
4601    // ---- async loader availability ----
4602
4603    /// The chunking types used by the async loader availability test graphs, by short name.
4604    fn test_chunking_type(kind: &str) -> ChunkingType {
4605        match kind {
4606            "async" => ChunkingType::Async,
4607            "shared" => ChunkingType::Shared {
4608                inherit_async: false,
4609                merge_tag: None,
4610            },
4611            "shared-merged" => ChunkingType::Shared {
4612                inherit_async: false,
4613                merge_tag: Some(rcstr!("m")),
4614            },
4615            "isolated" => ChunkingType::Isolated {
4616                _ty: crate::chunk::ChunkGroupType::Entry,
4617                merge_tag: None,
4618            },
4619            "traced" => ChunkingType::Traced {
4620                mode: TracedMode::Entry,
4621            },
4622            "emitted" => ChunkingType::Emitted {
4623                namespace: rcstr!("ns"),
4624                emit_to_all_entries: false,
4625            },
4626            "per-entry" => ChunkingType::PerEntry,
4627            _ => panic!("unknown chunking type {kind}"),
4628        }
4629    }
4630
4631    #[turbo_tasks::value(serialization = "skip", eq = "manual", cell = "new")]
4632    struct AsyncAvailabilityTestGraph {
4633        module_graph: ResolvedVc<ModuleGraph>,
4634        modules: FxHashMap<RcStr, ResolvedVc<Box<dyn Module>>>,
4635    }
4636
4637    /// A graph with one `ChunkGroupEntry::Entry` per name in `entries` and one
4638    /// `ChunkGroupEntry::Async` per name in `async_entries`.
4639    #[turbo_tasks::function(operation, root)]
4640    async fn async_availability_test_graph(
4641        dependencies: Vec<(RcStr, Vec<RcStr>)>,
4642        chunking_types: Vec<(RcStr, RcStr, RcStr)>,
4643        entries: Vec<RcStr>,
4644        async_entries: Vec<RcStr>,
4645    ) -> Result<Vc<AsyncAvailabilityTestGraph>> {
4646        build_async_availability_test_graph(dependencies, chunking_types, entries, async_entries)
4647            .await
4648    }
4649
4650    async fn build_async_availability_test_graph(
4651        dependencies: Vec<(RcStr, Vec<RcStr>)>,
4652        chunking_types: Vec<(RcStr, RcStr, RcStr)>,
4653        entries: Vec<RcStr>,
4654        async_entries: Vec<RcStr>,
4655    ) -> Result<Vc<AsyncAvailabilityTestGraph>> {
4656        let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
4657        let root = fs.root().await?;
4658        let repo = TestRepo::new_with_chunking_types(
4659            &root,
4660            dependencies,
4661            chunking_types
4662                .iter()
4663                .map(|(from, to, kind)| (from.clone(), to.clone(), test_chunking_type(kind))),
4664        );
4665        let module = async |name: &RcStr| mock_module(root.join(name)?, repo).to_resolved().await;
4666        let mut graph_entries = Vec::new();
4667        for entry in &entries {
4668            graph_entries.push(ChunkGroupEntry::Entry {
4669                modules: vec![module(entry).await?],
4670                heuristics: EntryHeuristics::default(),
4671            });
4672        }
4673        for entry in &async_entries {
4674            graph_entries.push(ChunkGroupEntry::Async(module(entry).await?));
4675        }
4676        let graph = SingleModuleGraph::new_with_entries(
4677            GraphEntries::resolved_cell(GraphEntries::new(graph_entries, vec![])),
4678            ModuleGraphOptions::default(),
4679        );
4680        let modules = graph
4681            .connect()
4682            .await?
4683            .modules
4684            .keys()
4685            .map(async |m| Ok((m.ident().await?.path.path.clone(), *m)))
4686            .try_join()
4687            .await?
4688            .into_iter()
4689            .collect();
4690        let module_graph = ModuleGraph::from_graphs(vec![graph], None)
4691            .connect()
4692            .to_resolved()
4693            .await?;
4694        Ok(AsyncAvailabilityTestGraph {
4695            module_graph,
4696            modules,
4697        }
4698        .cell())
4699    }
4700
4701    async fn run_turbo_test(test: impl Future<Output = Result<()>> + Send + 'static) {
4702        let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
4703            BackendOptions::default(),
4704            noop_backing_storage(),
4705        ));
4706        tt.run_once(test).await.unwrap();
4707    }
4708
4709    struct AsyncAvailabilityTest {
4710        module_graph: ResolvedVc<ModuleGraph>,
4711        modules: FxHashMap<RcStr, ResolvedVc<Box<dyn Module>>>,
4712    }
4713
4714    impl AsyncAvailabilityTest {
4715        async fn new(
4716            dependencies: &[(&str, &[&str])],
4717            chunking_types: &[(&str, &str, &str)],
4718            entries: &[&str],
4719            async_entries: &[&str],
4720        ) -> Result<Self> {
4721            let names = |names: &[&str]| names.iter().map(|n| RcStr::from(*n)).collect::<Vec<_>>();
4722            let setup = async_availability_test_graph(
4723                dependencies
4724                    .iter()
4725                    .map(|(module, deps)| (RcStr::from(*module), names(deps)))
4726                    .collect(),
4727                chunking_types
4728                    .iter()
4729                    .map(|(from, to, kind)| ((*from).into(), (*to).into(), (*kind).into()))
4730                    .collect(),
4731                names(entries),
4732                names(async_entries),
4733            )
4734            .read_strongly_consistent()
4735            .await?;
4736            Ok(Self {
4737                module_graph: setup.module_graph,
4738                modules: setup.modules.clone(),
4739            })
4740        }
4741
4742        fn module(&self, name: &str) -> ResolvedVc<Box<dyn Module>> {
4743            *self
4744                .modules
4745                .get(&RcStr::from(name))
4746                .unwrap_or_else(|| panic!("no module {name}"))
4747        }
4748
4749        /// Inspects the graph from a task (top-level code may only read strongly consistent). Each
4750        /// query is `(pages, in_async_module, async module)`.
4751        async fn report(
4752            &self,
4753            queries: &[(&[&str], bool, &str)],
4754        ) -> Result<ReadRef<AsyncAvailabilityTestReport>> {
4755            async_availability_test_report(
4756                self.module_graph,
4757                self.modules
4758                    .iter()
4759                    .map(|(name, module)| (name.clone(), *module))
4760                    .collect(),
4761                queries
4762                    .iter()
4763                    .map(|(pages, in_async_module, module)| {
4764                        (
4765                            pages.iter().map(|p| RcStr::from(*p)).collect(),
4766                            *in_async_module,
4767                            RcStr::from(*module),
4768                        )
4769                    })
4770                    .collect(),
4771            )
4772            .read_strongly_consistent()
4773            .await
4774        }
4775    }
4776
4777    #[turbo_tasks::value(serialization = "skip", eq = "manual", cell = "new")]
4778    struct AsyncAvailabilityTestReport {
4779        /// The relevant chunk groups of each async module, described by name.
4780        relevant: Vec<(String, Vec<String>, bool)>,
4781        /// For each query: the availability before and after narrowing, and the narrowed available
4782        /// chunk groups by name.
4783        narrowed: Vec<(AvailabilityInfo, AvailabilityInfo, Vec<String>)>,
4784        /// For each query: the available chunk groups before narrowing, by name.
4785        narrowed_input: Vec<Vec<String>>,
4786    }
4787
4788    /// For each query, builds the availability that `chunk_group_content` produces for the entry
4789    /// chunk groups of `pages` (or the root availability), and narrows it for the async module.
4790    #[turbo_tasks::function(operation, root)]
4791    async fn async_availability_test_report(
4792        module_graph: ResolvedVc<ModuleGraph>,
4793        modules: Vec<(RcStr, ResolvedVc<Box<dyn Module>>)>,
4794        queries: Vec<(Vec<RcStr>, bool, RcStr)>,
4795    ) -> Result<Vc<AsyncAvailabilityTestReport>> {
4796        let by_name = modules.iter().cloned().collect::<FxHashMap<_, _>>();
4797        let names = modules
4798            .iter()
4799            .map(|(name, module)| (*module, name.clone()))
4800            .collect::<FxHashMap<_, _>>();
4801        let info = module_graph.chunk_group_info().await?;
4802        let chunk_groups = info.chunk_groups.await?;
4803        let describe = |groups: &Bitset| {
4804            let mut groups = groups
4805                .iter()
4806                .map(|index| describe_chunk_group(&chunk_groups, index as usize, &names))
4807                .collect::<Vec<_>>();
4808            groups.sort();
4809            groups
4810        };
4811
4812        let mut relevant = info
4813            .async_loader_relevant_chunk_groups
4814            .await?
4815            .iter()
4816            .map(|(module, relevant)| {
4817                // Stored in a stable order, so that an entry only changes when its sets do.
4818                assert!(
4819                    relevant
4820                        .observed_chunk_groups
4821                        .windows(2)
4822                        .all(|w| w[0].iter().lt(w[1].iter())),
4823                    "observed chunk groups must be distinct and sorted"
4824                );
4825                (
4826                    names[module].to_string(),
4827                    describe(&relevant.chunk_groups),
4828                    relevant.needs_entry_group(),
4829                )
4830            })
4831            .collect::<Vec<_>>();
4832        relevant.sort();
4833
4834        let mut narrowed = Vec::new();
4835        let mut narrowed_input = Vec::new();
4836        for (pages, in_async_module, module) in queries {
4837            let pages = pages.iter().map(|p| by_name[p]).collect::<Vec<_>>();
4838            let mut availability = AvailabilityInfo::root();
4839            for page in &pages {
4840                availability = availability
4841                    .with_chunk_group(module_graph, ChunkGroupKey::Entry(vec![*page]))
4842                    .await?;
4843            }
4844            if !pages.is_empty() {
4845                availability = availability.with_entry_group(ResolvedVc::cell(pages));
4846            }
4847            if in_async_module {
4848                availability = availability.in_async_module();
4849            }
4850            let result = availability
4851                .canonicalize_for_async_loader(module_graph, by_name[&module])
4852                .await?;
4853            // The canonical availability must answer every observed test like the original one.
4854            if let Some(relevant) = info
4855                .async_loader_relevant_chunk_groups
4856                .get(&by_name[&module])
4857                .await?
4858            {
4859                let chunk_groups = async |availability: AvailabilityInfo| -> Result<Bitset> {
4860                    Ok(match availability.available_chunk_groups() {
4861                        Some(available) => available.await?.chunk_groups(module_graph)?.clone(),
4862                        None => Bitset::new(),
4863                    })
4864                };
4865                let before = chunk_groups(availability).await?;
4866                let after = chunk_groups(result).await?;
4867                for observed in &relevant.observed_chunk_groups {
4868                    assert_eq!(
4869                        observed.is_disjoint(&before),
4870                        observed.is_disjoint(&after),
4871                        "canonical availability changes the test for {observed:?}"
4872                    );
4873                }
4874            }
4875            let available = match result.available_chunk_groups() {
4876                Some(available) => describe(available.await?.chunk_groups(module_graph)?),
4877                None => vec![],
4878            };
4879            narrowed_input.push(match availability.available_chunk_groups() {
4880                Some(available) => describe(available.await?.chunk_groups(module_graph)?),
4881                None => vec![],
4882            });
4883            narrowed.push((availability, result, available));
4884        }
4885
4886        Ok(AsyncAvailabilityTestReport {
4887            relevant,
4888            narrowed,
4889            narrowed_input,
4890        }
4891        .cell())
4892    }
4893
4894    fn describe_chunk_group(
4895        info: &[ChunkGroup],
4896        index: usize,
4897        names: &FxHashMap<ResolvedVc<Box<dyn Module>>, RcStr>,
4898    ) -> String {
4899        let name = |module: &ResolvedVc<Box<dyn Module>>| names[module].to_string();
4900        match chunk_group_at(info, index).unwrap() {
4901            ChunkGroup::Entry(modules) => format!(
4902                "entry {}",
4903                modules.iter().map(name).collect::<Vec<_>>().join(",")
4904            ),
4905            ChunkGroup::Async(module) => format!("async {}", name(module)),
4906            ChunkGroup::Shared(module) => format!("shared {}", name(module)),
4907            ChunkGroup::Isolated(module) => format!("isolated {}", name(module)),
4908            ChunkGroup::Collected(module) => format!("collected {}", name(module)),
4909            ChunkGroup::SharedMerged {
4910                parent, merge_tag, ..
4911            } => format!(
4912                "shared merged {merge_tag} of ({})",
4913                describe_chunk_group(info, *parent, names)
4914            ),
4915            other => panic!("unexpected chunk group {other:?}"),
4916        }
4917    }
4918
4919    fn relevant(
4920        module: &str,
4921        groups: &[&str],
4922        needs_entry_group: bool,
4923    ) -> (String, Vec<String>, bool) {
4924        let mut groups = groups.iter().map(|g| g.to_string()).collect::<Vec<_>>();
4925        groups.sort();
4926        (module.to_string(), groups, needs_entry_group)
4927    }
4928
4929    /// Two pages load the same async module, whose subgraph is disjoint from both pages: the
4930    /// narrowed availability is identical, so both share one async loader.
4931    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4932    async fn test_async_loader_availability_disjoint() {
4933        run_turbo_test(async {
4934            let test = AsyncAvailabilityTest::new(
4935                &[
4936                    ("p1.js", &["lazy.js", "s.js"]),
4937                    ("p2.js", &["lazy.js", "s.js"]),
4938                    ("lazy.js", &["leaf.js"]),
4939                ],
4940                &[("p1.js", "lazy.js", "async"), ("p2.js", "lazy.js", "async")],
4941                &["p1.js", "p2.js"],
4942                &[],
4943            )
4944            .await?;
4945            let report = test
4946                .report(&[(&["p1.js"], true, "lazy.js"), (&["p2.js"], true, "lazy.js")])
4947                .await?;
4948            assert_eq!(
4949                report.relevant,
4950                vec![relevant("lazy.js", &["async lazy.js"], false)]
4951            );
4952
4953            let (p1_before, p1, _) = report.narrowed[0];
4954            let (p2_before, p2, _) = report.narrowed[1];
4955            assert_ne!(p1_before, p2_before);
4956            // Equal task inputs, so `async_loader_chunk_item(lazy, graph, availability)` is one
4957            // task for both pages.
4958            assert_eq!(p1, p2);
4959            assert_eq!(p1.available_chunk_groups(), None);
4960            assert_eq!(p1.entry_group(), None);
4961            assert!(p1.is_in_async_module());
4962            Ok(())
4963        })
4964        .await
4965    }
4966
4967    /// Both pages and the async module use one shared module, like `react/jsx-runtime`. Both pages
4968    /// make the same modules available, so they share one loader.
4969    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4970    async fn test_async_loader_availability_shared_with_all_pages() {
4971        run_turbo_test(async {
4972            let test = AsyncAvailabilityTest::new(
4973                &[
4974                    ("p1.js", &["lazy.js", "runtime.js"]),
4975                    ("p2.js", &["lazy.js", "runtime.js"]),
4976                    ("lazy.js", &["runtime.js", "leaf.js"]),
4977                ],
4978                &[("p1.js", "lazy.js", "async"), ("p2.js", "lazy.js", "async")],
4979                &["p1.js", "p2.js"],
4980                &[],
4981            )
4982            .await?;
4983            let report = test
4984                .report(&[(&["p1.js"], true, "lazy.js"), (&["p2.js"], true, "lazy.js")])
4985                .await?;
4986            let (p1_before, p1, ref p1_available) = report.narrowed[0];
4987            let (p2_before, p2, _) = report.narrowed[1];
4988            assert_ne!(p1_before, p2_before);
4989            assert_eq!(p1, p2);
4990            assert_eq!(
4991                p1_available,
4992                &vec!["entry p1.js".to_string(), "entry p2.js".to_string()]
4993            );
4994            Ok(())
4995        })
4996        .await
4997    }
4998
4999    /// A module shared between a page and the async module keeps that page's chunk group, which
5000    /// makes the module available in the async chunk group.
5001    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5002    async fn test_async_loader_availability_shared_with_page() {
5003        run_turbo_test(async {
5004            let test = AsyncAvailabilityTest::new(
5005                &[
5006                    ("p1.js", &["lazy.js", "shared.js"]),
5007                    ("p2.js", &["lazy.js"]),
5008                    ("lazy.js", &["shared.js"]),
5009                ],
5010                &[("p1.js", "lazy.js", "async"), ("p2.js", "lazy.js", "async")],
5011                &["p1.js", "p2.js"],
5012                &[],
5013            )
5014            .await?;
5015            let report = test
5016                .report(&[
5017                    (&["p1.js"], true, "lazy.js"),
5018                    (&["p2.js"], true, "lazy.js"),
5019                    (&["p1.js", "p2.js"], true, "lazy.js"),
5020                ])
5021                .await?;
5022            assert_eq!(
5023                report.relevant,
5024                vec![relevant(
5025                    "lazy.js",
5026                    &["async lazy.js", "entry p1.js"],
5027                    false
5028                )]
5029            );
5030
5031            let (_, from_p1, ref from_p1_available) = report.narrowed[0];
5032            assert_eq!(from_p1_available, &vec!["entry p1.js".to_string()]);
5033            let (_, from_p2, _) = report.narrowed[1];
5034            assert_eq!(from_p2.available_chunk_groups(), None);
5035
5036            // Narrowing to an equal set yields the same cell, however the input was built.
5037            let (_, from_both, _) = report.narrowed[2];
5038            assert_eq!(
5039                from_both.available_chunk_groups(),
5040                from_p1.available_chunk_groups()
5041            );
5042            Ok(())
5043        })
5044        .await
5045    }
5046
5047    /// Nested async chunk groups are chunked with the availability of their parent, so the parent
5048    /// depends on what they observe, and on the chunk groups of the nested async loader (which
5049    /// includes importers outside of the parent).
5050    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5051    async fn test_async_loader_availability_nested() {
5052        run_turbo_test(async {
5053            let test = AsyncAvailabilityTest::new(
5054                &[
5055                    ("p1.js", &["a.js", "x.js"]),
5056                    ("p2.js", &["b.js"]),
5057                    ("a.js", &["b.js"]),
5058                    ("b.js", &["x.js"]),
5059                ],
5060                &[
5061                    ("p1.js", "a.js", "async"),
5062                    ("a.js", "b.js", "async"),
5063                    ("p2.js", "b.js", "async"),
5064                ],
5065                &["p1.js", "p2.js"],
5066                &[],
5067            )
5068            .await?;
5069            // The queries also check that the canonical availability keeps every observed test.
5070            let report = test
5071                .report(&[
5072                    (&["p1.js"], true, "a.js"),
5073                    (&["p2.js"], true, "a.js"),
5074                    (&["p1.js", "p2.js"], true, "a.js"),
5075                    (&["p1.js"], true, "b.js"),
5076                    (&["p2.js"], true, "b.js"),
5077                ])
5078                .await?;
5079            assert_eq!(
5080                report.relevant,
5081                vec![
5082                    relevant(
5083                        "a.js",
5084                        &["async a.js", "async b.js", "entry p1.js", "entry p2.js"],
5085                        false
5086                    ),
5087                    relevant("b.js", &["async b.js", "entry p1.js"], false),
5088                ]
5089            );
5090            Ok(())
5091        })
5092        .await
5093    }
5094
5095    /// Chunking continues through shared references, so the members of shared (and shared merged)
5096    /// chunk groups count.
5097    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5098    async fn test_async_loader_availability_shared_references() {
5099        run_turbo_test(async {
5100            let test = AsyncAvailabilityTest::new(
5101                &[
5102                    ("p1.js", &["a.js", "y.js"]),
5103                    ("p2.js", &["w.js"]),
5104                    ("a.js", &["s.js", "t.js"]),
5105                    ("s.js", &["y.js"]),
5106                    ("t.js", &["w.js"]),
5107                ],
5108                &[
5109                    ("p1.js", "a.js", "async"),
5110                    ("a.js", "s.js", "shared"),
5111                    ("a.js", "t.js", "shared-merged"),
5112                ],
5113                &["p1.js", "p2.js"],
5114                &[],
5115            )
5116            .await?;
5117            assert_eq!(
5118                test.report(&[]).await?.relevant,
5119                vec![relevant(
5120                    "a.js",
5121                    &[
5122                        "async a.js",
5123                        "entry p1.js",
5124                        "entry p2.js",
5125                        "shared merged m of (async a.js)",
5126                        "shared s.js"
5127                    ],
5128                    false
5129                )]
5130            );
5131            Ok(())
5132        })
5133        .await
5134    }
5135
5136    /// Async modules that import each other (and themselves) share the closure.
5137    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5138    async fn test_async_loader_availability_cycles() {
5139        run_turbo_test(async {
5140            let test = AsyncAvailabilityTest::new(
5141                &[
5142                    ("p1.js", &["a.js", "c.js", "d.js", "z.js"]),
5143                    ("a.js", &["b.js"]),
5144                    ("b.js", &["a.js", "z.js"]),
5145                    ("c.js", &["c.js"]),
5146                    ("d.js", &["q.js"]),
5147                ],
5148                &[
5149                    ("p1.js", "a.js", "async"),
5150                    ("a.js", "b.js", "async"),
5151                    ("b.js", "a.js", "async"),
5152                    ("p1.js", "c.js", "async"),
5153                    ("c.js", "c.js", "async"),
5154                    ("p1.js", "d.js", "async"),
5155                ],
5156                &["p1.js"],
5157                &[],
5158            )
5159            .await?;
5160            assert_eq!(
5161                test.report(&[]).await?.relevant,
5162                vec![
5163                    relevant("a.js", &["async a.js", "async b.js", "entry p1.js"], false),
5164                    relevant("b.js", &["async a.js", "async b.js", "entry p1.js"], false),
5165                    // The self import creates a loader for `c` inside of `c`.
5166                    relevant("c.js", &["async c.js", "entry p1.js"], false),
5167                    relevant("d.js", &["async d.js"], false),
5168                ]
5169            );
5170            Ok(())
5171        })
5172        .await
5173    }
5174
5175    /// Chunking doesn't continue through isolated and traced references.
5176    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5177    async fn test_async_loader_availability_isolated_and_traced() {
5178        run_turbo_test(async {
5179            let test = AsyncAvailabilityTest::new(
5180                &[
5181                    ("p1.js", &["a.js", "w.js", "v.js"]),
5182                    ("a.js", &["i.js", "t.js"]),
5183                    ("i.js", &["w.js"]),
5184                    ("t.js", &["v.js"]),
5185                ],
5186                &[
5187                    ("p1.js", "a.js", "async"),
5188                    ("a.js", "i.js", "isolated"),
5189                    ("a.js", "t.js", "traced"),
5190                ],
5191                &["p1.js"],
5192                &[],
5193            )
5194            .await?;
5195            assert_eq!(
5196                test.report(&[]).await?.relevant,
5197                vec![relevant("a.js", &["async a.js"], false)]
5198            );
5199            Ok(())
5200        })
5201        .await
5202    }
5203
5204    /// An async chunk group that is a graph entry, without an importer.
5205    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5206    async fn test_async_loader_availability_async_entry() {
5207        run_turbo_test(async {
5208            let test = AsyncAvailabilityTest::new(
5209                &[("p1.js", &["f.js"]), ("e.js", &["f.js"])],
5210                &[],
5211                &["p1.js"],
5212                &["e.js"],
5213            )
5214            .await?;
5215            assert_eq!(
5216                test.report(&[]).await?.relevant,
5217                vec![relevant("e.js", &["async e.js", "entry p1.js"], false)]
5218            );
5219            Ok(())
5220        })
5221        .await
5222    }
5223
5224    /// Without available chunk groups there is nothing to narrow; the flags are kept.
5225    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5226    async fn test_async_loader_availability_root() {
5227        run_turbo_test(async {
5228            let test = AsyncAvailabilityTest::new(
5229                &[("p1.js", &["lazy.js"])],
5230                &[("p1.js", "lazy.js", "async")],
5231                &["p1.js"],
5232                &[],
5233            )
5234            .await?;
5235            let report = test
5236                .report(&[(&[], false, "lazy.js"), (&[], true, "lazy.js")])
5237                .await?;
5238            for (before, after, _) in &report.narrowed {
5239                assert_eq!(after, before);
5240            }
5241            assert!(!report.narrowed[0].1.is_in_async_module());
5242            assert!(report.narrowed[1].1.is_in_async_module());
5243            Ok(())
5244        })
5245        .await
5246    }
5247
5248    /// A collecting module reads the entry group. Collected modules are chunked into the chunk
5249    /// group of the collecting module, so their chunk groups count too.
5250    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5251    async fn test_async_loader_availability_collect() {
5252        run_turbo_test(async {
5253            let test = AsyncAvailabilityTest::new(
5254                &[
5255                    ("p1.js", &["a.js", "b.js", "e.js"]),
5256                    ("p2.js", &["c.js"]),
5257                    ("a.js", &["collect.js"]),
5258                    ("b.js", &["h.js"]),
5259                    ("c.js", &["collect-empty.js"]),
5260                    ("e.js", &["g.js"]),
5261                ],
5262                &[
5263                    ("p1.js", "a.js", "async"),
5264                    ("p1.js", "b.js", "async"),
5265                    ("p2.js", "c.js", "async"),
5266                    ("p1.js", "e.js", "emitted"),
5267                    ("a.js", "collect.js", "per-entry"),
5268                    ("c.js", "collect-empty.js", "per-entry"),
5269                ],
5270                &["p1.js", "p2.js"],
5271                &[],
5272            )
5273            .await?;
5274            let report = test
5275                .report(&[(&["p1.js"], true, "a.js"), (&["p1.js"], true, "b.js")])
5276                .await?;
5277            assert_eq!(
5278                report.relevant,
5279                vec![
5280                    relevant("a.js", &["async a.js", "collected e.js"], true),
5281                    relevant("b.js", &["async b.js"], false),
5282                    // Nothing is collected, but the collecting module still reads the entry group.
5283                    relevant("c.js", &["async c.js"], true),
5284                ]
5285            );
5286
5287            let (p1, a, _) = report.narrowed[0];
5288            assert_eq!(a.entry_group(), p1.entry_group());
5289            assert!(a.entry_group().is_some());
5290            let (_, b, _) = report.narrowed[1];
5291            assert_eq!(b.entry_group(), None);
5292            Ok(())
5293        })
5294        .await
5295    }
5296
5297    /// An activatable module (a lazily compiled dynamic import) keeps the availability its loader
5298    /// is given, so that names derived from it don't change when it activates. Async targets whose
5299    /// chunking reaches it stop at it and use the subset filter instead of the canonical
5300    /// availability (which may contain chunk groups the activated subgraph would misread), keep the
5301    /// entry group, and don't change on activation either.
5302    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5303    async fn test_async_loader_availability_activatable() {
5304        run_turbo_test(async {
5305            let dependencies = |active: bool| -> Vec<(&'static str, &'static [&'static str])> {
5306                let mut dependencies: Vec<(&str, &[&str])> = vec![
5307                    ("p1.js", &["a.js", "u.js", "runtime.js", "shared.js"]),
5308                    ("p2.js", &["a.js", "u.js", "runtime.js", "x.js"]),
5309                    ("a.js", &["proxy.js", "runtime.js", "shared.js"]),
5310                    ("u.js", &["runtime.js"]),
5311                ];
5312                if active {
5313                    dependencies.push(("proxy.js", &["leaf.js"]));
5314                    dependencies.push(("leaf.js", &["runtime.js", "x.js", "collect.js"]));
5315                }
5316                dependencies
5317            };
5318            let chunking_types = |active: bool| {
5319                let mut chunking_types = vec![
5320                    ("p1.js", "a.js", "async"),
5321                    ("p2.js", "a.js", "async"),
5322                    ("p1.js", "u.js", "async"),
5323                    ("p2.js", "u.js", "async"),
5324                    ("a.js", "proxy.js", "async"),
5325                ];
5326                if active {
5327                    chunking_types.push(("proxy.js", "leaf.js", "async"));
5328                    chunking_types.push(("leaf.js", "collect.js", "per-entry"));
5329                }
5330                chunking_types
5331            };
5332            let queries: &[(&[&str], bool, &str)] = &[
5333                (&["p1.js"], true, "a.js"),
5334                (&["p2.js"], true, "a.js"),
5335                (&["p1.js"], true, "u.js"),
5336                (&["p2.js"], true, "u.js"),
5337            ];
5338
5339            let mut reports = Vec::new();
5340            for active in [false, true] {
5341                let test = AsyncAvailabilityTest::new(
5342                    &dependencies(active),
5343                    &chunking_types(active),
5344                    &["p1.js", "p2.js"],
5345                    &[],
5346                )
5347                .await?;
5348                let mut queries = queries.to_vec();
5349                if active {
5350                    // `proxy` and `leaf` are only chunked through `a`.
5351                    queries.push((&["p1.js"], true, "proxy.js"));
5352                    queries.push((&["p1.js"], true, "leaf.js"));
5353                }
5354                reports.push(test.report(&queries).await?);
5355            }
5356            let (inactive, active) = (&reports[0], &reports[1]);
5357
5358            let relevant_of = |report: &AsyncAvailabilityTestReport, module: &str| {
5359                report.relevant.iter().find(|(m, ..)| m == module).cloned()
5360            };
5361            for (report, behind_proxy) in [(inactive, &[][..]), (active, &["async leaf.js"][..])] {
5362                // The activatable target keeps its availability.
5363                assert_eq!(relevant_of(report, "proxy.js"), None);
5364                // Its containing target stops at it and keeps the entry group. (The chunk groups
5365                // of `runtime.js` grow on activation, but only by chunk groups behind the proxy,
5366                // which are never available above it.)
5367                let mut groups = vec![
5368                    "async a.js",
5369                    "async proxy.js",
5370                    "async u.js",
5371                    "entry p1.js",
5372                    "entry p2.js",
5373                ];
5374                groups.extend(behind_proxy);
5375                assert_eq!(
5376                    relevant_of(report, "a.js"),
5377                    Some(relevant("a.js", &groups, true))
5378                );
5379                // An unrelated target is still canonical: both pages get the same availability,
5380                // which isn't a subset of either page's.
5381                let (_, from_p1, ref from_p1_available) = report.narrowed[2];
5382                let (_, from_p2, _) = report.narrowed[3];
5383                assert_eq!(from_p1, from_p2);
5384                assert!(from_p1_available.contains(&"entry p2.js".to_string()));
5385            }
5386
5387            // The containing target uses the subset filter and keeps the entry group.
5388            for (index, report) in [inactive, active].into_iter().enumerate() {
5389                for query in 0..2 {
5390                    let (before, after, ref after_available) = report.narrowed[query];
5391                    let before_available = &report.narrowed_input[query];
5392                    assert!(
5393                        after_available.iter().all(|g| before_available.contains(g)),
5394                        "graph {index}, query {query}: {after_available:?} is not a subset of \
5395                         {before_available:?}"
5396                    );
5397                    assert!(after.entry_group().is_some());
5398                    assert_eq!(after.entry_group(), before.entry_group());
5399                }
5400            }
5401            // Activation doesn't change it.
5402            for query in 0..2 {
5403                assert_eq!(inactive.narrowed[query].2, active.narrowed[query].2);
5404            }
5405
5406            // Behind the proxy, the activated target is canonicalized on its own (its collecting
5407            // module reads the entry group).
5408            assert_eq!(
5409                relevant_of(active, "leaf.js"),
5410                Some(relevant(
5411                    "leaf.js",
5412                    &[
5413                        "async a.js",
5414                        "async leaf.js",
5415                        "async u.js",
5416                        "entry p1.js",
5417                        "entry p2.js"
5418                    ],
5419                    true
5420                ))
5421            );
5422            // The proxy's own loader keeps the availability it is given.
5423            let (before, after, _) = active.narrowed[4];
5424            assert_eq!(after, before);
5425            // The activated target isn't limited to a subset: its canonical availability contains
5426            // chunk groups the input doesn't.
5427            let (_, _, ref leaf_available) = active.narrowed[5];
5428            assert!(
5429                leaf_available
5430                    .iter()
5431                    .any(|g| !active.narrowed_input[5].contains(g)),
5432                "{leaf_available:?} should be canonical"
5433            );
5434            Ok(())
5435        })
5436        .await
5437    }
5438
5439    #[turbo_tasks::value(transparent)]
5440    struct TestStep(State<u32>);
5441
5442    #[turbo_tasks::function(operation, root)]
5443    fn test_step_operation() -> Vc<TestStep> {
5444        TestStep(State::new(0)).cell()
5445    }
5446
5447    /// Step 1: `a` and `b` don't read the entry group. Step 2: `b` does. Step 3: `a` does too.
5448    #[turbo_tasks::function(operation, root)]
5449    async fn test_relevant_chunk_groups_operation(
5450        step: ResolvedVc<TestStep>,
5451        a: ResolvedVc<Box<dyn Module>>,
5452        b: ResolvedVc<Box<dyn Module>>,
5453    ) -> Result<Vc<AsyncLoaderRelevantChunkGroupsMap>> {
5454        let step = *step.await?.get();
5455        let entry = |reaches_collecting_module| AsyncLoaderRelevantChunkGroups {
5456            observed_chunk_groups: Default::default(),
5457            chunk_groups: Default::default(),
5458            reaches_collecting_module,
5459            reaches_activatable: false,
5460        };
5461        Ok(Vc::cell(FxHashMap::from_iter([
5462            (a, entry(step >= 3)),
5463            (b, entry(step >= 2)),
5464        ])))
5465    }
5466
5467    static NARROWED_EXECUTIONS: std::sync::atomic::AtomicUsize =
5468        std::sync::atomic::AtomicUsize::new(0);
5469
5470    #[turbo_tasks::value]
5471    struct NarrowedTestResult {
5472        keeps_entry_group: bool,
5473        execution: usize,
5474    }
5475
5476    #[turbo_tasks::function(operation, root)]
5477    async fn test_narrowed_operation(
5478        relevant: OperationVc<AsyncLoaderRelevantChunkGroupsMap>,
5479        module_graph: ResolvedVc<ModuleGraph>,
5480        module: ResolvedVc<Box<dyn Module>>,
5481        entry_group: ResolvedVc<Modules>,
5482    ) -> Result<Vc<NarrowedTestResult>> {
5483        let narrowed = AvailabilityInfo::root()
5484            .with_entry_group(entry_group)
5485            .canonicalize_for_async_loader_with(module_graph, relevant.connect(), module)
5486            .await?;
5487        Ok(NarrowedTestResult {
5488            keeps_entry_group: narrowed.entry_group().is_some(),
5489            execution: NARROWED_EXECUTIONS.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
5490        }
5491        .cell())
5492    }
5493
5494    /// Narrowing reads only the entry of the async module, so a change to another async module's
5495    /// entry doesn't invalidate it.
5496    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5497    async fn test_async_loader_availability_keyed_invalidation() {
5498        run_turbo_test(async {
5499            let test = AsyncAvailabilityTest::new(
5500                &[("p1.js", &["a.js", "b.js"])],
5501                &[("p1.js", "a.js", "async"), ("p1.js", "b.js", "async")],
5502                &["p1.js"],
5503                &[],
5504            )
5505            .await?;
5506            let step_op = test_step_operation();
5507            let step_vc = step_op.resolve().strongly_consistent().await?;
5508            let step = step_op.read_strongly_consistent().await?;
5509            step.set(1);
5510
5511            let relevant = test_relevant_chunk_groups_operation(
5512                step_vc,
5513                test.module("a.js"),
5514                test.module("b.js"),
5515            );
5516            let entry_group = ResolvedVc::cell(vec![test.module("p1.js")]);
5517            let a = test_narrowed_operation(
5518                relevant,
5519                test.module_graph,
5520                test.module("a.js"),
5521                entry_group,
5522            );
5523            let b = test_narrowed_operation(
5524                relevant,
5525                test.module_graph,
5526                test.module("b.js"),
5527                entry_group,
5528            );
5529
5530            let a1 = a.read_strongly_consistent().await?;
5531            let b1 = b.read_strongly_consistent().await?;
5532            assert!(!a1.keeps_entry_group);
5533            assert!(!b1.keeps_entry_group);
5534
5535            // Only `b` changes.
5536            step.set(2);
5537            let a2 = a.read_strongly_consistent().await?;
5538            let b2 = b.read_strongly_consistent().await?;
5539            assert!(!a2.keeps_entry_group);
5540            assert!(b2.keeps_entry_group);
5541            assert_eq!(a1.execution, a2.execution, "`a` must not be invalidated");
5542            assert_ne!(b1.execution, b2.execution);
5543
5544            // Only `a` changes.
5545            step.set(3);
5546            let a3 = a.read_strongly_consistent().await?;
5547            let b3 = b.read_strongly_consistent().await?;
5548            assert!(a3.keeps_entry_group);
5549            assert!(b3.keeps_entry_group);
5550            assert_ne!(a2.execution, a3.execution);
5551            assert_eq!(b2.execution, b3.execution, "`b` must not be invalidated");
5552            Ok(())
5553        })
5554        .await
5555    }
5556
5557    /// `p1.js` loads `a.js` and `b.js` asynchronously. From step 2 on, `b.js` also loads
5558    /// `extra.js` asynchronously, which adds a chunk group (and a module) to the graph without
5559    /// changing anything about `a.js`.
5560    #[turbo_tasks::function(operation, root)]
5561    async fn changing_chunk_group_test_graph(
5562        step: ResolvedVc<TestStep>,
5563    ) -> Result<Vc<AsyncAvailabilityTestGraph>> {
5564        let step = *step.await?.get();
5565        let mut dependencies = vec![(rcstr!("p1.js"), vec![rcstr!("a.js"), rcstr!("b.js")])];
5566        let mut chunking_types = vec![
5567            (rcstr!("p1.js"), rcstr!("a.js"), rcstr!("async")),
5568            (rcstr!("p1.js"), rcstr!("b.js"), rcstr!("async")),
5569        ];
5570        if step >= 2 {
5571            dependencies.push((rcstr!("b.js"), vec![rcstr!("extra.js")]));
5572            chunking_types.push((rcstr!("b.js"), rcstr!("extra.js"), rcstr!("async")));
5573        }
5574        build_async_availability_test_graph(
5575            dependencies,
5576            chunking_types,
5577            vec![rcstr!("p1.js")],
5578            vec![],
5579        )
5580        .await
5581    }
5582
5583    #[turbo_tasks::value]
5584    struct ChunkGroupReadsTestResult {
5585        /// The chunk groups of `a.js`, by index.
5586        groups_of_a: Vec<u32>,
5587        /// The chunk groups that contain a loader of `a.js`, by index.
5588        loader_groups_of_a: Vec<u32>,
5589        /// The index of `a.js`'s async chunk group.
5590        index_of_a: u32,
5591    }
5592
5593    #[turbo_tasks::function(operation, root)]
5594    async fn chunk_group_reads_test_operation(
5595        module_graph: ResolvedVc<ModuleGraph>,
5596        a: ResolvedVc<Box<dyn Module>>,
5597    ) -> Result<Vc<ChunkGroupReadsTestResult>> {
5598        let chunk_group_info = module_graph.chunk_group_info();
5599        let groups_of_a = chunk_group_info
5600            .get_chunk_groups_for_module(*a)
5601            .await?
5602            .iter()
5603            .map(|g| g.index)
5604            .collect();
5605        let loader_groups_of_a = chunk_group_info
5606            .get_async_loader_ancestor_chunk_groups(*a)
5607            .await?
5608            .iter()
5609            .copied()
5610            .collect();
5611        let index_of_a = chunk_group_info
5612            .get_index_of(ChunkGroupKey::Async(a))
5613            .await? as u32;
5614        let chunk_group = chunk_group_info
5615            .get_chunk_group(ChunkGroupKey::Async(a))
5616            .await?;
5617        assert!(matches!(chunk_group, ChunkGroup::Async(m) if m == a));
5618        Ok(ChunkGroupReadsTestResult {
5619            groups_of_a,
5620            loader_groups_of_a,
5621            index_of_a,
5622        }
5623        .cell())
5624    }
5625
5626    fn task_executions(name: &str) -> u64 {
5627        let stats =
5628            serde_json::to_value(turbo_tasks::turbo_tasks().task_statistics().get()).unwrap();
5629        stats
5630            .as_object()
5631            .unwrap()
5632            .iter()
5633            .filter(|(key, _)| key.ends_with(name))
5634            .map(|(_, value)| value["executions"].as_u64().unwrap_or(0))
5635            .sum()
5636    }
5637
5638    /// Reading one chunk group's data doesn't depend on the whole `ChunkGroupInfo`: adding an
5639    /// unrelated chunk group doesn't re-execute the per-module chunk group lookups of `a.js`.
5640    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5641    async fn test_chunk_group_info_reads_are_narrow() {
5642        run_turbo_test(async {
5643            turbo_tasks::turbo_tasks().task_statistics().enable();
5644            let step_op = test_step_operation();
5645            let step_vc = step_op.resolve().strongly_consistent().await?;
5646            let step = step_op.read_strongly_consistent().await?;
5647            step.set(1);
5648
5649            let graph_op = changing_chunk_group_test_graph(step_vc);
5650            let graph1 = graph_op.read_strongly_consistent().await?;
5651            let module = |graph: &AsyncAvailabilityTestGraph, name: &str| {
5652                *graph
5653                    .modules
5654                    .get(&RcStr::from(name))
5655                    .unwrap_or_else(|| panic!("no module {name}"))
5656            };
5657            let a = module(&graph1, "a.js");
5658            let reads = chunk_group_reads_test_operation(graph1.module_graph, a);
5659            let read1 = reads.read_strongly_consistent().await?;
5660            assert!(!read1.groups_of_a.is_empty());
5661            assert!(!read1.loader_groups_of_a.is_empty());
5662            let lookups1 = task_executions("ChunkGroupInfo::get_chunk_groups_for_module");
5663            let loaders1 =
5664                task_executions("ChunkGroupInfo::get_async_loader_ancestor_chunk_groups");
5665            assert!(lookups1 >= 1 && loaders1 >= 1, "{lookups1} {loaders1}");
5666
5667            // Add a chunk group that has nothing to do with `a.js`.
5668            step.set(2);
5669            let graph2 = graph_op.read_strongly_consistent().await?;
5670            assert!(graph2.modules.contains_key(&RcStr::from("extra.js")));
5671            assert_eq!(graph2.module_graph, graph1.module_graph);
5672            assert_eq!(module(&graph2, "a.js"), a);
5673            let read2 = reads.read_strongly_consistent().await?;
5674            // The premise: nothing about `a.js` changed.
5675            assert_eq!(read2.groups_of_a, read1.groups_of_a);
5676            assert_eq!(read2.loader_groups_of_a, read1.loader_groups_of_a);
5677            assert_eq!(read2.index_of_a, read1.index_of_a);
5678            assert_eq!(
5679                task_executions("ChunkGroupInfo::get_chunk_groups_for_module"),
5680                lookups1,
5681                "the chunk groups of `a.js` must not be recomputed"
5682            );
5683            assert_eq!(
5684                task_executions("ChunkGroupInfo::get_async_loader_ancestor_chunk_groups"),
5685                loaders1,
5686                "the loader chunk groups of `a.js` must not be recomputed"
5687            );
5688            Ok(())
5689        })
5690        .await
5691    }
5692}