source-mesh-core 1.1.0

Rust dependency graph analysis, diagrams, and cycle reports
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::hash_map::RandomState;
use std::iter;
use std::num::NonZeroUsize;

use anyhow::Context as _;
use anyhow::Error;
use anyhow::Result;
use anyhow::ensure;
use getset::CopyGetters;
use getset::Getters;
use petgraph::algo::all_simple_paths;
use petgraph::algo::kosaraju_scc;
use petgraph::graph::DiGraph;
use petgraph::graph::GraphError;
use petgraph::graph::NodeIndex;
use petgraph::visit::EdgeFiltered;
use petgraph::visit::EdgeRef as _;
use petgraph::visit::IntoNeighbors as _;

use crate::model::Edge;
use crate::model::FileGraph;
use crate::model::FileNode;
use crate::model::FolderGraph;
use crate::model::FolderNode;

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CopyGetters)]
#[getset(get_copy = "pub")]
pub struct CycleGroupId {
    number: NonZeroUsize,
}

#[derive(Getters, CopyGetters)]
pub struct Cycle<Node> {
    #[getset(get = "pub")]
    nodes: Vec<Node>,
    #[getset(get_copy = "pub")]
    group: CycleGroupId,
}

struct CyclicComponent {
    group: CycleGroupId,
    nodes: BTreeSet<NodeIndex>,
}

pub struct CycleAnalysis<Node> {
    topology: DiGraph<Node, ()>,
    components: Vec<CyclicComponent>,
    edge_groups: BTreeMap<Edge<Node>, Option<CycleGroupId>>,
}

impl<Node: Clone + Ord> CycleAnalysis<Node> {
    fn new<'a>(nodes: &BTreeSet<Node>, edges: impl Iterator<Item = &'a Edge<Node>>) -> Result<Self> where Node: 'a {
        let edges: Vec<_> = edges.collect();
        let mut topology = DiGraph::new();
        let node_indices = nodes.iter().map(|node| topology.try_add_node(node.clone()).map(|index| (node, index)));
        let node_indices: Result<BTreeMap<_, _>, _> = node_indices.collect();
        let node_indices = node_indices.context("Cycle analysis exceeds the supported node index capacity")?;
        for edge in &edges {
            let endpoints = (node_indices.get(edge.source()), node_indices.get(edge.target()));
            let (Some(source_index), Some(target_index)) = endpoints else {
                unreachable!("Validated cycle edge endpoints must have topology indices");
            };
            topology.try_update_edge(*source_index, *target_index, ()).map_err(|error| match error {
                GraphError::EdgeIxLimit => Error::new(error).context("Cycle analysis exceeds the supported edge index capacity"),
                GraphError::NodeIxLimit => unreachable!("Updating a cycle edge cannot add nodes"),
                GraphError::NodeMissed(_) | GraphError::NodeOutBounds => {
                    unreachable!("Cycle edge endpoints were added to the topology")
                }
            })?;
        }
        let mut components = kosaraju_scc(&topology);
        components.retain(|component| {
            component.len() > 1 || component.first().is_some_and(|node| topology.contains_edge(*node, *node))
        });
        for component in &mut components {
            component.sort_unstable();
        }
        components.sort_unstable();
        let mut node_groups = BTreeMap::new();
        let cyclic_components = components.into_iter().enumerate().map(|(index, component)| {
            let Some(number) = NonZeroUsize::new(index + 1) else {
                unreachable!("One-based component vector indices are nonzero");
            };
            let group = CycleGroupId { number };
            for node in &component {
                node_groups.insert(*node, group);
            }
            CyclicComponent { group, nodes: component.into_iter().collect() }
        }).collect();
        let edge_groups = edges.into_iter().map(|edge| {
            let endpoints = (node_indices.get(edge.source()), node_indices.get(edge.target()));
            let (Some(source_index), Some(target_index)) = endpoints else {
                unreachable!("Cycle edge endpoints must remain indexed during grouping");
            };
            let source = node_groups.get(source_index);
            let target = node_groups.get(target_index);
            let group = match (source, target) {
                (Some(source_group), Some(target_group)) if source_group == target_group => Some(*source_group),
                _ => None,
            };
            (Edge::new(edge.source().clone(), edge.target().clone(), edge.kind()), group)
        }).collect();
        Ok(Self { topology, components: cyclic_components, edge_groups })
    }

    #[must_use]
    pub fn edge_group(&self, edge: &Edge<Node>) -> Option<CycleGroupId> {
        self.edge_groups.get(edge).copied().flatten()
    }

    #[must_use]
    pub const fn group_count(&self) -> usize {
        self.components.len()
    }

    pub fn cycles(&self, limit: NonZeroUsize) -> Result<Vec<Cycle<Node>>> {
        let mut cycles = Vec::new();
        for component in &self.components {
            for &minimum_cycle_node in &component.nodes {
                let cycle_subgraph = EdgeFiltered::from_fn(&self.topology, |edge| {
                    let endpoints = [edge.source(), edge.target()];
                    endpoints.into_iter().all(|node| node >= minimum_cycle_node && component.nodes.contains(&node))
                });
                for first_successor in cycle_subgraph.neighbors(minimum_cycle_node) {
                    let paths: Box<dyn Iterator<Item = Vec<NodeIndex>> + '_> = if first_successor == minimum_cycle_node {
                        Box::new(iter::once(vec![minimum_cycle_node]))
                    } else {
                        let paths = all_simple_paths::<Vec<_>, _, RandomState>(
                            &cycle_subgraph,
                            first_successor,
                            minimum_cycle_node,
                            0,
                            None,
                        );
                        Box::new(paths)
                    };
                    for path in paths {
                        ensure!(cycles.len() < limit.get(), "Cycle count exceeds {limit}; raise the limit to list all cycles");
                        let path_nodes = iter::once(minimum_cycle_node).chain(path);
                        let nodes = path_nodes.map(|node| self.topology[node].clone()).collect();
                        cycles.push(Cycle { nodes, group: component.group });
                    }
                }
            }
        }
        cycles.sort_by(|left, right| (left.group, &left.nodes).cmp(&(right.group, &right.nodes)));
        Ok(cycles)
    }
}

pub fn analyze_folders(graph: &FolderGraph) -> Result<CycleAnalysis<FolderNode>> {
    CycleAnalysis::new(graph.nodes(), graph.edges().keys())
}

pub fn analyze_files(graph: &FileGraph) -> Result<CycleAnalysis<FileNode>> {
    CycleAnalysis::new(graph.files(), graph.edges().iter())
}

pub(crate) fn validate_folder_analysis(analysis: &CycleAnalysis<FolderNode>, graph: &FolderGraph) -> Result<()> {
    ensure!(
        analysis.topology.node_weights().eq(graph.nodes()) && analysis.edge_groups.keys().eq(graph.edges().keys()),
        "Cycle analysis does not match the folder graph"
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::collections::BTreeSet;
    use std::iter;
    use std::num::NonZeroUsize;
    use std::panic::catch_unwind;
    use std::path::Path;
    use std::path::PathBuf;

    use anyhow::Result;
    use claims::assert_ok;
    use claims::assert_some;
    use pretty_assertions::assert_eq;
    use rstest::rstest;

    use super::CycleAnalysis;
    use super::analyze_files;
    use super::analyze_folders;
    use super::validate_folder_analysis;
    use crate::SourcePath;
    use crate::model::DependencyCount;
    use crate::model::DependencyKind;
    use crate::model::DependencyKind::Production;
    use crate::model::DependencyKind::Test;
    use crate::model::FileEdge;
    use crate::model::FileGraph;
    use crate::model::FileNode;
    use crate::model::FolderEdge;
    use crate::model::FolderGraph;
    use crate::model::FolderNode;

    fn folder_fixture(dependencies: &[(&str, &str, DependencyKind)]) -> Result<FolderGraph> {
        let edges = folder_dependencies(dependencies);
        let nodes = edges.keys().flat_map(|edge| [edge.source().clone(), edge.target().clone()]).collect();
        FolderGraph::new(nodes, edges)
    }

    #[must_use]
    fn folder_dependencies(dependencies: &[(&str, &str, DependencyKind)]) -> BTreeMap<FolderEdge, DependencyCount> {
        dependencies.iter().map(|&(source, target, kind)| {
            let edge = FolderEdge::new(FolderNode::new(source.into()), FolderNode::new(target.into()), kind);
            (edge, DependencyCount::new(1))
        }).collect()
    }

    #[must_use]
    fn folder_path(labels: &[&str]) -> Vec<FolderNode> {
        labels.iter().map(|label| FolderNode::new((*label).into())).collect()
    }

    #[rstest]
    #[case(&[], vec![])]
    #[case(&[("alpha", "beta", Production), ("beta", "gamma", Production)], vec![])]
    #[case(&[("alpha", "beta", Production), ("gamma", "beta", Production)], vec![])]
    #[case(&[("alpha", "beta", Production), ("beta", "alpha", Production)], vec![vec!["alpha", "beta", "alpha"]])]
    #[case(
        &[("alpha", "beta", Production), ("beta", "gamma", Production), ("gamma", "alpha", Production)],
        vec![vec!["alpha", "beta", "gamma", "alpha"]]
    )]
    #[case(
        &[
            ("alpha", "beta", Production), ("beta", "alpha", Production),
            ("beta", "gamma", Production), ("gamma", "beta", Production),
        ],
        vec![vec!["alpha", "beta", "alpha"], vec!["beta", "gamma", "beta"]]
    )]
    #[case(&[("alpha", "alpha", Production)], vec![vec!["alpha", "alpha"]])]
    #[case(
        &[("alpha", "alpha", Production), ("alpha", "beta", Production), ("beta", "alpha", Production)],
        vec![vec!["alpha", "alpha"], vec!["alpha", "beta", "alpha"]]
    )]
    #[case(
        &[("alpha", "beta", Production), ("alpha", "beta", Test), ("beta", "alpha", Production), ("beta", "alpha", Test)],
        vec![vec!["alpha", "beta", "alpha"]]
    )]
    #[case(&[("alpha", "alpha", Production), ("alpha", "alpha", Test)], vec![vec!["alpha", "alpha"]])]
    #[case(
        &[
            ("alpha", "beta", Production), ("alpha", "gamma", Production), ("beta", "omega", Production),
            ("gamma", "omega", Production), ("omega", "alpha", Production),
        ],
        vec![vec!["alpha", "beta", "omega", "alpha"], vec!["alpha", "gamma", "omega", "alpha"]]
    )]
    #[case(
        &[
            ("alpha", "beta", Production), ("beta", "gamma", Production), ("gamma", "alpha", Production),
            ("alpha", "gamma", Production), ("gamma", "beta", Production), ("beta", "alpha", Production),
        ],
        vec![
            vec!["alpha", "beta", "alpha"], vec!["alpha", "beta", "gamma", "alpha"],
            vec!["alpha", "gamma", "alpha"], vec!["alpha", "gamma", "beta", "alpha"], vec!["beta", "gamma", "beta"],
        ]
    )]
    fn test_directed_cycle_routes(#[case] dependencies: &[(&str, &str, DependencyKind)], #[case] expected_paths: Vec<Vec<&str>>) {
        let fixture = folder_fixture(dependencies);
        let fixture = assert_ok!(fixture, "Cycle-route dependencies must form a valid folder graph");
        let system_under_test = analyze_folders(&fixture);
        let system_under_test = assert_ok!(system_under_test, "Folder cycle analysis must succeed");
        let expected: Vec<_> = expected_paths.into_iter().map(|labels| folder_path(&labels)).collect();

        let limit = NonZeroUsize::new(10);
        let limit = assert_some!(limit, "Cycle-route enumeration limit must be nonzero");
        let cycles = system_under_test.cycles(limit);
        let cycles = assert_ok!(cycles, "All fixture cycles must fit within the enumeration limit");
        let paths: Vec<_> = cycles.into_iter().map(|cycle| cycle.nodes).collect();

        assert_eq!(expected, paths, "Directed cycle routes or their canonical order differ");
    }

    #[rstest]
    #[case("alpha", "beta", Production, Some(1))]
    #[case("beta", "alpha", Test, Some(1))]
    #[case("gamma", "omega", Production, Some(2))]
    #[case("omega", "gamma", Production, Some(2))]
    #[case("beta", "gamma", Production, None)]
    #[case("alpha", "omega", Production, None)]
    #[case("alpha", "beta", Test, None)]
    #[case("unknown", "alpha", Production, None)]
    #[case("entry", "alpha", Production, None)]
    #[case("omega", "exit", Production, None)]
    #[case("leaf", "sink", Production, None)]
    fn test_component_edge_membership(
        #[case] source: &str,
        #[case] target: &str,
        #[case] kind: DependencyKind,
        #[case] expected_group: Option<usize>,
    ) {
        let fixture = folder_fixture(&[
            ("omega", "gamma", Production),
            ("gamma", "omega", Production),
            ("beta", "gamma", Production),
            ("beta", "alpha", Test),
            ("alpha", "beta", Production),
            ("entry", "alpha", Production),
            ("omega", "exit", Production),
            ("leaf", "sink", Production),
        ]);
        let fixture = assert_ok!(fixture, "Component-membership dependencies must form a valid folder graph");
        let system_under_test = analyze_folders(&fixture);
        let system_under_test = assert_ok!(system_under_test, "Component-membership analysis must succeed");
        let edge = FolderEdge::new(FolderNode::new(source.into()), FolderNode::new(target.into()), kind);

        let group = system_under_test.edge_group(&edge);

        assert_eq!(2, system_under_test.group_count(), "Independent cyclic components were merged");
        assert_eq!(expected_group, group.map(|identifier| identifier.number().get()), "Incorrect cycle edge group");
    }

    #[test]
    fn test_cycle_group_assignment() {
        let fixture = folder_fixture(&[
            ("gamma", "omega", Production),
            ("omega", "gamma", Production),
            ("alpha", "beta", Production),
            ("beta", "alpha", Production),
            ("beta", "gamma", Production),
        ]);
        let fixture = assert_ok!(fixture, "Independent cycle groups and their bridge must form a valid graph");
        let system_under_test = analyze_folders(&fixture);
        let system_under_test = assert_ok!(system_under_test, "Independent cycle-group analysis must succeed");
        let expected = [folder_path(&["alpha", "beta", "alpha"]), folder_path(&["gamma", "omega", "gamma"])];

        let limit = NonZeroUsize::new(2);
        let limit = assert_some!(limit, "Two-cycle enumeration limit must be nonzero");
        let cycles = system_under_test.cycles(limit);
        let cycles = assert_ok!(cycles, "Both independent cycles must fit within the limit");
        let groups: Vec<_> = cycles.iter().map(|cycle| cycle.group().number().get()).collect();
        let paths: Vec<_> = cycles.into_iter().map(|cycle| cycle.nodes).collect();

        assert_eq!(groups, [1, 2], "Cycle group numbers differ");
        assert_eq!(paths, expected, "Independent cycle routes or their order differ");
    }

    #[rstest]
    #[case(1, true)]
    #[case(2, false)]
    #[case(3, false)]
    fn test_cycle_enumeration_limit(#[case] limit: usize, #[case] exceeds_limit: bool) {
        let fixture = folder_fixture(&[
            ("alpha", "beta", Production),
            ("beta", "alpha", Production),
            ("beta", "gamma", Production),
            ("gamma", "beta", Production),
        ]);
        let fixture = assert_ok!(fixture, "Overlapping-cycle dependencies must form a valid graph");
        let system_under_test = analyze_folders(&fixture);
        let system_under_test = assert_ok!(system_under_test, "Overlapping-cycle analysis must succeed");

        let limit = NonZeroUsize::new(limit);
        let limit = assert_some!(limit, "Parameterized cycle limit must be nonzero");
        let result = system_under_test.cycles(limit);

        assert_eq!(1, system_under_test.group_count(), "Overlapping cycles have separate groups");
        if exceeds_limit {
            assert!(result.is_err(), "Excess cycles were silently truncated");
        } else {
            let cycles = assert_ok!(result, "Both overlapping cycles must fit within limit {limit}");
            assert_eq!(2, cycles.len(), "Enumeration did not retain every cycle within the limit");
        }
    }

    #[test]
    fn test_isolated_nodes() {
        let fixture = FolderGraph::new(BTreeSet::from([FolderNode::new("isolated".into())]), BTreeMap::new());
        let fixture = assert_ok!(fixture, "An isolated folder must form a valid graph");
        let system_under_test = analyze_folders(&fixture);
        let system_under_test = assert_ok!(system_under_test, "An isolated folder must support cycle analysis");

        let cycles = system_under_test.cycles(NonZeroUsize::MIN);
        let cycles = assert_ok!(cycles, "An isolated folder must enumerate without exceeding the cycle limit");

        assert_eq!(0, system_under_test.group_count(), "Isolated node became a cyclic component");
        assert!(cycles.is_empty(), "Isolated node produced a phantom cycle");
    }

    #[rstest]
    #[case(Path::new("."), false, 1)]
    #[case(Path::new("."), true, 0)]
    #[case(Path::new("alpha"), false, 0)]
    #[case(Path::new("beta"), false, 0)]
    fn test_file_cycle_routes(#[case] root: &Path, #[case] exclude_tests: bool, #[case] expected_cycles: usize) {
        let first_path = SourcePath::new(PathBuf::from_iter(["alpha", "source.rs"]));
        let first_path = assert_ok!(first_path, "First cycle file must have a valid source path");
        let first_file = FileNode::new(first_path);
        let second_path = SourcePath::new(PathBuf::from_iter(["beta", "source.rs"]));
        let second_path = assert_ok!(second_path, "Second cycle file must have a valid source path");
        let second_file = FileNode::new(second_path);
        let fixture = FileGraph::new(
            BTreeSet::from([first_file.clone(), second_file.clone()]),
            BTreeSet::from([
                FileEdge::new(first_file.clone(), second_file.clone(), Production),
                FileEdge::new(second_file.clone(), first_file.clone(), Test),
            ]),
        );
        let fixture = assert_ok!(fixture, "Production and test cycle edges must form a valid file graph");
        let fixture = if exclude_tests { fixture.without_test_dependencies() } else { fixture }.within_root(root);
        let fixture = assert_ok!(fixture, "File cycle fixture must support the requested root: {root:?}");
        let system_under_test = analyze_files(&fixture);
        let system_under_test = assert_ok!(system_under_test, "Filtered file graph must support cycle analysis");
        let expected = vec![first_file.clone(), second_file, first_file];

        let cycles = system_under_test.cycles(NonZeroUsize::MIN);
        let cycles = assert_ok!(cycles, "Filtered file graph must have at most one cycle");

        assert_eq!(expected_cycles, system_under_test.group_count(), "File cycle components ignored root or test filtering");
        assert_eq!(expected_cycles, cycles.len(), "File cycle count differs");
        if expected_cycles != 0 {
            assert!(cycles.first().is_some_and(|cycle| cycle.nodes() == &expected), "File cycle route differs");
            assert!(
                fixture.edges().iter().all(|edge| system_under_test.edge_group(edge).is_some()),
                "File cycle edge was not grouped"
            );
        }
    }

    #[rstest]
    #[case("alpha", "unknown")]
    #[case("unknown", "alpha")]
    fn test_dependency_endpoint_membership(#[case] source: &str, #[case] target: &str) {
        let nodes = BTreeSet::from([FolderNode::new("alpha".into())]);
        let edge = FolderEdge::new(FolderNode::new(source.into()), FolderNode::new(target.into()), Production);
        let system_under_test = || CycleAnalysis::new(&nodes, iter::once(&edge));

        let result = catch_unwind(system_under_test);

        assert!(result.is_err(), "Missing validated endpoints must be invariant violations, not user errors");
    }

    #[rstest]
    #[case(&[("alpha", "beta", Production), ("beta", "gamma", Production)])]
    #[case(&[
        ("alpha", "beta", Production), ("beta", "alpha", Production),
        ("beta", "gamma", Production), ("gamma", "alpha", Production),
    ])]
    #[case(&[("alpha", "beta", Test), ("beta", "alpha", Production), ("beta", "gamma", Production)])]
    #[case(&[("alpha", "beta", Production), ("beta", "alpha", Production)])]
    fn test_folder_analysis_dependencies(#[case] dependencies: &[(&str, &str, DependencyKind)]) {
        let fixture_dependencies = [("alpha", "beta", Production), ("beta", "alpha", Production), ("beta", "gamma", Production)];
        let fixture = folder_fixture(&fixture_dependencies);
        let fixture = assert_ok!(fixture, "Original analysis dependencies must form a valid graph");
        let system_under_test = analyze_folders(&fixture);
        let system_under_test = assert_ok!(system_under_test, "Original topology must support cycle analysis");
        let changed_graph = FolderGraph::new(fixture.nodes().clone(), folder_dependencies(dependencies));
        let changed_graph = assert_ok!(changed_graph, "Changed dependencies must still form a valid graph");

        let result = validate_folder_analysis(&system_under_test, &changed_graph);

        assert!(result.is_err(), "Changed dependency topology or kind accepted an outdated cycle analysis");
    }

    #[rstest]
    #[case(&["alpha", "beta"], false)]
    #[case(&["alpha", "beta", "isolated", "other"], false)]
    #[case(&["isolated", "beta", "alpha"], true)]
    fn test_folder_analysis_nodes(#[case] labels: &[&str], #[case] matches_analysis: bool) {
        let dependencies = [("alpha", "beta", Production), ("beta", "alpha", Production)];
        let fixture = FolderGraph::new(
            folder_path(&["alpha", "beta", "isolated"]).into_iter().collect(),
            folder_dependencies(&dependencies),
        );
        let fixture = assert_ok!(fixture, "Cycle and isolated nodes must form a valid graph");
        let system_under_test = analyze_folders(&fixture);
        let system_under_test = assert_ok!(system_under_test, "Original node set must support cycle analysis");
        let changed_graph = FolderGraph::new(folder_path(labels).into_iter().collect(), folder_dependencies(&dependencies));
        let changed_graph = assert_ok!(changed_graph, "Changed node set must retain every dependency endpoint");

        let result = validate_folder_analysis(&system_under_test, &changed_graph);

        if matches_analysis {
            assert_ok!(result, "Reordered folder nodes must preserve the cycle analysis topology");
        } else {
            assert!(result.is_err(), "Changed folder node set accepted an outdated cycle analysis");
        }
    }

    #[rstest]
    #[case(1)]
    #[case(27)]
    fn test_folder_analysis_dependency_counts(#[case] count: usize) {
        let dependencies = [("alpha", "beta", Production), ("beta", "alpha", Production)];
        let fixture = folder_fixture(&dependencies);
        let fixture = assert_ok!(fixture, "Dependency-count fixture must form a valid graph");
        let system_under_test = analyze_folders(&fixture);
        let system_under_test = assert_ok!(system_under_test, "Dependency-count fixture must support cycle analysis");
        let mut edges = folder_dependencies(&dependencies);
        for weight in edges.values_mut() {
            *weight = DependencyCount::new(count);
        }
        let changed_graph = FolderGraph::new(fixture.nodes().clone(), edges);
        let changed_graph = assert_ok!(changed_graph, "Changed dependency counts must preserve graph validity");

        let result = validate_folder_analysis(&system_under_test, &changed_graph);

        assert_ok!(result, "Dependency counts must not invalidate an unchanged cycle topology");
    }
}