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                    type_member_types: Box::default(),
479                }
480            })
481            .collect();
482
483        let entry_points = vec![EntryPoint {
484            path: PathBuf::from("/project/file0.ts"),
485            source: EntryPointSource::PackageJsonMain,
486        }];
487
488        ModuleGraph::build(&resolved_modules, &entry_points, &files)
489    }
490
491    fn dfs_find_cycles_from_for_test(mut input: DfsCycleInput<'_>) {
492        dfs_find_cycles_from(&mut input);
493    }
494
495    #[test]
496    fn find_cycles_empty_graph() {
497        let graph = ModuleGraph::build(&[], &[], &[]);
498        assert!(graph.find_cycles().is_empty());
499    }
500
501    #[test]
502    fn find_cycles_no_cycles() {
503        let graph = build_cycle_graph(3, &[(0, 1), (1, 2)]);
504        assert!(graph.find_cycles().is_empty());
505    }
506
507    #[test]
508    fn find_cycles_simple_two_node_cycle() {
509        let graph = build_cycle_graph(2, &[(0, 1), (1, 0)]);
510        let cycles = graph.find_cycles();
511        assert_eq!(cycles.len(), 1);
512        assert_eq!(cycles[0].len(), 2);
513    }
514
515    #[test]
516    fn find_cycles_three_node_cycle() {
517        let graph = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
518        let cycles = graph.find_cycles();
519        assert_eq!(cycles.len(), 1);
520        assert_eq!(cycles[0].len(), 3);
521    }
522
523    #[test]
524    fn find_cycles_self_import_ignored() {
525        let graph = build_cycle_graph(1, &[(0, 0)]);
526        let cycles = graph.find_cycles();
527        assert!(
528            cycles.is_empty(),
529            "self-imports should not be reported as cycles"
530        );
531    }
532
533    #[test]
534    fn find_cycles_multiple_independent_cycles() {
535        let graph = build_cycle_graph(4, &[(0, 1), (1, 0), (2, 3), (3, 2)]);
536        let cycles = graph.find_cycles();
537        assert_eq!(cycles.len(), 2);
538        assert!(cycles.iter().all(|c| c.len() == 2));
539    }
540
541    #[test]
542    fn find_cycles_linear_chain_with_back_edge() {
543        let graph = build_cycle_graph(4, &[(0, 1), (1, 2), (2, 3), (3, 1)]);
544        let cycles = graph.find_cycles();
545        assert_eq!(cycles.len(), 1);
546        assert_eq!(cycles[0].len(), 3);
547        let ids: Vec<u32> = cycles[0].iter().map(|f| f.0).collect();
548        assert!(ids.contains(&1));
549        assert!(ids.contains(&2));
550        assert!(ids.contains(&3));
551        assert!(!ids.contains(&0));
552    }
553
554    #[test]
555    fn find_cycles_overlapping_cycles_enumerated() {
556        let graph = build_cycle_graph(3, &[(0, 1), (1, 0), (1, 2), (2, 1)]);
557        let cycles = graph.find_cycles();
558        assert_eq!(
559            cycles.len(),
560            2,
561            "should find 2 elementary cycles, not 1 SCC"
562        );
563        assert!(
564            cycles.iter().all(|c| c.len() == 2),
565            "both cycles should have length 2"
566        );
567    }
568
569    #[test]
570    fn find_cycles_deterministic_ordering() {
571        let graph1 = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
572        let graph2 = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
573        let cycles1 = graph1.find_cycles();
574        let cycles2 = graph2.find_cycles();
575        assert_eq!(cycles1.len(), cycles2.len());
576        for (c1, c2) in cycles1.iter().zip(cycles2.iter()) {
577            let paths1: Vec<&PathBuf> = c1
578                .iter()
579                .map(|f| &graph1.modules[f.0 as usize].path)
580                .collect();
581            let paths2: Vec<&PathBuf> = c2
582                .iter()
583                .map(|f| &graph2.modules[f.0 as usize].path)
584                .collect();
585            assert_eq!(paths1, paths2);
586        }
587    }
588
589    #[test]
590    fn find_cycles_sorted_by_length() {
591        let graph = build_cycle_graph(5, &[(0, 1), (1, 0), (2, 3), (3, 4), (4, 2)]);
592        let cycles = graph.find_cycles();
593        assert_eq!(cycles.len(), 2);
594        assert!(
595            cycles[0].len() <= cycles[1].len(),
596            "cycles should be sorted by length"
597        );
598    }
599
600    #[test]
601    fn find_cycles_large_cycle() {
602        let edges: Vec<(u32, u32)> = (0..10).map(|i| (i, (i + 1) % 10)).collect();
603        let graph = build_cycle_graph(10, &edges);
604        let cycles = graph.find_cycles();
605        assert_eq!(cycles.len(), 1);
606        assert_eq!(cycles[0].len(), 10);
607    }
608
609    #[test]
610    fn find_cycles_complex_scc_multiple_elementary() {
611        let graph = build_cycle_graph(4, &[(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)]);
612        let cycles = graph.find_cycles();
613        assert!(
614            cycles.len() >= 2,
615            "should find at least 2 elementary cycles, got {}",
616            cycles.len()
617        );
618        assert!(cycles.iter().all(|c| c.len() <= 4));
619    }
620
621    #[test]
622    fn find_cycles_no_duplicate_cycles() {
623        let graph = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
624        let cycles = graph.find_cycles();
625        assert_eq!(cycles.len(), 1, "triangle should produce exactly 1 cycle");
626        assert_eq!(cycles[0].len(), 3);
627    }
628
629    /// Build lightweight `ModuleNode` stubs and successor data for unit tests.
630    ///
631    /// `edges_spec` is a list of (source, target) pairs (0-indexed).
632    /// Returns (modules, all_succs, succ_ranges) suitable for constructing a `SuccessorMap`.
633    #[expect(
634        clippy::cast_possible_truncation,
635        reason = "test file counts are trivially small"
636    )]
637    fn build_test_succs(
638        file_count: usize,
639        edges_spec: &[(usize, usize)],
640    ) -> (Vec<ModuleNode>, Vec<usize>, Vec<Range<usize>>) {
641        let modules: Vec<ModuleNode> = (0..file_count)
642            .map(|i| {
643                let mut node = ModuleNode {
644                    file_id: FileId(i as u32),
645                    path: PathBuf::from(format!("/project/file{i}.ts")),
646                    edge_range: 0..0,
647                    exports: vec![],
648                    re_exports: vec![],
649                    flags: ModuleNode::flags_from(i == 0, true, false),
650                };
651                node.set_reachable(true);
652                node
653            })
654            .collect();
655
656        let mut all_succs: Vec<usize> = Vec::new();
657        let mut succ_ranges: Vec<Range<usize>> = Vec::with_capacity(file_count);
658        for src in 0..file_count {
659            let start = all_succs.len();
660            let mut seen = FxHashSet::default();
661            for &(s, t) in edges_spec {
662                if s == src && t < file_count && seen.insert(t) {
663                    all_succs.push(t);
664                }
665            }
666            let end = all_succs.len();
667            succ_ranges.push(start..end);
668        }
669
670        (modules, all_succs, succ_ranges)
671    }
672
673    #[test]
674    fn canonical_cycle_empty() {
675        let modules: Vec<ModuleNode> = vec![];
676        assert!(canonical_cycle(&[], &modules).is_empty());
677    }
678
679    #[test]
680    fn canonical_cycle_rotates_to_smallest_path() {
681        let (modules, _, _) = build_test_succs(3, &[]);
682        let result = canonical_cycle(&[2, 0, 1], &modules);
683        assert_eq!(result, vec![0, 1, 2]);
684    }
685
686    #[test]
687    fn canonical_cycle_already_canonical() {
688        let (modules, _, _) = build_test_succs(3, &[]);
689        let result = canonical_cycle(&[0, 1, 2], &modules);
690        assert_eq!(result, vec![0, 1, 2]);
691    }
692
693    #[test]
694    fn canonical_cycle_single_node() {
695        let (modules, _, _) = build_test_succs(1, &[]);
696        let result = canonical_cycle(&[0], &modules);
697        assert_eq!(result, vec![0]);
698    }
699
700    #[test]
701    fn try_record_cycle_inserts_new_cycle() {
702        let (modules, _, _) = build_test_succs(3, &[]);
703        let mut seen = FxHashSet::default();
704        let mut cycles = Vec::new();
705
706        try_record_cycle(&[0, 1, 2], &modules, &mut seen, &mut cycles);
707        assert_eq!(cycles.len(), 1);
708        assert_eq!(cycles[0], vec![0, 1, 2]);
709    }
710
711    #[test]
712    fn try_record_cycle_deduplicates_rotated_cycle() {
713        let (modules, _, _) = build_test_succs(3, &[]);
714        let mut seen = FxHashSet::default();
715        let mut cycles = Vec::new();
716
717        try_record_cycle(&[0, 1, 2], &modules, &mut seen, &mut cycles);
718        try_record_cycle(&[1, 2, 0], &modules, &mut seen, &mut cycles);
719        try_record_cycle(&[2, 0, 1], &modules, &mut seen, &mut cycles);
720
721        assert_eq!(
722            cycles.len(),
723            1,
724            "rotations of the same cycle should be deduped"
725        );
726    }
727
728    #[test]
729    fn try_record_cycle_single_node_self_loop() {
730        let (modules, _, _) = build_test_succs(1, &[]);
731        let mut seen = FxHashSet::default();
732        let mut cycles = Vec::new();
733
734        try_record_cycle(&[0], &modules, &mut seen, &mut cycles);
735        assert_eq!(cycles.len(), 1);
736        assert_eq!(cycles[0], vec![0]);
737    }
738
739    #[test]
740    fn try_record_cycle_distinct_cycles_both_recorded() {
741        let (modules, _, _) = build_test_succs(4, &[]);
742        let mut seen = FxHashSet::default();
743        let mut cycles = Vec::new();
744
745        try_record_cycle(&[0, 1], &modules, &mut seen, &mut cycles);
746        try_record_cycle(&[2, 3], &modules, &mut seen, &mut cycles);
747
748        assert_eq!(cycles.len(), 2);
749    }
750
751    #[test]
752    fn successor_map_empty_graph() {
753        let (modules, all_succs, succ_ranges) = build_test_succs(0, &[]);
754        let succs = SuccessorMap {
755            all_succs: &all_succs,
756            succ_ranges: &succ_ranges,
757            modules: &modules,
758        };
759        assert!(succs.all_succs.is_empty());
760        assert!(succs.succ_ranges.is_empty());
761    }
762
763    #[test]
764    fn successor_map_single_node_self_edge() {
765        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[(0, 0)]);
766        let succs = SuccessorMap {
767            all_succs: &all_succs,
768            succ_ranges: &succ_ranges,
769            modules: &modules,
770        };
771        assert_eq!(succs.all_succs.len(), 1);
772        assert_eq!(succs.all_succs[0], 0);
773        assert_eq!(succs.succ_ranges[0], 0..1);
774    }
775
776    #[test]
777    fn successor_map_deduplicates_edges() {
778        let (modules, all_succs, succ_ranges) = build_test_succs(2, &[(0, 1), (0, 1)]);
779        let succs = SuccessorMap {
780            all_succs: &all_succs,
781            succ_ranges: &succ_ranges,
782            modules: &modules,
783        };
784        let range = &succs.succ_ranges[0];
785        assert_eq!(
786            range.end - range.start,
787            1,
788            "duplicate edges should be deduped"
789        );
790    }
791
792    #[test]
793    fn successor_map_multiple_successors() {
794        let (modules, all_succs, succ_ranges) = build_test_succs(4, &[(0, 1), (0, 2), (0, 3)]);
795        let succs = SuccessorMap {
796            all_succs: &all_succs,
797            succ_ranges: &succ_ranges,
798            modules: &modules,
799        };
800        let range = &succs.succ_ranges[0];
801        assert_eq!(range.end - range.start, 3);
802        for i in 1..4 {
803            let r = &succs.succ_ranges[i];
804            assert_eq!(r.end - r.start, 0);
805        }
806    }
807
808    #[test]
809    fn dfs_find_cycles_from_isolated_node() {
810        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[]);
811        let succs = SuccessorMap {
812            all_succs: &all_succs,
813            succ_ranges: &succ_ranges,
814            modules: &modules,
815        };
816        let scc_set: FxHashSet<usize> = std::iter::once(0).collect();
817        let mut seen = FxHashSet::default();
818        let mut cycles = Vec::new();
819
820        dfs_find_cycles_from_for_test(DfsCycleInput {
821            start: 0,
822            depth_limit: 2,
823            scc_set: &scc_set,
824            succs: &succs,
825            max_cycles: 10,
826            seen: &mut seen,
827            cycles: &mut cycles,
828        });
829        assert!(cycles.is_empty(), "isolated node should have no cycles");
830    }
831
832    #[test]
833    fn dfs_find_cycles_from_simple_two_cycle() {
834        let (modules, all_succs, succ_ranges) = build_test_succs(2, &[(0, 1), (1, 0)]);
835        let succs = SuccessorMap {
836            all_succs: &all_succs,
837            succ_ranges: &succ_ranges,
838            modules: &modules,
839        };
840        let scc_set: FxHashSet<usize> = [0, 1].into_iter().collect();
841        let mut seen = FxHashSet::default();
842        let mut cycles = Vec::new();
843
844        dfs_find_cycles_from_for_test(DfsCycleInput {
845            start: 0,
846            depth_limit: 2,
847            scc_set: &scc_set,
848            succs: &succs,
849            max_cycles: 10,
850            seen: &mut seen,
851            cycles: &mut cycles,
852        });
853        assert_eq!(cycles.len(), 1);
854        assert_eq!(cycles[0].len(), 2);
855    }
856
857    #[test]
858    fn dfs_find_cycles_from_diamond_graph() {
859        let (modules, all_succs, succ_ranges) =
860            build_test_succs(4, &[(0, 1), (0, 2), (1, 3), (2, 3), (3, 0)]);
861        let succs = SuccessorMap {
862            all_succs: &all_succs,
863            succ_ranges: &succ_ranges,
864            modules: &modules,
865        };
866        let scc_set: FxHashSet<usize> = [0, 1, 2, 3].into_iter().collect();
867        let mut seen = FxHashSet::default();
868        let mut cycles = Vec::new();
869
870        dfs_find_cycles_from_for_test(DfsCycleInput {
871            start: 0,
872            depth_limit: 3,
873            scc_set: &scc_set,
874            succs: &succs,
875            max_cycles: 10,
876            seen: &mut seen,
877            cycles: &mut cycles,
878        });
879        assert_eq!(cycles.len(), 2, "diamond should have two 3-node cycles");
880        assert!(cycles.iter().all(|c| c.len() == 3));
881    }
882
883    #[test]
884    fn dfs_find_cycles_from_depth_limit_prevents_longer_cycles() {
885        let (modules, all_succs, succ_ranges) =
886            build_test_succs(4, &[(0, 1), (1, 2), (2, 3), (3, 0)]);
887        let succs = SuccessorMap {
888            all_succs: &all_succs,
889            succ_ranges: &succ_ranges,
890            modules: &modules,
891        };
892        let scc_set: FxHashSet<usize> = [0, 1, 2, 3].into_iter().collect();
893        let mut seen = FxHashSet::default();
894        let mut cycles = Vec::new();
895
896        dfs_find_cycles_from_for_test(DfsCycleInput {
897            start: 0,
898            depth_limit: 3,
899            scc_set: &scc_set,
900            succs: &succs,
901            max_cycles: 10,
902            seen: &mut seen,
903            cycles: &mut cycles,
904        });
905        assert!(
906            cycles.is_empty(),
907            "depth_limit=3 should prevent finding a 4-node cycle"
908        );
909    }
910
911    #[test]
912    fn dfs_find_cycles_from_depth_limit_exact_match() {
913        let (modules, all_succs, succ_ranges) =
914            build_test_succs(4, &[(0, 1), (1, 2), (2, 3), (3, 0)]);
915        let succs = SuccessorMap {
916            all_succs: &all_succs,
917            succ_ranges: &succ_ranges,
918            modules: &modules,
919        };
920        let scc_set: FxHashSet<usize> = [0, 1, 2, 3].into_iter().collect();
921        let mut seen = FxHashSet::default();
922        let mut cycles = Vec::new();
923
924        dfs_find_cycles_from_for_test(DfsCycleInput {
925            start: 0,
926            depth_limit: 4,
927            scc_set: &scc_set,
928            succs: &succs,
929            max_cycles: 10,
930            seen: &mut seen,
931            cycles: &mut cycles,
932        });
933        assert_eq!(
934            cycles.len(),
935            1,
936            "depth_limit=4 should find the 4-node cycle"
937        );
938        assert_eq!(cycles[0].len(), 4);
939    }
940
941    #[test]
942    fn dfs_find_cycles_from_respects_max_cycles() {
943        let edges: Vec<(usize, usize)> = (0..4)
944            .flat_map(|i| (0..4).filter(move |&j| i != j).map(move |j| (i, j)))
945            .collect();
946        let (modules, all_succs, succ_ranges) = build_test_succs(4, &edges);
947        let succs = SuccessorMap {
948            all_succs: &all_succs,
949            succ_ranges: &succ_ranges,
950            modules: &modules,
951        };
952        let scc_set: FxHashSet<usize> = (0..4).collect();
953        let mut seen = FxHashSet::default();
954        let mut cycles = Vec::new();
955
956        dfs_find_cycles_from_for_test(DfsCycleInput {
957            start: 0,
958            depth_limit: 2,
959            scc_set: &scc_set,
960            succs: &succs,
961            max_cycles: 2,
962            seen: &mut seen,
963            cycles: &mut cycles,
964        });
965        assert!(
966            cycles.len() <= 2,
967            "should respect max_cycles limit, got {}",
968            cycles.len()
969        );
970    }
971
972    #[test]
973    fn dfs_find_cycles_from_ignores_nodes_outside_scc() {
974        let (modules, all_succs, succ_ranges) = build_test_succs(3, &[(0, 1), (1, 2), (2, 0)]);
975        let succs = SuccessorMap {
976            all_succs: &all_succs,
977            succ_ranges: &succ_ranges,
978            modules: &modules,
979        };
980        let scc_set: FxHashSet<usize> = [0, 1].into_iter().collect();
981        let mut seen = FxHashSet::default();
982        let mut cycles = Vec::new();
983
984        for depth in 2..=3 {
985            dfs_find_cycles_from_for_test(DfsCycleInput {
986                start: 0,
987                depth_limit: depth,
988                scc_set: &scc_set,
989                succs: &succs,
990                max_cycles: 10,
991                seen: &mut seen,
992                cycles: &mut cycles,
993            });
994        }
995        assert!(
996            cycles.is_empty(),
997            "should not find cycles through nodes outside the SCC set"
998        );
999    }
1000
1001    #[test]
1002    fn enumerate_elementary_cycles_empty_scc() {
1003        let (modules, all_succs, succ_ranges) = build_test_succs(0, &[]);
1004        let succs = SuccessorMap {
1005            all_succs: &all_succs,
1006            succ_ranges: &succ_ranges,
1007            modules: &modules,
1008        };
1009        let cycles = enumerate_elementary_cycles(&[], &succs, 10);
1010        assert!(cycles.is_empty());
1011    }
1012
1013    #[test]
1014    fn enumerate_elementary_cycles_max_cycles_limit() {
1015        let edges: Vec<(usize, usize)> = (0..4)
1016            .flat_map(|i| (0..4).filter(move |&j| i != j).map(move |j| (i, j)))
1017            .collect();
1018        let (modules, all_succs, succ_ranges) = build_test_succs(4, &edges);
1019        let succs = SuccessorMap {
1020            all_succs: &all_succs,
1021            succ_ranges: &succ_ranges,
1022            modules: &modules,
1023        };
1024        let scc_nodes: Vec<usize> = (0..4).collect();
1025
1026        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 3);
1027        assert!(
1028            cycles.len() <= 3,
1029            "should respect max_cycles=3 limit, got {}",
1030            cycles.len()
1031        );
1032    }
1033
1034    #[test]
1035    fn enumerate_elementary_cycles_finds_all_in_triangle() {
1036        let (modules, all_succs, succ_ranges) = build_test_succs(3, &[(0, 1), (1, 2), (2, 0)]);
1037        let succs = SuccessorMap {
1038            all_succs: &all_succs,
1039            succ_ranges: &succ_ranges,
1040            modules: &modules,
1041        };
1042        let scc_nodes: Vec<usize> = vec![0, 1, 2];
1043
1044        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1045        assert_eq!(cycles.len(), 1);
1046        assert_eq!(cycles[0].len(), 3);
1047    }
1048
1049    #[test]
1050    fn enumerate_elementary_cycles_iterative_deepening_order() {
1051        let (modules, all_succs, succ_ranges) =
1052            build_test_succs(3, &[(0, 1), (1, 0), (1, 2), (2, 0)]);
1053        let succs = SuccessorMap {
1054            all_succs: &all_succs,
1055            succ_ranges: &succ_ranges,
1056            modules: &modules,
1057        };
1058        let scc_nodes: Vec<usize> = vec![0, 1, 2];
1059
1060        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1061        assert!(cycles.len() >= 2, "should find at least 2 cycles");
1062        assert!(
1063            cycles[0].len() <= cycles[cycles.len() - 1].len(),
1064            "shorter cycles should be found before longer ones"
1065        );
1066    }
1067
1068    #[test]
1069    fn find_cycles_max_cycles_per_scc_respected() {
1070        let edges: Vec<(u32, u32)> = (0..5)
1071            .flat_map(|i| (0..5).filter(move |&j| i != j).map(move |j| (i, j)))
1072            .collect();
1073        let graph = build_cycle_graph(5, &edges);
1074        let cycles = graph.find_cycles();
1075        assert!(
1076            cycles.len() <= 20,
1077            "should cap at MAX_CYCLES_PER_SCC, got {}",
1078            cycles.len()
1079        );
1080        assert!(
1081            !cycles.is_empty(),
1082            "dense graph should still find some cycles"
1083        );
1084    }
1085
1086    #[test]
1087    fn find_cycles_graph_with_no_cycles_returns_empty() {
1088        let graph = build_cycle_graph(5, &[(0, 1), (0, 2), (0, 3), (0, 4)]);
1089        assert!(graph.find_cycles().is_empty());
1090    }
1091
1092    #[test]
1093    fn find_cycles_diamond_no_cycle() {
1094        let graph = build_cycle_graph(4, &[(0, 1), (0, 2), (1, 3), (2, 3)]);
1095        assert!(graph.find_cycles().is_empty());
1096    }
1097
1098    #[test]
1099    fn find_cycles_diamond_with_back_edge() {
1100        let graph = build_cycle_graph(4, &[(0, 1), (0, 2), (1, 3), (2, 3), (3, 0)]);
1101        let cycles = graph.find_cycles();
1102        assert!(
1103            cycles.len() >= 2,
1104            "diamond with back-edge should have at least 2 elementary cycles, got {}",
1105            cycles.len()
1106        );
1107        assert_eq!(cycles[0].len(), 3);
1108    }
1109
1110    #[test]
1111    fn canonical_cycle_non_sequential_indices() {
1112        let (modules, _, _) = build_test_succs(5, &[]);
1113        let result = canonical_cycle(&[3, 1, 4], &modules);
1114        assert_eq!(result, vec![1, 4, 3]);
1115    }
1116
1117    #[test]
1118    fn canonical_cycle_different_starting_points_same_result() {
1119        let (modules, _, _) = build_test_succs(4, &[]);
1120        let r1 = canonical_cycle(&[0, 1, 2, 3], &modules);
1121        let r2 = canonical_cycle(&[1, 2, 3, 0], &modules);
1122        let r3 = canonical_cycle(&[2, 3, 0, 1], &modules);
1123        let r4 = canonical_cycle(&[3, 0, 1, 2], &modules);
1124        assert_eq!(r1, r2);
1125        assert_eq!(r2, r3);
1126        assert_eq!(r3, r4);
1127        assert_eq!(r1, vec![0, 1, 2, 3]);
1128    }
1129
1130    #[test]
1131    fn canonical_cycle_two_node_both_rotations() {
1132        let (modules, _, _) = build_test_succs(2, &[]);
1133        assert_eq!(canonical_cycle(&[0, 1], &modules), vec![0, 1]);
1134        assert_eq!(canonical_cycle(&[1, 0], &modules), vec![0, 1]);
1135    }
1136
1137    #[test]
1138    fn dfs_find_cycles_from_self_loop_not_found() {
1139        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[(0, 0)]);
1140        let succs = SuccessorMap {
1141            all_succs: &all_succs,
1142            succ_ranges: &succ_ranges,
1143            modules: &modules,
1144        };
1145        let scc_set: FxHashSet<usize> = std::iter::once(0).collect();
1146        let mut seen = FxHashSet::default();
1147        let mut cycles = Vec::new();
1148
1149        for depth in 1..=3 {
1150            dfs_find_cycles_from_for_test(DfsCycleInput {
1151                start: 0,
1152                depth_limit: depth,
1153                scc_set: &scc_set,
1154                succs: &succs,
1155                max_cycles: 10,
1156                seen: &mut seen,
1157                cycles: &mut cycles,
1158            });
1159        }
1160        assert!(
1161            cycles.is_empty(),
1162            "self-loop should not be detected as a cycle by dfs_find_cycles_from"
1163        );
1164    }
1165
1166    #[test]
1167    fn enumerate_elementary_cycles_self_loop_not_found() {
1168        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[(0, 0)]);
1169        let succs = SuccessorMap {
1170            all_succs: &all_succs,
1171            succ_ranges: &succ_ranges,
1172            modules: &modules,
1173        };
1174        let cycles = enumerate_elementary_cycles(&[0], &succs, 20);
1175        assert!(
1176            cycles.is_empty(),
1177            "self-loop should not produce elementary cycles"
1178        );
1179    }
1180
1181    #[test]
1182    fn find_cycles_two_cycles_sharing_edge() {
1183        let graph = build_cycle_graph(4, &[(0, 1), (1, 2), (2, 0), (1, 3), (3, 0)]);
1184        let cycles = graph.find_cycles();
1185        assert_eq!(
1186            cycles.len(),
1187            2,
1188            "two cycles sharing edge A->B should both be found, got {}",
1189            cycles.len()
1190        );
1191        assert!(
1192            cycles.iter().all(|c| c.len() == 3),
1193            "both cycles should have length 3"
1194        );
1195    }
1196
1197    #[test]
1198    fn enumerate_elementary_cycles_shared_edge() {
1199        let (modules, all_succs, succ_ranges) =
1200            build_test_succs(4, &[(0, 1), (1, 2), (2, 0), (1, 3), (3, 0)]);
1201        let succs = SuccessorMap {
1202            all_succs: &all_succs,
1203            succ_ranges: &succ_ranges,
1204            modules: &modules,
1205        };
1206        let scc_nodes: Vec<usize> = vec![0, 1, 2, 3];
1207        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1208        assert_eq!(
1209            cycles.len(),
1210            2,
1211            "should find exactly 2 elementary cycles sharing edge 0->1, got {}",
1212            cycles.len()
1213        );
1214    }
1215
1216    #[test]
1217    fn enumerate_elementary_cycles_pentagon_with_chords() {
1218        let (modules, all_succs, succ_ranges) =
1219            build_test_succs(5, &[(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2), (0, 3)]);
1220        let succs = SuccessorMap {
1221            all_succs: &all_succs,
1222            succ_ranges: &succ_ranges,
1223            modules: &modules,
1224        };
1225        let scc_nodes: Vec<usize> = vec![0, 1, 2, 3, 4];
1226        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1227
1228        assert!(
1229            cycles.len() >= 3,
1230            "pentagon with chords should have at least 3 elementary cycles, got {}",
1231            cycles.len()
1232        );
1233        let unique: FxHashSet<Vec<usize>> = cycles.iter().cloned().collect();
1234        assert_eq!(
1235            unique.len(),
1236            cycles.len(),
1237            "all enumerated cycles should be unique"
1238        );
1239        assert_eq!(
1240            cycles[0].len(),
1241            3,
1242            "shortest cycle in pentagon with chords should be length 3"
1243        );
1244    }
1245
1246    #[test]
1247    fn find_cycles_large_scc_complete_graph_k6() {
1248        let edges: Vec<(u32, u32)> = (0..6)
1249            .flat_map(|i| (0..6).filter(move |&j| i != j).map(move |j| (i, j)))
1250            .collect();
1251        let graph = build_cycle_graph(6, &edges);
1252        let cycles = graph.find_cycles();
1253
1254        assert!(
1255            cycles.len() <= 20,
1256            "should cap at MAX_CYCLES_PER_SCC (20), got {}",
1257            cycles.len()
1258        );
1259        assert_eq!(
1260            cycles.len(),
1261            20,
1262            "K6 has far more than 20 elementary cycles, so we should hit the cap"
1263        );
1264        assert_eq!(cycles[0].len(), 2, "shortest cycles in K6 should be 2-node");
1265    }
1266
1267    #[test]
1268    fn enumerate_elementary_cycles_respects_depth_cap_of_12() {
1269        let edges: Vec<(usize, usize)> = (0..15).map(|i| (i, (i + 1) % 15)).collect();
1270        let (modules, all_succs, succ_ranges) = build_test_succs(15, &edges);
1271        let succs = SuccessorMap {
1272            all_succs: &all_succs,
1273            succ_ranges: &succ_ranges,
1274            modules: &modules,
1275        };
1276        let scc_nodes: Vec<usize> = (0..15).collect();
1277        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1278
1279        assert!(
1280            cycles.is_empty(),
1281            "a pure 15-node cycle should not be found with depth cap of 12, got {} cycles",
1282            cycles.len()
1283        );
1284    }
1285
1286    #[test]
1287    fn enumerate_elementary_cycles_finds_cycle_at_depth_cap_boundary() {
1288        let edges: Vec<(usize, usize)> = (0..12).map(|i| (i, (i + 1) % 12)).collect();
1289        let (modules, all_succs, succ_ranges) = build_test_succs(12, &edges);
1290        let succs = SuccessorMap {
1291            all_succs: &all_succs,
1292            succ_ranges: &succ_ranges,
1293            modules: &modules,
1294        };
1295        let scc_nodes: Vec<usize> = (0..12).collect();
1296        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1297
1298        assert_eq!(
1299            cycles.len(),
1300            1,
1301            "a pure 12-node cycle should be found at the depth cap boundary"
1302        );
1303        assert_eq!(cycles[0].len(), 12);
1304    }
1305
1306    #[test]
1307    fn enumerate_elementary_cycles_13_node_pure_cycle_not_found() {
1308        let edges: Vec<(usize, usize)> = (0..13).map(|i| (i, (i + 1) % 13)).collect();
1309        let (modules, all_succs, succ_ranges) = build_test_succs(13, &edges);
1310        let succs = SuccessorMap {
1311            all_succs: &all_succs,
1312            succ_ranges: &succ_ranges,
1313            modules: &modules,
1314        };
1315        let scc_nodes: Vec<usize> = (0..13).collect();
1316        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20);
1317
1318        assert!(
1319            cycles.is_empty(),
1320            "13-node pure cycle exceeds depth cap of 12"
1321        );
1322    }
1323
1324    #[test]
1325    fn find_cycles_max_cycles_per_scc_enforced_on_k7() {
1326        let edges: Vec<(u32, u32)> = (0..7)
1327            .flat_map(|i| (0..7).filter(move |&j| i != j).map(move |j| (i, j)))
1328            .collect();
1329        let graph = build_cycle_graph(7, &edges);
1330        let cycles = graph.find_cycles();
1331
1332        assert!(
1333            cycles.len() <= 20,
1334            "K7 should cap at MAX_CYCLES_PER_SCC (20), got {}",
1335            cycles.len()
1336        );
1337        assert_eq!(
1338            cycles.len(),
1339            20,
1340            "K7 has far more than 20 elementary cycles, should hit the cap exactly"
1341        );
1342    }
1343
1344    #[test]
1345    fn find_cycles_two_dense_sccs_each_capped() {
1346        let mut edges: Vec<(u32, u32)> = Vec::new();
1347        for i in 0..4 {
1348            for j in 0..4 {
1349                if i != j {
1350                    edges.push((i, j));
1351                }
1352            }
1353        }
1354        for i in 4..8 {
1355            for j in 4..8 {
1356                if i != j {
1357                    edges.push((i, j));
1358                }
1359            }
1360        }
1361        let graph = build_cycle_graph(8, &edges);
1362        let cycles = graph.find_cycles();
1363
1364        assert!(!cycles.is_empty(), "two dense SCCs should produce cycles");
1365        assert!(
1366            cycles.len() > 2,
1367            "should find multiple cycles across both SCCs, got {}",
1368            cycles.len()
1369        );
1370    }
1371
1372    mod proptests {
1373        use super::*;
1374        use proptest::prelude::*;
1375
1376        proptest! {
1377            /// A DAG (directed acyclic graph) should always have zero cycles.
1378            /// We construct a DAG by only allowing edges from lower to higher node indices.
1379            #[test]
1380            fn dag_has_no_cycles(
1381                file_count in 2..20usize,
1382                edge_pairs in prop::collection::vec((0..19u32, 0..19u32), 0..30),
1383            ) {
1384                let dag_edges: Vec<(u32, u32)> = edge_pairs
1385                    .into_iter()
1386                    .filter(|(a, b)| (*a as usize) < file_count && (*b as usize) < file_count && a < b)
1387                    .collect();
1388
1389                let graph = build_cycle_graph(file_count, &dag_edges);
1390                let cycles = graph.find_cycles();
1391                prop_assert!(
1392                    cycles.is_empty(),
1393                    "DAG should have no cycles, but found {}",
1394                    cycles.len()
1395                );
1396            }
1397
1398            /// Adding mutual edges A->B->A should always detect a cycle.
1399            #[test]
1400            fn mutual_edges_always_detect_cycle(extra_nodes in 0..10usize) {
1401                let file_count = 2 + extra_nodes;
1402                let graph = build_cycle_graph(file_count, &[(0, 1), (1, 0)]);
1403                let cycles = graph.find_cycles();
1404                prop_assert!(
1405                    !cycles.is_empty(),
1406                    "A->B->A should always produce at least one cycle"
1407                );
1408                let has_pair_cycle = cycles.iter().any(|c| {
1409                    c.contains(&FileId(0)) && c.contains(&FileId(1))
1410                });
1411                prop_assert!(has_pair_cycle, "Should find a cycle containing nodes 0 and 1");
1412            }
1413
1414            /// All cycle members should be valid FileId indices.
1415            #[test]
1416            fn cycle_members_are_valid_indices(
1417                file_count in 2..15usize,
1418                edge_pairs in prop::collection::vec((0..14u32, 0..14u32), 1..20),
1419            ) {
1420                let edges: Vec<(u32, u32)> = edge_pairs
1421                    .into_iter()
1422                    .filter(|(a, b)| (*a as usize) < file_count && (*b as usize) < file_count && a != b)
1423                    .collect();
1424
1425                let graph = build_cycle_graph(file_count, &edges);
1426                let cycles = graph.find_cycles();
1427                for cycle in &cycles {
1428                    prop_assert!(cycle.len() >= 2, "Cycles must have at least 2 nodes");
1429                    for file_id in cycle {
1430                        prop_assert!(
1431                            (file_id.0 as usize) < file_count,
1432                            "FileId {} exceeds file count {}",
1433                            file_id.0, file_count
1434                        );
1435                    }
1436                }
1437            }
1438
1439            /// Cycles should be sorted by length (shortest first).
1440            #[test]
1441            fn cycles_sorted_by_length(
1442                file_count in 3..12usize,
1443                edge_pairs in prop::collection::vec((0..11u32, 0..11u32), 2..25),
1444            ) {
1445                let edges: Vec<(u32, u32)> = edge_pairs
1446                    .into_iter()
1447                    .filter(|(a, b)| (*a as usize) < file_count && (*b as usize) < file_count && a != b)
1448                    .collect();
1449
1450                let graph = build_cycle_graph(file_count, &edges);
1451                let cycles = graph.find_cycles();
1452                for window in cycles.windows(2) {
1453                    prop_assert!(
1454                        window[0].len() <= window[1].len(),
1455                        "Cycles should be sorted by length: {} > {}",
1456                        window[0].len(), window[1].len()
1457                    );
1458                }
1459            }
1460        }
1461    }
1462
1463    /// Build a cycle graph where specific edges are type-only.
1464    fn build_cycle_graph_with_type_only(
1465        file_count: usize,
1466        edges_spec: &[(u32, u32, bool)], // (source, target, is_type_only)
1467    ) -> ModuleGraph {
1468        let files: Vec<DiscoveredFile> = (0..file_count)
1469            .map(|i| DiscoveredFile {
1470                id: FileId(i as u32),
1471                path: PathBuf::from(format!("/project/file{i}.ts")),
1472                size_bytes: 100,
1473            })
1474            .collect();
1475
1476        let resolved_modules: Vec<ResolvedModule> = (0..file_count)
1477            .map(|i| {
1478                let imports: Vec<ResolvedImport> = edges_spec
1479                    .iter()
1480                    .filter(|(src, _, _)| *src == i as u32)
1481                    .map(|(_, tgt, type_only)| ResolvedImport {
1482                        info: ImportInfo {
1483                            source: format!("./file{tgt}"),
1484                            imported_name: ImportedName::Named("x".to_string()),
1485                            local_name: "x".to_string(),
1486                            is_type_only: *type_only,
1487                            from_style: false,
1488                            span: oxc_span::Span::new(0, 10),
1489                            source_span: oxc_span::Span::default(),
1490                        },
1491                        target: ResolveResult::InternalModule(FileId(*tgt)),
1492                    })
1493                    .collect();
1494
1495                ResolvedModule {
1496                    file_id: FileId(i as u32),
1497                    path: PathBuf::from(format!("/project/file{i}.ts")),
1498                    exports: vec![fallow_types::extract::ExportInfo {
1499                        name: ExportName::Named("x".to_string()),
1500                        local_name: Some("x".to_string()),
1501                        is_type_only: false,
1502                        visibility: VisibilityTag::None,
1503                        expected_unused_reason: None,
1504                        span: oxc_span::Span::new(0, 20),
1505                        members: vec![],
1506                        is_side_effect_used: false,
1507                        super_class: None,
1508                    }],
1509                    re_exports: vec![],
1510                    resolved_imports: imports,
1511                    resolved_dynamic_imports: vec![],
1512                    resolved_dynamic_patterns: vec![],
1513                    member_accesses: vec![],
1514                    semantic_facts: Box::default(),
1515                    whole_object_uses: Box::default(),
1516                    has_cjs_exports: false,
1517                    has_angular_component_template_url: false,
1518                    unused_import_bindings: FxHashSet::default(),
1519                    type_referenced_import_bindings: vec![],
1520                    value_referenced_import_bindings: vec![],
1521                    namespace_object_aliases: vec![],
1522                    exported_factory_returns: Box::default(),
1523                    type_member_types: Box::default(),
1524                }
1525            })
1526            .collect();
1527
1528        let entry_points = vec![EntryPoint {
1529            path: PathBuf::from("/project/file0.ts"),
1530            source: EntryPointSource::PackageJsonMain,
1531        }];
1532
1533        ModuleGraph::build(&resolved_modules, &entry_points, &files)
1534    }
1535
1536    #[test]
1537    fn type_only_bidirectional_import_not_a_cycle() {
1538        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, true), (1, 0, true)]);
1539        let cycles = graph.find_cycles();
1540        assert!(
1541            cycles.is_empty(),
1542            "type-only bidirectional imports should not be reported as cycles"
1543        );
1544    }
1545
1546    #[test]
1547    fn mixed_type_and_value_import_not_a_cycle() {
1548        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, false), (1, 0, true)]);
1549        let cycles = graph.find_cycles();
1550        assert!(
1551            cycles.is_empty(),
1552            "A->B (value) + B->A (type-only) is not a runtime cycle"
1553        );
1554    }
1555
1556    #[test]
1557    fn both_value_imports_with_one_type_still_a_cycle() {
1558        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, false), (1, 0, false)]);
1559        let cycles = graph.find_cycles();
1560        assert!(
1561            !cycles.is_empty(),
1562            "bidirectional value imports should be reported as a cycle"
1563        );
1564    }
1565
1566    #[test]
1567    fn all_value_imports_still_a_cycle() {
1568        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, false), (1, 0, false)]);
1569        let cycles = graph.find_cycles();
1570        assert_eq!(cycles.len(), 1);
1571    }
1572
1573    #[test]
1574    fn three_node_type_only_cycle_not_reported() {
1575        let graph =
1576            build_cycle_graph_with_type_only(3, &[(0, 1, true), (1, 2, true), (2, 0, true)]);
1577        let cycles = graph.find_cycles();
1578        assert!(
1579            cycles.is_empty(),
1580            "three-node type-only cycle should not be reported"
1581        );
1582    }
1583
1584    #[test]
1585    fn three_node_cycle_one_value_edge_still_reported() {
1586        let graph =
1587            build_cycle_graph_with_type_only(3, &[(0, 1, false), (1, 2, true), (2, 0, true)]);
1588        let cycles = graph.find_cycles();
1589        assert!(
1590            cycles.is_empty(),
1591            "cycle broken by type-only edge in the middle should not be reported"
1592        );
1593    }
1594}