Skip to main content

fallow_graph/graph/
cycles.rs

1//! Circular dependency detection via Tarjan's SCC algorithm + elementary cycle enumeration.
2
3use std::ops::Range;
4
5use fixedbitset::FixedBitSet;
6use rustc_hash::FxHashSet;
7
8use fallow_types::discover::FileId;
9
10use super::ModuleGraph;
11use super::types::ModuleNode;
12
13impl ModuleGraph {
14    /// Find all circular dependency cycles in the module graph.
15    ///
16    /// Uses an iterative implementation of Tarjan's strongly connected components
17    /// algorithm (O(V + E)) to find all SCCs with 2 or more nodes. Each such SCC
18    /// represents a set of files involved in a circular dependency.
19    ///
20    /// Returns cycles sorted by length (shortest first), with files within each
21    /// cycle sorted by path for deterministic output.
22    ///
23    /// # Panics
24    ///
25    /// Panics if the internal file-to-path lookup is inconsistent with the module list.
26    #[must_use]
27    pub fn find_cycles(&self) -> Vec<Vec<FileId>> {
28        let n = self.modules.len();
29        if n == 0 {
30            return Vec::new();
31        }
32
33        let (all_succs, succ_ranges) = self.build_runtime_successors(n);
34
35        let mut state = SccState::new(n);
36        for start_node in 0..n {
37            if state.indices[start_node] != u32::MAX {
38                continue;
39            }
40            state.run_dfs_from(start_node, &all_succs, &succ_ranges);
41        }
42
43        self.enumerate_cycles_from_sccs(&state.sccs, &all_succs, &succ_ranges)
44    }
45
46    /// Build the flattened runtime-successor adjacency (type-only edges and
47    /// duplicate targets excluded) plus the per-node range index into it.
48    fn build_runtime_successors(&self, n: usize) -> (Vec<usize>, Vec<Range<usize>>) {
49        let mut all_succs: Vec<usize> = Vec::with_capacity(self.edges.len());
50        let mut succ_ranges: Vec<Range<usize>> = Vec::with_capacity(n);
51        let mut seen_set = FxHashSet::default();
52        for module in &self.modules {
53            let start = all_succs.len();
54            seen_set.clear();
55            for edge in &self.edges[module.edge_range.clone()] {
56                if edge.symbols.iter().all(|s| s.is_type_only) {
57                    continue;
58                }
59                let target = edge.target.0 as usize;
60                if target < n && seen_set.insert(target) {
61                    all_succs.push(target);
62                }
63            }
64            let end = all_succs.len();
65            succ_ranges.push(start..end);
66        }
67        (all_succs, succ_ranges)
68    }
69
70    /// Enumerate individual elementary cycles from SCCs and return sorted results.
71    #[expect(
72        clippy::cast_possible_truncation,
73        reason = "file count is bounded by project size, well under u32::MAX"
74    )]
75    fn enumerate_cycles_from_sccs(
76        &self,
77        sccs: &[Vec<FileId>],
78        all_succs: &[usize],
79        succ_ranges: &[Range<usize>],
80    ) -> Vec<Vec<FileId>> {
81        const MAX_CYCLES_PER_SCC: usize = 20;
82
83        let succs = SuccessorMap {
84            all_succs,
85            succ_ranges,
86            modules: &self.modules,
87        };
88
89        let mut result: Vec<Vec<FileId>> = Vec::new();
90        let mut seen_cycles: FxHashSet<Vec<u32>> = FxHashSet::default();
91
92        for scc in sccs {
93            if scc.len() == 2 {
94                let mut cycle = vec![scc[0].0 as usize, scc[1].0 as usize];
95                if self.modules[cycle[1]].path < self.modules[cycle[0]].path {
96                    cycle.swap(0, 1);
97                }
98                let key: Vec<u32> = cycle.iter().map(|&n| n as u32).collect();
99                if seen_cycles.insert(key) {
100                    result.push(cycle.into_iter().map(|n| FileId(n as u32)).collect());
101                }
102                continue;
103            }
104
105            let scc_nodes: Vec<usize> = scc.iter().map(|id| id.0 as usize).collect();
106            let elementary = enumerate_elementary_cycles(&scc_nodes, &succs, MAX_CYCLES_PER_SCC);
107
108            for cycle in elementary {
109                let key: Vec<u32> = cycle.iter().map(|&n| n as u32).collect();
110                if seen_cycles.insert(key) {
111                    result.push(cycle.into_iter().map(|n| FileId(n as u32)).collect());
112                }
113            }
114        }
115
116        result.sort_by(|a, b| {
117            a.len().cmp(&b.len()).then_with(|| {
118                self.modules[a[0].0 as usize]
119                    .path
120                    .cmp(&self.modules[b[0].0 as usize].path)
121            })
122        });
123
124        result
125    }
126}
127
128/// One iterative-DFS frame for the Tarjan SCC pass over runtime successors.
129struct SccFrame {
130    node: usize,
131    succ_pos: usize,
132    succ_end: usize,
133}
134
135/// Mutable Tarjan SCC state for `find_cycles`, collecting SCCs of size >= 2.
136struct SccState {
137    index_counter: u32,
138    indices: Vec<u32>,
139    lowlinks: Vec<u32>,
140    on_stack: FixedBitSet,
141    stack: Vec<usize>,
142    sccs: Vec<Vec<FileId>>,
143}
144
145impl SccState {
146    fn new(n: usize) -> Self {
147        Self {
148            index_counter: 0,
149            indices: vec![u32::MAX; n],
150            lowlinks: vec![0; n],
151            on_stack: FixedBitSet::with_capacity(n),
152            stack: Vec::new(),
153            sccs: Vec::new(),
154        }
155    }
156
157    /// Assign the next DFS index to `node` and push it onto the SCC stack.
158    fn discover(&mut self, node: usize) {
159        self.indices[node] = self.index_counter;
160        self.lowlinks[node] = self.index_counter;
161        self.index_counter += 1;
162        self.on_stack.insert(node);
163        self.stack.push(node);
164    }
165
166    /// Build a frame spanning the successor range of `node`.
167    fn frame_for(node: usize, succ_ranges: &[Range<usize>]) -> SccFrame {
168        let range = &succ_ranges[node];
169        SccFrame {
170            node,
171            succ_pos: range.start,
172            succ_end: range.end,
173        }
174    }
175
176    /// Run the iterative Tarjan DFS rooted at `start`, appending discovered
177    /// SCCs of size >= 2 to `self.sccs`.
178    fn run_dfs_from(&mut self, start: usize, all_succs: &[usize], succ_ranges: &[Range<usize>]) {
179        self.discover(start);
180        let mut dfs_stack: Vec<SccFrame> = vec![Self::frame_for(start, succ_ranges)];
181
182        while let Some(frame) = dfs_stack.last_mut() {
183            if frame.succ_pos < frame.succ_end {
184                if let Some(child) = self.advance_frame(frame, all_succs) {
185                    dfs_stack.push(Self::frame_for(child, succ_ranges));
186                }
187            } else {
188                let v = frame.node;
189                let v_lowlink = self.lowlinks[v];
190                dfs_stack.pop();
191                if let Some(parent) = dfs_stack.last() {
192                    let pv = parent.node;
193                    self.lowlinks[pv] = self.lowlinks[pv].min(v_lowlink);
194                }
195                self.collect_root_scc(v);
196            }
197        }
198    }
199
200    /// Advance one successor of `frame`, discovering a new child (returned for
201    /// descent) or updating the lowlink for an on-stack back edge.
202    fn advance_frame(&mut self, frame: &mut SccFrame, all_succs: &[usize]) -> Option<usize> {
203        let w = all_succs[frame.succ_pos];
204        frame.succ_pos += 1;
205        if self.indices[w] == u32::MAX {
206            self.discover(w);
207            Some(w)
208        } else {
209            if self.on_stack.contains(w) {
210                let v = frame.node;
211                self.lowlinks[v] = self.lowlinks[v].min(self.indices[w]);
212            }
213            None
214        }
215    }
216
217    /// When `v` is an SCC root, pop its members off the stack and record the
218    /// SCC if it has at least two nodes.
219    #[expect(
220        clippy::cast_possible_truncation,
221        reason = "file count is bounded by project size, well under u32::MAX"
222    )]
223    #[expect(
224        clippy::expect_used,
225        reason = "Tarjan traversal only pops nodes that were pushed onto the SCC stack"
226    )]
227    fn collect_root_scc(&mut self, v: usize) {
228        if self.lowlinks[v] != self.indices[v] {
229            return;
230        }
231        let mut scc = Vec::new();
232        loop {
233            let w = self.stack.pop().expect("SCC stack should not be empty");
234            self.on_stack.set(w, false);
235            scc.push(FileId(w as u32));
236            if w == v {
237                break;
238            }
239        }
240        if scc.len() >= 2 {
241            self.sccs.push(scc);
242        }
243    }
244}
245
246/// Rotate a cycle so the node with the smallest path is first (canonical form for dedup).
247fn canonical_cycle(cycle: &[usize], modules: &[ModuleNode]) -> Vec<usize> {
248    if cycle.is_empty() {
249        return Vec::new();
250    }
251    let min_pos = cycle
252        .iter()
253        .enumerate()
254        .min_by(|(_, a), (_, b)| modules[**a].path.cmp(&modules[**b].path))
255        .map_or(0, |(i, _)| i);
256    let mut result = cycle[min_pos..].to_vec();
257    result.extend_from_slice(&cycle[..min_pos]);
258    result
259}
260
261struct CycleFrame {
262    succ_pos: usize,
263    succ_end: usize,
264}
265
266struct SuccessorMap<'a> {
267    all_succs: &'a [usize],
268    succ_ranges: &'a [Range<usize>],
269    modules: &'a [ModuleNode],
270}
271
272#[expect(
273    clippy::cast_possible_truncation,
274    reason = "file count is bounded by project size, well under u32::MAX"
275)]
276fn try_record_cycle(
277    path: &[usize],
278    modules: &[ModuleNode],
279    seen: &mut FxHashSet<Vec<u32>>,
280    cycles: &mut Vec<Vec<usize>>,
281) {
282    let canonical = canonical_cycle(path, modules);
283    let key: Vec<u32> = canonical.iter().map(|&n| n as u32).collect();
284    if seen.insert(key) {
285        cycles.push(canonical);
286    }
287}
288
289/// Run a bounded DFS from `start`, looking for elementary cycles of exactly `depth_limit` nodes.
290///
291/// Appends any newly found cycles to `cycles` (deduped via `seen`).
292/// Stops early once `cycles.len() >= max_cycles`.
293struct DfsCycleInput<'a> {
294    start: usize,
295    depth_limit: usize,
296    scc_set: &'a FxHashSet<usize>,
297    succs: &'a SuccessorMap<'a>,
298    max_cycles: usize,
299    seen: &'a mut FxHashSet<Vec<u32>>,
300    cycles: &'a mut Vec<Vec<usize>>,
301}
302
303fn dfs_find_cycles_from(input: &mut DfsCycleInput<'_>) {
304    let mut path: Vec<usize> = vec![input.start];
305    let mut path_set = FixedBitSet::with_capacity(input.succs.modules.len());
306    path_set.insert(input.start);
307
308    let range = &input.succs.succ_ranges[input.start];
309    let mut dfs: Vec<CycleFrame> = vec![CycleFrame {
310        succ_pos: range.start,
311        succ_end: range.end,
312    }];
313
314    while let Some(frame) = dfs.last_mut() {
315        if input.cycles.len() >= input.max_cycles {
316            return;
317        }
318
319        if frame.succ_pos >= frame.succ_end {
320            dfs.pop();
321            if path.len() > 1 {
322                let Some(removed) = path.pop() else {
323                    continue;
324                };
325                path_set.set(removed, false);
326            }
327            continue;
328        }
329
330        let w = input.succs.all_succs[frame.succ_pos];
331        frame.succ_pos += 1;
332
333        if !input.scc_set.contains(&w) {
334            continue;
335        }
336
337        if w == input.start && path.len() >= 2 && path.len() == input.depth_limit {
338            try_record_cycle(&path, input.succs.modules, input.seen, input.cycles);
339            continue;
340        }
341
342        if path_set.contains(w) || path.len() >= input.depth_limit {
343            continue;
344        }
345
346        path.push(w);
347        path_set.insert(w);
348
349        let range = &input.succs.succ_ranges[w];
350        dfs.push(CycleFrame {
351            succ_pos: range.start,
352            succ_end: range.end,
353        });
354    }
355}
356
357/// Enumerate individual elementary cycles within an SCC using depth-limited DFS.
358///
359/// Uses iterative deepening: first finds all 2-node cycles, then 3-node, etc.
360/// This ensures the shortest, most actionable cycles are always found first.
361/// Stops after `max_cycles` total cycles to bound work on dense SCCs.
362fn enumerate_elementary_cycles(
363    scc_nodes: &[usize],
364    succs: &SuccessorMap<'_>,
365    max_cycles: usize,
366) -> Vec<Vec<usize>> {
367    let scc_set: FxHashSet<usize> = scc_nodes.iter().copied().collect();
368    let mut cycles: Vec<Vec<usize>> = Vec::new();
369    let mut seen: FxHashSet<Vec<u32>> = FxHashSet::default();
370
371    let mut sorted_nodes: Vec<usize> = scc_nodes.to_vec();
372    sorted_nodes.sort_by(|a, b| succs.modules[*a].path.cmp(&succs.modules[*b].path));
373
374    let max_depth = scc_nodes.len().min(12); // Cap depth to avoid very long cycles
375    for depth_limit in 2..=max_depth {
376        if cycles.len() >= max_cycles {
377            break;
378        }
379
380        for &start in &sorted_nodes {
381            if cycles.len() >= max_cycles {
382                break;
383            }
384
385            dfs_find_cycles_from(&mut DfsCycleInput {
386                start,
387                depth_limit,
388                scc_set: &scc_set,
389                succs,
390                max_cycles,
391                seen: &mut seen,
392                cycles: &mut cycles,
393            });
394        }
395    }
396
397    cycles
398}
399
400#[cfg(test)]
401mod tests {
402    use std::ops::Range;
403    use std::path::PathBuf;
404
405    use rustc_hash::FxHashSet;
406
407    use crate::graph::types::ModuleNode;
408    use crate::resolve::{ResolveResult, ResolvedImport, ResolvedModule};
409    use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
410    use fallow_types::extract::{ExportName, ImportInfo, ImportedName, VisibilityTag};
411
412    use super::{
413        DfsCycleInput, ModuleGraph, SuccessorMap, canonical_cycle, dfs_find_cycles_from,
414        enumerate_elementary_cycles, try_record_cycle,
415    };
416
417    /// Helper: build a graph from files+edges, no entry points needed for cycle detection.
418    #[expect(
419        clippy::cast_possible_truncation,
420        reason = "test file counts are trivially small"
421    )]
422    fn build_cycle_graph(file_count: usize, edges_spec: &[(u32, u32)]) -> ModuleGraph {
423        let files: Vec<DiscoveredFile> = (0..file_count)
424            .map(|i| DiscoveredFile {
425                id: FileId(i as u32),
426                path: PathBuf::from(format!("/project/file{i}.ts")),
427                size_bytes: 100,
428            })
429            .collect();
430
431        let resolved_modules: Vec<ResolvedModule> = (0..file_count)
432            .map(|i| {
433                let imports: Vec<ResolvedImport> = edges_spec
434                    .iter()
435                    .filter(|(src, _)| *src == i as u32)
436                    .map(|(_, tgt)| ResolvedImport {
437                        info: ImportInfo {
438                            source: format!("./file{tgt}"),
439                            imported_name: ImportedName::Named("x".to_string()),
440                            local_name: "x".to_string(),
441                            is_type_only: false,
442                            from_style: false,
443                            span: oxc_span::Span::new(0, 10),
444                            source_span: oxc_span::Span::default(),
445                        },
446                        target: ResolveResult::InternalModule(FileId(*tgt)),
447                    })
448                    .collect();
449
450                ResolvedModule {
451                    file_id: FileId(i as u32),
452                    path: PathBuf::from(format!("/project/file{i}.ts")),
453                    exports: vec![fallow_types::extract::ExportInfo {
454                        name: ExportName::Named("x".to_string()),
455                        local_name: Some("x".to_string()),
456                        is_type_only: false,
457                        visibility: VisibilityTag::None,
458                        expected_unused_reason: None,
459                        span: oxc_span::Span::new(0, 20),
460                        members: vec![],
461                        is_side_effect_used: false,
462                        super_class: None,
463                    }],
464                    re_exports: vec![],
465                    resolved_imports: imports,
466                    resolved_dynamic_imports: vec![],
467                    resolved_dynamic_patterns: vec![],
468                    member_accesses: vec![],
469                    semantic_facts: Box::default(),
470                    whole_object_uses: Box::default(),
471                    has_cjs_exports: false,
472                    has_angular_component_template_url: false,
473                    unused_import_bindings: FxHashSet::default(),
474                    type_referenced_import_bindings: vec![],
475                    value_referenced_import_bindings: vec![],
476                    namespace_object_aliases: vec![],
477                    exported_factory_returns: Box::default(),
478                    exported_factory_return_object_shapes: Box::default(),
479                    type_member_types: Box::default(),
480                }
481            })
482            .collect();
483
484        let entry_points = vec![EntryPoint {
485            path: PathBuf::from("/project/file0.ts"),
486            source: EntryPointSource::PackageJsonMain,
487        }];
488
489        ModuleGraph::build(&resolved_modules, &entry_points, &files)
490    }
491
492    fn dfs_find_cycles_from_for_test(mut input: DfsCycleInput<'_>) {
493        dfs_find_cycles_from(&mut input);
494    }
495
496    #[test]
497    fn find_cycles_empty_graph() {
498        let graph = ModuleGraph::build(&[], &[], &[]);
499        assert!(graph.find_cycles().is_empty());
500    }
501
502    #[test]
503    fn find_cycles_no_cycles() {
504        let graph = build_cycle_graph(3, &[(0, 1), (1, 2)]);
505        assert!(graph.find_cycles().is_empty());
506    }
507
508    #[test]
509    fn find_cycles_simple_two_node_cycle() {
510        let graph = build_cycle_graph(2, &[(0, 1), (1, 0)]);
511        let cycles = graph.find_cycles();
512        assert_eq!(cycles.len(), 1);
513        assert_eq!(cycles[0].len(), 2);
514    }
515
516    #[test]
517    fn find_cycles_three_node_cycle() {
518        let graph = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
519        let cycles = graph.find_cycles();
520        assert_eq!(cycles.len(), 1);
521        assert_eq!(cycles[0].len(), 3);
522    }
523
524    #[test]
525    fn find_cycles_self_import_ignored() {
526        let graph = build_cycle_graph(1, &[(0, 0)]);
527        let cycles = graph.find_cycles();
528        assert!(
529            cycles.is_empty(),
530            "self-imports should not be reported as cycles"
531        );
532    }
533
534    #[test]
535    fn find_cycles_multiple_independent_cycles() {
536        let graph = build_cycle_graph(4, &[(0, 1), (1, 0), (2, 3), (3, 2)]);
537        let cycles = graph.find_cycles();
538        assert_eq!(cycles.len(), 2);
539        assert!(cycles.iter().all(|c| c.len() == 2));
540    }
541
542    #[test]
543    fn find_cycles_linear_chain_with_back_edge() {
544        let graph = build_cycle_graph(4, &[(0, 1), (1, 2), (2, 3), (3, 1)]);
545        let cycles = graph.find_cycles();
546        assert_eq!(cycles.len(), 1);
547        assert_eq!(cycles[0].len(), 3);
548        let ids: Vec<u32> = cycles[0].iter().map(|f| f.0).collect();
549        assert!(ids.contains(&1));
550        assert!(ids.contains(&2));
551        assert!(ids.contains(&3));
552        assert!(!ids.contains(&0));
553    }
554
555    #[test]
556    fn find_cycles_overlapping_cycles_enumerated() {
557        let graph = build_cycle_graph(3, &[(0, 1), (1, 0), (1, 2), (2, 1)]);
558        let cycles = graph.find_cycles();
559        assert_eq!(
560            cycles.len(),
561            2,
562            "should find 2 elementary cycles, not 1 SCC"
563        );
564        assert!(
565            cycles.iter().all(|c| c.len() == 2),
566            "both cycles should have length 2"
567        );
568    }
569
570    #[test]
571    fn find_cycles_deterministic_ordering() {
572        let graph1 = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
573        let graph2 = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
574        let cycles1 = graph1.find_cycles();
575        let cycles2 = graph2.find_cycles();
576        assert_eq!(cycles1.len(), cycles2.len());
577        for (c1, c2) in cycles1.iter().zip(cycles2.iter()) {
578            let paths1: Vec<&PathBuf> = c1
579                .iter()
580                .map(|f| &graph1.modules[f.0 as usize].path)
581                .collect();
582            let paths2: Vec<&PathBuf> = c2
583                .iter()
584                .map(|f| &graph2.modules[f.0 as usize].path)
585                .collect();
586            assert_eq!(paths1, paths2);
587        }
588    }
589
590    #[test]
591    fn find_cycles_sorted_by_length() {
592        let graph = build_cycle_graph(5, &[(0, 1), (1, 0), (2, 3), (3, 4), (4, 2)]);
593        let cycles = graph.find_cycles();
594        assert_eq!(cycles.len(), 2);
595        assert!(
596            cycles[0].len() <= cycles[1].len(),
597            "cycles should be sorted by length"
598        );
599    }
600
601    #[test]
602    fn find_cycles_large_cycle() {
603        let edges: Vec<(u32, u32)> = (0..10).map(|i| (i, (i + 1) % 10)).collect();
604        let graph = build_cycle_graph(10, &edges);
605        let cycles = graph.find_cycles();
606        assert_eq!(cycles.len(), 1);
607        assert_eq!(cycles[0].len(), 10);
608    }
609
610    #[test]
611    fn find_cycles_complex_scc_multiple_elementary() {
612        let graph = build_cycle_graph(4, &[(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)]);
613        let cycles = graph.find_cycles();
614        assert!(
615            cycles.len() >= 2,
616            "should find at least 2 elementary cycles, got {}",
617            cycles.len()
618        );
619        assert!(cycles.iter().all(|c| c.len() <= 4));
620    }
621
622    #[test]
623    fn find_cycles_no_duplicate_cycles() {
624        let graph = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
625        let cycles = graph.find_cycles();
626        assert_eq!(cycles.len(), 1, "triangle should produce exactly 1 cycle");
627        assert_eq!(cycles[0].len(), 3);
628    }
629
630    /// Build lightweight `ModuleNode` stubs and successor data for unit tests.
631    ///
632    /// `edges_spec` is a list of (source, target) pairs (0-indexed).
633    /// Returns (modules, all_succs, succ_ranges) suitable for constructing a `SuccessorMap`.
634    #[expect(
635        clippy::cast_possible_truncation,
636        reason = "test file counts are trivially small"
637    )]
638    fn build_test_succs(
639        file_count: usize,
640        edges_spec: &[(usize, usize)],
641    ) -> (Vec<ModuleNode>, Vec<usize>, Vec<Range<usize>>) {
642        let modules: Vec<ModuleNode> = (0..file_count)
643            .map(|i| {
644                let mut node = ModuleNode {
645                    file_id: FileId(i as u32),
646                    path: PathBuf::from(format!("/project/file{i}.ts")),
647                    edge_range: 0..0,
648                    exports: vec![],
649                    re_exports: vec![],
650                    flags: ModuleNode::flags_from(i == 0, true, false),
651                };
652                node.set_reachable(true);
653                node
654            })
655            .collect();
656
657        let mut all_succs: Vec<usize> = Vec::new();
658        let mut succ_ranges: Vec<Range<usize>> = Vec::with_capacity(file_count);
659        for src in 0..file_count {
660            let start = all_succs.len();
661            let mut seen = FxHashSet::default();
662            for &(s, t) in edges_spec {
663                if s == src && t < file_count && seen.insert(t) {
664                    all_succs.push(t);
665                }
666            }
667            let end = all_succs.len();
668            succ_ranges.push(start..end);
669        }
670
671        (modules, all_succs, succ_ranges)
672    }
673
674    #[test]
675    fn canonical_cycle_empty() {
676        let modules: Vec<ModuleNode> = vec![];
677        assert!(canonical_cycle(&[], &modules).is_empty());
678    }
679
680    #[test]
681    fn canonical_cycle_rotates_to_smallest_path() {
682        let (modules, _, _) = build_test_succs(3, &[]);
683        let result = canonical_cycle(&[2, 0, 1], &modules);
684        assert_eq!(result, vec![0, 1, 2]);
685    }
686
687    #[test]
688    fn canonical_cycle_already_canonical() {
689        let (modules, _, _) = build_test_succs(3, &[]);
690        let result = canonical_cycle(&[0, 1, 2], &modules);
691        assert_eq!(result, vec![0, 1, 2]);
692    }
693
694    #[test]
695    fn canonical_cycle_single_node() {
696        let (modules, _, _) = build_test_succs(1, &[]);
697        let result = canonical_cycle(&[0], &modules);
698        assert_eq!(result, vec![0]);
699    }
700
701    #[test]
702    fn try_record_cycle_inserts_new_cycle() {
703        let (modules, _, _) = build_test_succs(3, &[]);
704        let mut seen = FxHashSet::default();
705        let mut cycles = Vec::new();
706
707        try_record_cycle(&[0, 1, 2], &modules, &mut seen, &mut cycles);
708        assert_eq!(cycles.len(), 1);
709        assert_eq!(cycles[0], vec![0, 1, 2]);
710    }
711
712    #[test]
713    fn try_record_cycle_deduplicates_rotated_cycle() {
714        let (modules, _, _) = build_test_succs(3, &[]);
715        let mut seen = FxHashSet::default();
716        let mut cycles = Vec::new();
717
718        try_record_cycle(&[0, 1, 2], &modules, &mut seen, &mut cycles);
719        try_record_cycle(&[1, 2, 0], &modules, &mut seen, &mut cycles);
720        try_record_cycle(&[2, 0, 1], &modules, &mut seen, &mut cycles);
721
722        assert_eq!(
723            cycles.len(),
724            1,
725            "rotations of the same cycle should be deduped"
726        );
727    }
728
729    #[test]
730    fn try_record_cycle_single_node_self_loop() {
731        let (modules, _, _) = build_test_succs(1, &[]);
732        let mut seen = FxHashSet::default();
733        let mut cycles = Vec::new();
734
735        try_record_cycle(&[0], &modules, &mut seen, &mut cycles);
736        assert_eq!(cycles.len(), 1);
737        assert_eq!(cycles[0], vec![0]);
738    }
739
740    #[test]
741    fn try_record_cycle_distinct_cycles_both_recorded() {
742        let (modules, _, _) = build_test_succs(4, &[]);
743        let mut seen = FxHashSet::default();
744        let mut cycles = Vec::new();
745
746        try_record_cycle(&[0, 1], &modules, &mut seen, &mut cycles);
747        try_record_cycle(&[2, 3], &modules, &mut seen, &mut cycles);
748
749        assert_eq!(cycles.len(), 2);
750    }
751
752    #[test]
753    fn successor_map_empty_graph() {
754        let (modules, all_succs, succ_ranges) = build_test_succs(0, &[]);
755        let succs = SuccessorMap {
756            all_succs: &all_succs,
757            succ_ranges: &succ_ranges,
758            modules: &modules,
759        };
760        assert!(succs.all_succs.is_empty());
761        assert!(succs.succ_ranges.is_empty());
762    }
763
764    #[test]
765    fn successor_map_single_node_self_edge() {
766        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[(0, 0)]);
767        let succs = SuccessorMap {
768            all_succs: &all_succs,
769            succ_ranges: &succ_ranges,
770            modules: &modules,
771        };
772        assert_eq!(succs.all_succs.len(), 1);
773        assert_eq!(succs.all_succs[0], 0);
774        assert_eq!(succs.succ_ranges[0], 0..1);
775    }
776
777    #[test]
778    fn successor_map_deduplicates_edges() {
779        let (modules, all_succs, succ_ranges) = build_test_succs(2, &[(0, 1), (0, 1)]);
780        let succs = SuccessorMap {
781            all_succs: &all_succs,
782            succ_ranges: &succ_ranges,
783            modules: &modules,
784        };
785        let range = &succs.succ_ranges[0];
786        assert_eq!(
787            range.end - range.start,
788            1,
789            "duplicate edges should be deduped"
790        );
791    }
792
793    #[test]
794    fn successor_map_multiple_successors() {
795        let (modules, all_succs, succ_ranges) = build_test_succs(4, &[(0, 1), (0, 2), (0, 3)]);
796        let succs = SuccessorMap {
797            all_succs: &all_succs,
798            succ_ranges: &succ_ranges,
799            modules: &modules,
800        };
801        let range = &succs.succ_ranges[0];
802        assert_eq!(range.end - range.start, 3);
803        for i in 1..4 {
804            let r = &succs.succ_ranges[i];
805            assert_eq!(r.end - r.start, 0);
806        }
807    }
808
809    #[test]
810    fn dfs_find_cycles_from_isolated_node() {
811        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[]);
812        let succs = SuccessorMap {
813            all_succs: &all_succs,
814            succ_ranges: &succ_ranges,
815            modules: &modules,
816        };
817        let scc_set: FxHashSet<usize> = std::iter::once(0).collect();
818        let mut seen = FxHashSet::default();
819        let mut cycles = Vec::new();
820
821        dfs_find_cycles_from_for_test(DfsCycleInput {
822            start: 0,
823            depth_limit: 2,
824            scc_set: &scc_set,
825            succs: &succs,
826            max_cycles: 10,
827            seen: &mut seen,
828            cycles: &mut cycles,
829        });
830        assert!(cycles.is_empty(), "isolated node should have no cycles");
831    }
832
833    #[test]
834    fn dfs_find_cycles_from_simple_two_cycle() {
835        let (modules, all_succs, succ_ranges) = build_test_succs(2, &[(0, 1), (1, 0)]);
836        let succs = SuccessorMap {
837            all_succs: &all_succs,
838            succ_ranges: &succ_ranges,
839            modules: &modules,
840        };
841        let scc_set: FxHashSet<usize> = [0, 1].into_iter().collect();
842        let mut seen = FxHashSet::default();
843        let mut cycles = Vec::new();
844
845        dfs_find_cycles_from_for_test(DfsCycleInput {
846            start: 0,
847            depth_limit: 2,
848            scc_set: &scc_set,
849            succs: &succs,
850            max_cycles: 10,
851            seen: &mut seen,
852            cycles: &mut cycles,
853        });
854        assert_eq!(cycles.len(), 1);
855        assert_eq!(cycles[0].len(), 2);
856    }
857
858    #[test]
859    fn dfs_find_cycles_from_diamond_graph() {
860        let (modules, all_succs, succ_ranges) =
861            build_test_succs(4, &[(0, 1), (0, 2), (1, 3), (2, 3), (3, 0)]);
862        let succs = SuccessorMap {
863            all_succs: &all_succs,
864            succ_ranges: &succ_ranges,
865            modules: &modules,
866        };
867        let scc_set: FxHashSet<usize> = [0, 1, 2, 3].into_iter().collect();
868        let mut seen = FxHashSet::default();
869        let mut cycles = Vec::new();
870
871        dfs_find_cycles_from_for_test(DfsCycleInput {
872            start: 0,
873            depth_limit: 3,
874            scc_set: &scc_set,
875            succs: &succs,
876            max_cycles: 10,
877            seen: &mut seen,
878            cycles: &mut cycles,
879        });
880        assert_eq!(cycles.len(), 2, "diamond should have two 3-node cycles");
881        assert!(cycles.iter().all(|c| c.len() == 3));
882    }
883
884    #[test]
885    fn dfs_find_cycles_from_depth_limit_prevents_longer_cycles() {
886        let (modules, all_succs, succ_ranges) =
887            build_test_succs(4, &[(0, 1), (1, 2), (2, 3), (3, 0)]);
888        let succs = SuccessorMap {
889            all_succs: &all_succs,
890            succ_ranges: &succ_ranges,
891            modules: &modules,
892        };
893        let scc_set: FxHashSet<usize> = [0, 1, 2, 3].into_iter().collect();
894        let mut seen = FxHashSet::default();
895        let mut cycles = Vec::new();
896
897        dfs_find_cycles_from_for_test(DfsCycleInput {
898            start: 0,
899            depth_limit: 3,
900            scc_set: &scc_set,
901            succs: &succs,
902            max_cycles: 10,
903            seen: &mut seen,
904            cycles: &mut cycles,
905        });
906        assert!(
907            cycles.is_empty(),
908            "depth_limit=3 should prevent finding a 4-node cycle"
909        );
910    }
911
912    #[test]
913    fn dfs_find_cycles_from_depth_limit_exact_match() {
914        let (modules, all_succs, succ_ranges) =
915            build_test_succs(4, &[(0, 1), (1, 2), (2, 3), (3, 0)]);
916        let succs = SuccessorMap {
917            all_succs: &all_succs,
918            succ_ranges: &succ_ranges,
919            modules: &modules,
920        };
921        let scc_set: FxHashSet<usize> = [0, 1, 2, 3].into_iter().collect();
922        let mut seen = FxHashSet::default();
923        let mut cycles = Vec::new();
924
925        dfs_find_cycles_from_for_test(DfsCycleInput {
926            start: 0,
927            depth_limit: 4,
928            scc_set: &scc_set,
929            succs: &succs,
930            max_cycles: 10,
931            seen: &mut seen,
932            cycles: &mut cycles,
933        });
934        assert_eq!(
935            cycles.len(),
936            1,
937            "depth_limit=4 should find the 4-node cycle"
938        );
939        assert_eq!(cycles[0].len(), 4);
940    }
941
942    #[test]
943    fn dfs_find_cycles_from_respects_max_cycles() {
944        let edges: Vec<(usize, usize)> = (0..4)
945            .flat_map(|i| (0..4).filter(move |&j| i != j).map(move |j| (i, j)))
946            .collect();
947        let (modules, all_succs, succ_ranges) = build_test_succs(4, &edges);
948        let succs = SuccessorMap {
949            all_succs: &all_succs,
950            succ_ranges: &succ_ranges,
951            modules: &modules,
952        };
953        let scc_set: FxHashSet<usize> = (0..4).collect();
954        let mut seen = FxHashSet::default();
955        let mut cycles = Vec::new();
956
957        dfs_find_cycles_from_for_test(DfsCycleInput {
958            start: 0,
959            depth_limit: 2,
960            scc_set: &scc_set,
961            succs: &succs,
962            max_cycles: 2,
963            seen: &mut seen,
964            cycles: &mut cycles,
965        });
966        assert!(
967            cycles.len() <= 2,
968            "should respect max_cycles limit, got {}",
969            cycles.len()
970        );
971    }
972
973    #[test]
974    fn dfs_find_cycles_from_ignores_nodes_outside_scc() {
975        let (modules, all_succs, succ_ranges) = build_test_succs(3, &[(0, 1), (1, 2), (2, 0)]);
976        let succs = SuccessorMap {
977            all_succs: &all_succs,
978            succ_ranges: &succ_ranges,
979            modules: &modules,
980        };
981        let scc_set: FxHashSet<usize> = [0, 1].into_iter().collect();
982        let mut seen = FxHashSet::default();
983        let mut cycles = Vec::new();
984
985        for depth in 2..=3 {
986            dfs_find_cycles_from_for_test(DfsCycleInput {
987                start: 0,
988                depth_limit: depth,
989                scc_set: &scc_set,
990                succs: &succs,
991                max_cycles: 10,
992                seen: &mut seen,
993                cycles: &mut cycles,
994            });
995        }
996        assert!(
997            cycles.is_empty(),
998            "should not find cycles through nodes outside the SCC set"
999        );
1000    }
1001
1002    #[test]
1003    fn enumerate_elementary_cycles_empty_scc() {
1004        let (modules, all_succs, succ_ranges) = build_test_succs(0, &[]);
1005        let succs = SuccessorMap {
1006            all_succs: &all_succs,
1007            succ_ranges: &succ_ranges,
1008            modules: &modules,
1009        };
1010        let cycles = enumerate_elementary_cycles(&[], &succs, 10);
1011        assert!(cycles.is_empty());
1012    }
1013
1014    #[test]
1015    fn enumerate_elementary_cycles_max_cycles_limit() {
1016        let edges: Vec<(usize, usize)> = (0..4)
1017            .flat_map(|i| (0..4).filter(move |&j| i != j).map(move |j| (i, j)))
1018            .collect();
1019        let (modules, all_succs, succ_ranges) = build_test_succs(4, &edges);
1020        let succs = SuccessorMap {
1021            all_succs: &all_succs,
1022            succ_ranges: &succ_ranges,
1023            modules: &modules,
1024        };
1025        let scc_nodes: Vec<usize> = (0..4).collect();
1026
1027        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 3);
1028        assert!(
1029            cycles.len() <= 3,
1030            "should respect max_cycles=3 limit, got {}",
1031            cycles.len()
1032        );
1033    }
1034
1035    #[test]
1036    fn enumerate_elementary_cycles_finds_all_in_triangle() {
1037        let (modules, all_succs, succ_ranges) = build_test_succs(3, &[(0, 1), (1, 2), (2, 0)]);
1038        let succs = SuccessorMap {
1039            all_succs: &all_succs,
1040            succ_ranges: &succ_ranges,
1041            modules: &modules,
1042        };
1043        let scc_nodes: Vec<usize> = vec![0, 1, 2];
1044
1045        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1046        assert_eq!(cycles.len(), 1);
1047        assert_eq!(cycles[0].len(), 3);
1048    }
1049
1050    #[test]
1051    fn enumerate_elementary_cycles_iterative_deepening_order() {
1052        let (modules, all_succs, succ_ranges) =
1053            build_test_succs(3, &[(0, 1), (1, 0), (1, 2), (2, 0)]);
1054        let succs = SuccessorMap {
1055            all_succs: &all_succs,
1056            succ_ranges: &succ_ranges,
1057            modules: &modules,
1058        };
1059        let scc_nodes: Vec<usize> = vec![0, 1, 2];
1060
1061        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1062        assert!(cycles.len() >= 2, "should find at least 2 cycles");
1063        assert!(
1064            cycles[0].len() <= cycles[cycles.len() - 1].len(),
1065            "shorter cycles should be found before longer ones"
1066        );
1067    }
1068
1069    #[test]
1070    fn find_cycles_max_cycles_per_scc_respected() {
1071        let edges: Vec<(u32, u32)> = (0..5)
1072            .flat_map(|i| (0..5).filter(move |&j| i != j).map(move |j| (i, j)))
1073            .collect();
1074        let graph = build_cycle_graph(5, &edges);
1075        let cycles = graph.find_cycles();
1076        assert!(
1077            cycles.len() <= 20,
1078            "should cap at MAX_CYCLES_PER_SCC, got {}",
1079            cycles.len()
1080        );
1081        assert!(
1082            !cycles.is_empty(),
1083            "dense graph should still find some cycles"
1084        );
1085    }
1086
1087    #[test]
1088    fn find_cycles_graph_with_no_cycles_returns_empty() {
1089        let graph = build_cycle_graph(5, &[(0, 1), (0, 2), (0, 3), (0, 4)]);
1090        assert!(graph.find_cycles().is_empty());
1091    }
1092
1093    #[test]
1094    fn find_cycles_diamond_no_cycle() {
1095        let graph = build_cycle_graph(4, &[(0, 1), (0, 2), (1, 3), (2, 3)]);
1096        assert!(graph.find_cycles().is_empty());
1097    }
1098
1099    #[test]
1100    fn find_cycles_diamond_with_back_edge() {
1101        let graph = build_cycle_graph(4, &[(0, 1), (0, 2), (1, 3), (2, 3), (3, 0)]);
1102        let cycles = graph.find_cycles();
1103        assert!(
1104            cycles.len() >= 2,
1105            "diamond with back-edge should have at least 2 elementary cycles, got {}",
1106            cycles.len()
1107        );
1108        assert_eq!(cycles[0].len(), 3);
1109    }
1110
1111    #[test]
1112    fn canonical_cycle_non_sequential_indices() {
1113        let (modules, _, _) = build_test_succs(5, &[]);
1114        let result = canonical_cycle(&[3, 1, 4], &modules);
1115        assert_eq!(result, vec![1, 4, 3]);
1116    }
1117
1118    #[test]
1119    fn canonical_cycle_different_starting_points_same_result() {
1120        let (modules, _, _) = build_test_succs(4, &[]);
1121        let r1 = canonical_cycle(&[0, 1, 2, 3], &modules);
1122        let r2 = canonical_cycle(&[1, 2, 3, 0], &modules);
1123        let r3 = canonical_cycle(&[2, 3, 0, 1], &modules);
1124        let r4 = canonical_cycle(&[3, 0, 1, 2], &modules);
1125        assert_eq!(r1, r2);
1126        assert_eq!(r2, r3);
1127        assert_eq!(r3, r4);
1128        assert_eq!(r1, vec![0, 1, 2, 3]);
1129    }
1130
1131    #[test]
1132    fn canonical_cycle_two_node_both_rotations() {
1133        let (modules, _, _) = build_test_succs(2, &[]);
1134        assert_eq!(canonical_cycle(&[0, 1], &modules), vec![0, 1]);
1135        assert_eq!(canonical_cycle(&[1, 0], &modules), vec![0, 1]);
1136    }
1137
1138    #[test]
1139    fn dfs_find_cycles_from_self_loop_not_found() {
1140        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[(0, 0)]);
1141        let succs = SuccessorMap {
1142            all_succs: &all_succs,
1143            succ_ranges: &succ_ranges,
1144            modules: &modules,
1145        };
1146        let scc_set: FxHashSet<usize> = std::iter::once(0).collect();
1147        let mut seen = FxHashSet::default();
1148        let mut cycles = Vec::new();
1149
1150        for depth in 1..=3 {
1151            dfs_find_cycles_from_for_test(DfsCycleInput {
1152                start: 0,
1153                depth_limit: depth,
1154                scc_set: &scc_set,
1155                succs: &succs,
1156                max_cycles: 10,
1157                seen: &mut seen,
1158                cycles: &mut cycles,
1159            });
1160        }
1161        assert!(
1162            cycles.is_empty(),
1163            "self-loop should not be detected as a cycle by dfs_find_cycles_from"
1164        );
1165    }
1166
1167    #[test]
1168    fn enumerate_elementary_cycles_self_loop_not_found() {
1169        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[(0, 0)]);
1170        let succs = SuccessorMap {
1171            all_succs: &all_succs,
1172            succ_ranges: &succ_ranges,
1173            modules: &modules,
1174        };
1175        let cycles = enumerate_elementary_cycles(&[0], &succs, 20);
1176        assert!(
1177            cycles.is_empty(),
1178            "self-loop should not produce elementary cycles"
1179        );
1180    }
1181
1182    #[test]
1183    fn find_cycles_two_cycles_sharing_edge() {
1184        let graph = build_cycle_graph(4, &[(0, 1), (1, 2), (2, 0), (1, 3), (3, 0)]);
1185        let cycles = graph.find_cycles();
1186        assert_eq!(
1187            cycles.len(),
1188            2,
1189            "two cycles sharing edge A->B should both be found, got {}",
1190            cycles.len()
1191        );
1192        assert!(
1193            cycles.iter().all(|c| c.len() == 3),
1194            "both cycles should have length 3"
1195        );
1196    }
1197
1198    #[test]
1199    fn enumerate_elementary_cycles_shared_edge() {
1200        let (modules, all_succs, succ_ranges) =
1201            build_test_succs(4, &[(0, 1), (1, 2), (2, 0), (1, 3), (3, 0)]);
1202        let succs = SuccessorMap {
1203            all_succs: &all_succs,
1204            succ_ranges: &succ_ranges,
1205            modules: &modules,
1206        };
1207        let scc_nodes: Vec<usize> = vec![0, 1, 2, 3];
1208        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1209        assert_eq!(
1210            cycles.len(),
1211            2,
1212            "should find exactly 2 elementary cycles sharing edge 0->1, got {}",
1213            cycles.len()
1214        );
1215    }
1216
1217    #[test]
1218    fn enumerate_elementary_cycles_pentagon_with_chords() {
1219        let (modules, all_succs, succ_ranges) =
1220            build_test_succs(5, &[(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2), (0, 3)]);
1221        let succs = SuccessorMap {
1222            all_succs: &all_succs,
1223            succ_ranges: &succ_ranges,
1224            modules: &modules,
1225        };
1226        let scc_nodes: Vec<usize> = vec![0, 1, 2, 3, 4];
1227        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1228
1229        assert!(
1230            cycles.len() >= 3,
1231            "pentagon with chords should have at least 3 elementary cycles, got {}",
1232            cycles.len()
1233        );
1234        let unique: FxHashSet<Vec<usize>> = cycles.iter().cloned().collect();
1235        assert_eq!(
1236            unique.len(),
1237            cycles.len(),
1238            "all enumerated cycles should be unique"
1239        );
1240        assert_eq!(
1241            cycles[0].len(),
1242            3,
1243            "shortest cycle in pentagon with chords should be length 3"
1244        );
1245    }
1246
1247    #[test]
1248    fn find_cycles_large_scc_complete_graph_k6() {
1249        let edges: Vec<(u32, u32)> = (0..6)
1250            .flat_map(|i| (0..6).filter(move |&j| i != j).map(move |j| (i, j)))
1251            .collect();
1252        let graph = build_cycle_graph(6, &edges);
1253        let cycles = graph.find_cycles();
1254
1255        assert!(
1256            cycles.len() <= 20,
1257            "should cap at MAX_CYCLES_PER_SCC (20), got {}",
1258            cycles.len()
1259        );
1260        assert_eq!(
1261            cycles.len(),
1262            20,
1263            "K6 has far more than 20 elementary cycles, so we should hit the cap"
1264        );
1265        assert_eq!(cycles[0].len(), 2, "shortest cycles in K6 should be 2-node");
1266    }
1267
1268    #[test]
1269    fn enumerate_elementary_cycles_respects_depth_cap_of_12() {
1270        let edges: Vec<(usize, usize)> = (0..15).map(|i| (i, (i + 1) % 15)).collect();
1271        let (modules, all_succs, succ_ranges) = build_test_succs(15, &edges);
1272        let succs = SuccessorMap {
1273            all_succs: &all_succs,
1274            succ_ranges: &succ_ranges,
1275            modules: &modules,
1276        };
1277        let scc_nodes: Vec<usize> = (0..15).collect();
1278        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1279
1280        assert!(
1281            cycles.is_empty(),
1282            "a pure 15-node cycle should not be found with depth cap of 12, got {} cycles",
1283            cycles.len()
1284        );
1285    }
1286
1287    #[test]
1288    fn enumerate_elementary_cycles_finds_cycle_at_depth_cap_boundary() {
1289        let edges: Vec<(usize, usize)> = (0..12).map(|i| (i, (i + 1) % 12)).collect();
1290        let (modules, all_succs, succ_ranges) = build_test_succs(12, &edges);
1291        let succs = SuccessorMap {
1292            all_succs: &all_succs,
1293            succ_ranges: &succ_ranges,
1294            modules: &modules,
1295        };
1296        let scc_nodes: Vec<usize> = (0..12).collect();
1297        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1298
1299        assert_eq!(
1300            cycles.len(),
1301            1,
1302            "a pure 12-node cycle should be found at the depth cap boundary"
1303        );
1304        assert_eq!(cycles[0].len(), 12);
1305    }
1306
1307    #[test]
1308    fn enumerate_elementary_cycles_13_node_pure_cycle_not_found() {
1309        let edges: Vec<(usize, usize)> = (0..13).map(|i| (i, (i + 1) % 13)).collect();
1310        let (modules, all_succs, succ_ranges) = build_test_succs(13, &edges);
1311        let succs = SuccessorMap {
1312            all_succs: &all_succs,
1313            succ_ranges: &succ_ranges,
1314            modules: &modules,
1315        };
1316        let scc_nodes: Vec<usize> = (0..13).collect();
1317        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1318
1319        assert!(
1320            cycles.is_empty(),
1321            "13-node pure cycle exceeds depth cap of 12"
1322        );
1323    }
1324
1325    #[test]
1326    fn find_cycles_max_cycles_per_scc_enforced_on_k7() {
1327        let edges: Vec<(u32, u32)> = (0..7)
1328            .flat_map(|i| (0..7).filter(move |&j| i != j).map(move |j| (i, j)))
1329            .collect();
1330        let graph = build_cycle_graph(7, &edges);
1331        let cycles = graph.find_cycles();
1332
1333        assert!(
1334            cycles.len() <= 20,
1335            "K7 should cap at MAX_CYCLES_PER_SCC (20), got {}",
1336            cycles.len()
1337        );
1338        assert_eq!(
1339            cycles.len(),
1340            20,
1341            "K7 has far more than 20 elementary cycles, should hit the cap exactly"
1342        );
1343    }
1344
1345    #[test]
1346    fn find_cycles_two_dense_sccs_each_capped() {
1347        let mut edges: Vec<(u32, u32)> = Vec::new();
1348        for i in 0..4 {
1349            for j in 0..4 {
1350                if i != j {
1351                    edges.push((i, j));
1352                }
1353            }
1354        }
1355        for i in 4..8 {
1356            for j in 4..8 {
1357                if i != j {
1358                    edges.push((i, j));
1359                }
1360            }
1361        }
1362        let graph = build_cycle_graph(8, &edges);
1363        let cycles = graph.find_cycles();
1364
1365        assert!(!cycles.is_empty(), "two dense SCCs should produce cycles");
1366        assert!(
1367            cycles.len() > 2,
1368            "should find multiple cycles across both SCCs, got {}",
1369            cycles.len()
1370        );
1371    }
1372
1373    mod proptests {
1374        use super::*;
1375        use proptest::prelude::*;
1376
1377        proptest! {
1378            /// A DAG (directed acyclic graph) should always have zero cycles.
1379            /// We construct a DAG by only allowing edges from lower to higher node indices.
1380            #[test]
1381            fn dag_has_no_cycles(
1382                file_count in 2..20usize,
1383                edge_pairs in prop::collection::vec((0..19u32, 0..19u32), 0..30),
1384            ) {
1385                let dag_edges: Vec<(u32, u32)> = edge_pairs
1386                    .into_iter()
1387                    .filter(|(a, b)| (*a as usize) < file_count && (*b as usize) < file_count && a < b)
1388                    .collect();
1389
1390                let graph = build_cycle_graph(file_count, &dag_edges);
1391                let cycles = graph.find_cycles();
1392                prop_assert!(
1393                    cycles.is_empty(),
1394                    "DAG should have no cycles, but found {}",
1395                    cycles.len()
1396                );
1397            }
1398
1399            /// Adding mutual edges A->B->A should always detect a cycle.
1400            #[test]
1401            fn mutual_edges_always_detect_cycle(extra_nodes in 0..10usize) {
1402                let file_count = 2 + extra_nodes;
1403                let graph = build_cycle_graph(file_count, &[(0, 1), (1, 0)]);
1404                let cycles = graph.find_cycles();
1405                prop_assert!(
1406                    !cycles.is_empty(),
1407                    "A->B->A should always produce at least one cycle"
1408                );
1409                let has_pair_cycle = cycles.iter().any(|c| {
1410                    c.contains(&FileId(0)) && c.contains(&FileId(1))
1411                });
1412                prop_assert!(has_pair_cycle, "Should find a cycle containing nodes 0 and 1");
1413            }
1414
1415            /// All cycle members should be valid FileId indices.
1416            #[test]
1417            fn cycle_members_are_valid_indices(
1418                file_count in 2..15usize,
1419                edge_pairs in prop::collection::vec((0..14u32, 0..14u32), 1..20),
1420            ) {
1421                let edges: Vec<(u32, u32)> = edge_pairs
1422                    .into_iter()
1423                    .filter(|(a, b)| (*a as usize) < file_count && (*b as usize) < file_count && a != b)
1424                    .collect();
1425
1426                let graph = build_cycle_graph(file_count, &edges);
1427                let cycles = graph.find_cycles();
1428                for cycle in &cycles {
1429                    prop_assert!(cycle.len() >= 2, "Cycles must have at least 2 nodes");
1430                    for file_id in cycle {
1431                        prop_assert!(
1432                            (file_id.0 as usize) < file_count,
1433                            "FileId {} exceeds file count {}",
1434                            file_id.0, file_count
1435                        );
1436                    }
1437                }
1438            }
1439
1440            /// Cycles should be sorted by length (shortest first).
1441            #[test]
1442            fn cycles_sorted_by_length(
1443                file_count in 3..12usize,
1444                edge_pairs in prop::collection::vec((0..11u32, 0..11u32), 2..25),
1445            ) {
1446                let edges: Vec<(u32, u32)> = edge_pairs
1447                    .into_iter()
1448                    .filter(|(a, b)| (*a as usize) < file_count && (*b as usize) < file_count && a != b)
1449                    .collect();
1450
1451                let graph = build_cycle_graph(file_count, &edges);
1452                let cycles = graph.find_cycles();
1453                for window in cycles.windows(2) {
1454                    prop_assert!(
1455                        window[0].len() <= window[1].len(),
1456                        "Cycles should be sorted by length: {} > {}",
1457                        window[0].len(), window[1].len()
1458                    );
1459                }
1460            }
1461        }
1462    }
1463
1464    /// Build a cycle graph where specific edges are type-only.
1465    fn build_cycle_graph_with_type_only(
1466        file_count: usize,
1467        edges_spec: &[(u32, u32, bool)], // (source, target, is_type_only)
1468    ) -> ModuleGraph {
1469        let files: Vec<DiscoveredFile> = (0..file_count)
1470            .map(|i| DiscoveredFile {
1471                id: FileId(i as u32),
1472                path: PathBuf::from(format!("/project/file{i}.ts")),
1473                size_bytes: 100,
1474            })
1475            .collect();
1476
1477        let resolved_modules: Vec<ResolvedModule> = (0..file_count)
1478            .map(|i| {
1479                let imports: Vec<ResolvedImport> = edges_spec
1480                    .iter()
1481                    .filter(|(src, _, _)| *src == i as u32)
1482                    .map(|(_, tgt, type_only)| ResolvedImport {
1483                        info: ImportInfo {
1484                            source: format!("./file{tgt}"),
1485                            imported_name: ImportedName::Named("x".to_string()),
1486                            local_name: "x".to_string(),
1487                            is_type_only: *type_only,
1488                            from_style: false,
1489                            span: oxc_span::Span::new(0, 10),
1490                            source_span: oxc_span::Span::default(),
1491                        },
1492                        target: ResolveResult::InternalModule(FileId(*tgt)),
1493                    })
1494                    .collect();
1495
1496                ResolvedModule {
1497                    file_id: FileId(i as u32),
1498                    path: PathBuf::from(format!("/project/file{i}.ts")),
1499                    exports: vec![fallow_types::extract::ExportInfo {
1500                        name: ExportName::Named("x".to_string()),
1501                        local_name: Some("x".to_string()),
1502                        is_type_only: false,
1503                        visibility: VisibilityTag::None,
1504                        expected_unused_reason: None,
1505                        span: oxc_span::Span::new(0, 20),
1506                        members: vec![],
1507                        is_side_effect_used: false,
1508                        super_class: None,
1509                    }],
1510                    re_exports: vec![],
1511                    resolved_imports: imports,
1512                    resolved_dynamic_imports: vec![],
1513                    resolved_dynamic_patterns: vec![],
1514                    member_accesses: vec![],
1515                    semantic_facts: Box::default(),
1516                    whole_object_uses: Box::default(),
1517                    has_cjs_exports: false,
1518                    has_angular_component_template_url: false,
1519                    unused_import_bindings: FxHashSet::default(),
1520                    type_referenced_import_bindings: vec![],
1521                    value_referenced_import_bindings: vec![],
1522                    namespace_object_aliases: vec![],
1523                    exported_factory_returns: Box::default(),
1524                    exported_factory_return_object_shapes: Box::default(),
1525                    type_member_types: Box::default(),
1526                }
1527            })
1528            .collect();
1529
1530        let entry_points = vec![EntryPoint {
1531            path: PathBuf::from("/project/file0.ts"),
1532            source: EntryPointSource::PackageJsonMain,
1533        }];
1534
1535        ModuleGraph::build(&resolved_modules, &entry_points, &files)
1536    }
1537
1538    #[test]
1539    fn type_only_bidirectional_import_not_a_cycle() {
1540        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, true), (1, 0, true)]);
1541        let cycles = graph.find_cycles();
1542        assert!(
1543            cycles.is_empty(),
1544            "type-only bidirectional imports should not be reported as cycles"
1545        );
1546    }
1547
1548    #[test]
1549    fn mixed_type_and_value_import_not_a_cycle() {
1550        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, false), (1, 0, true)]);
1551        let cycles = graph.find_cycles();
1552        assert!(
1553            cycles.is_empty(),
1554            "A->B (value) + B->A (type-only) is not a runtime cycle"
1555        );
1556    }
1557
1558    #[test]
1559    fn both_value_imports_with_one_type_still_a_cycle() {
1560        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, false), (1, 0, false)]);
1561        let cycles = graph.find_cycles();
1562        assert!(
1563            !cycles.is_empty(),
1564            "bidirectional value imports should be reported as a cycle"
1565        );
1566    }
1567
1568    #[test]
1569    fn all_value_imports_still_a_cycle() {
1570        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, false), (1, 0, false)]);
1571        let cycles = graph.find_cycles();
1572        assert_eq!(cycles.len(), 1);
1573    }
1574
1575    #[test]
1576    fn three_node_type_only_cycle_not_reported() {
1577        let graph =
1578            build_cycle_graph_with_type_only(3, &[(0, 1, true), (1, 2, true), (2, 0, true)]);
1579        let cycles = graph.find_cycles();
1580        assert!(
1581            cycles.is_empty(),
1582            "three-node type-only cycle should not be reported"
1583        );
1584    }
1585
1586    #[test]
1587    fn three_node_cycle_one_value_edge_still_reported() {
1588        let graph =
1589            build_cycle_graph_with_type_only(3, &[(0, 1, false), (1, 2, true), (2, 0, true)]);
1590        let cycles = graph.find_cycles();
1591        assert!(
1592            cycles.is_empty(),
1593            "cycle broken by type-only edge in the middle should not be reported"
1594        );
1595    }
1596}