1use std::path::{Path, PathBuf};
14
15use rustc_hash::{FxHashMap, FxHashSet};
16
17use crate::churn::ChurnCommit;
18use crate::workspace_scope::WorkspaceScope;
19
20const DEFAULT_MAX_FILES_PER_COMMIT: usize = 30;
24const DEFAULT_MIN_REVISIONS: u32 = 5;
26const DEFAULT_MIN_SHARED_REVISIONS: u32 = 5;
28const DEFAULT_MIN_DEGREE: f64 = 0.3;
30pub(crate) const STRONG_COUPLING_DEGREE: f64 = 0.5;
33
34#[derive(Debug, Clone, Copy, PartialEq)]
36pub struct ChangeCouplingSettings {
37 pub max_files_per_commit: usize,
39 pub min_revisions: u32,
41 pub min_shared_revisions: u32,
43 pub min_degree: f64,
45}
46
47impl Default for ChangeCouplingSettings {
48 fn default() -> Self {
49 Self {
50 max_files_per_commit: DEFAULT_MAX_FILES_PER_COMMIT,
51 min_revisions: DEFAULT_MIN_REVISIONS,
52 min_shared_revisions: DEFAULT_MIN_SHARED_REVISIONS,
53 min_degree: DEFAULT_MIN_DEGREE,
54 }
55 }
56}
57
58impl From<&fallow_config::ChangeCouplingConfig> for ChangeCouplingSettings {
59 fn from(config: &fallow_config::ChangeCouplingConfig) -> Self {
60 Self {
61 max_files_per_commit: config.max_files_per_commit,
62 min_revisions: config.min_revisions,
63 min_shared_revisions: config.min_shared_revisions,
64 min_degree: config.min_degree,
65 }
66 }
67}
68
69#[derive(Debug, Clone, PartialEq)]
71pub struct CoChangePair {
72 pub path_a: PathBuf,
74 pub path_b: PathBuf,
76 pub revisions_a: u32,
78 pub revisions_b: u32,
80 pub shared_revisions: u32,
82 pub degree: f64,
85}
86
87impl CoChangePair {
88 #[must_use]
90 pub(crate) fn is_strong(&self) -> bool {
91 self.degree >= STRONG_COUPLING_DEGREE
92 }
93
94 #[must_use]
96 fn partner_of(&self, path: &Path) -> Option<&Path> {
97 if self.path_a == path {
98 Some(&self.path_b)
99 } else if self.path_b == path {
100 Some(&self.path_a)
101 } else {
102 None
103 }
104 }
105}
106
107#[derive(Debug, Clone, Copy, PartialEq)]
109pub struct FileDispersion {
110 pub median_files_per_commit: f64,
112 pub median_lines_per_commit: f64,
115}
116
117#[derive(Debug, Clone, Default)]
119pub struct ChangeHistoryAnalysis {
120 pub commits_analyzed: usize,
122 pub commits_skipped: usize,
124 pub dispersion: FxHashMap<PathBuf, FileDispersion>,
126 pub hidden_pairs: Vec<CoChangePair>,
129}
130
131impl ChangeHistoryAnalysis {
132 pub(crate) fn partners_of<'a>(
134 &'a self,
135 path: &'a Path,
136 ) -> impl Iterator<Item = (&'a Path, &'a CoChangePair)> {
137 self.hidden_pairs
138 .iter()
139 .filter_map(move |pair| pair.partner_of(path).map(|partner| (partner, pair)))
140 }
141}
142
143#[derive(Debug, Clone, Default)]
148pub struct StaticLinkIndex {
149 ids: FxHashMap<PathBuf, u32>,
150 targets: Vec<Vec<u32>>,
152 re_export_sources: Vec<Vec<u32>>,
154}
155
156impl StaticLinkIndex {
157 #[must_use]
159 pub fn from_retained_graph(graph: &crate::module_graph::RetainedModuleGraph) -> Self {
160 Self::from_graph(graph.as_graph())
161 }
162
163 #[must_use]
165 pub(crate) fn from_graph(graph: &fallow_graph::graph::ModuleGraph) -> Self {
166 let mut ids = FxHashMap::default();
167 let mut targets = Vec::with_capacity(graph.modules.len());
168 let mut re_export_sources = Vec::with_capacity(graph.modules.len());
169 for node in &graph.modules {
170 ids.insert(node.path.clone(), node.file_id.0);
171 let mut node_targets: Vec<u32> = graph
172 .edges_for(node.file_id)
173 .iter()
174 .map(|id| id.0)
175 .collect();
176 let sources: Vec<u32> = node
177 .re_exports
178 .iter()
179 .map(|edge| edge.source_file.0)
180 .collect();
181 node_targets.extend(sources.iter().copied());
182 node_targets.sort_unstable();
183 node_targets.dedup();
184 targets.push(node_targets);
185 re_export_sources.push(sources);
186 }
187 Self {
188 ids,
189 targets,
190 re_export_sources,
191 }
192 }
193
194 #[cfg(test)]
196 fn from_links(
197 files: &[PathBuf],
198 imports: &[(usize, usize)],
199 re_exports: &[(usize, usize)],
200 ) -> Self {
201 let ids = files
202 .iter()
203 .enumerate()
204 .filter_map(|(idx, path)| u32::try_from(idx).ok().map(|idx| (path.clone(), idx)))
205 .collect();
206 let mut targets = vec![Vec::new(); files.len()];
207 let mut re_export_sources = vec![Vec::new(); files.len()];
208 for &(from, to) in imports {
209 if let (Some(list), Ok(to)) = (targets.get_mut(from), u32::try_from(to)) {
210 list.push(to);
211 }
212 }
213 for &(from, to) in re_exports {
214 if let (Some(list), Ok(to)) = (targets.get_mut(from), u32::try_from(to)) {
215 list.push(to);
216 }
217 if let (Some(list), Ok(to)) = (re_export_sources.get_mut(from), u32::try_from(to)) {
218 list.push(to);
219 }
220 }
221 Self {
222 ids,
223 targets,
224 re_export_sources,
225 }
226 }
227
228 #[must_use]
230 pub fn contains(&self, path: &Path) -> bool {
231 self.ids.contains_key(path)
232 }
233
234 #[must_use]
236 fn linked(&self, a: &Path, b: &Path) -> bool {
237 let (Some(&a), Some(&b)) = (self.ids.get(a), self.ids.get(b)) else {
238 return false;
239 };
240 self.reaches(a, b) || self.reaches(b, a)
241 }
242
243 fn reaches(&self, from: u32, to: u32) -> bool {
246 let Some(direct) = self.targets.get(from as usize) else {
247 return false;
248 };
249 let mut seen: FxHashSet<u32> = FxHashSet::default();
250 let mut queue: Vec<u32> = direct.clone();
251 while let Some(current) = queue.pop() {
252 if current == to {
253 return true;
254 }
255 if !seen.insert(current) {
256 continue;
257 }
258 if let Some(sources) = self.re_export_sources.get(current as usize) {
259 queue.extend(sources.iter().copied().filter(|id| !seen.contains(id)));
260 }
261 }
262 false
263 }
264}
265
266#[must_use]
272pub fn analyze_change_history(
273 commits: &[ChurnCommit],
274 links: &StaticLinkIndex,
275 settings: &ChangeCouplingSettings,
276) -> ChangeHistoryAnalysis {
277 let mut interned: FxHashMap<&Path, u32> = FxHashMap::default();
278 let mut paths: Vec<&Path> = Vec::new();
279 let mut revisions: Vec<u32> = Vec::new();
280 let mut samples: Vec<Vec<(u32, u32)>> = Vec::new();
281 let mut shared: FxHashMap<(u32, u32), u32> = FxHashMap::default();
282 let mut analysis = ChangeHistoryAnalysis::default();
283
284 for commit in commits {
285 let files: Vec<&crate::churn::ChurnCommitFile> = commit
286 .files
287 .iter()
288 .filter(|file| links.contains(&file.path))
289 .collect();
290 if files.is_empty() {
291 continue;
292 }
293 if files.len() > settings.max_files_per_commit {
294 analysis.commits_skipped += 1;
295 continue;
296 }
297 analysis.commits_analyzed += 1;
298 let file_count = u32::try_from(files.len()).unwrap_or(u32::MAX);
299 let lines = files
300 .iter()
301 .fold(0_u32, |sum, file| sum.saturating_add(file.lines_changed));
302 let mut ids: Vec<u32> = files
303 .iter()
304 .map(|file| {
305 *interned.entry(file.path.as_path()).or_insert_with(|| {
306 paths.push(file.path.as_path());
307 revisions.push(0);
308 samples.push(Vec::new());
309 u32::try_from(paths.len() - 1).unwrap_or(u32::MAX)
310 })
311 })
312 .collect();
313 ids.sort_unstable();
314 ids.dedup();
315 for &id in &ids {
316 revisions[id as usize] += 1;
317 samples[id as usize].push((file_count, lines));
318 }
319 for (index, &a) in ids.iter().enumerate() {
320 for &b in &ids[index + 1..] {
321 *shared.entry((a, b)).or_default() += 1;
322 }
323 }
324 }
325
326 for (id, file_samples) in samples.into_iter().enumerate() {
327 let mut file_counts: Vec<u32> = file_samples.iter().map(|(files, _)| *files).collect();
328 let mut line_counts: Vec<u32> = file_samples.iter().map(|(_, lines)| *lines).collect();
329 analysis.dispersion.insert(
330 paths[id].to_path_buf(),
331 FileDispersion {
332 median_files_per_commit: median(&mut file_counts),
333 median_lines_per_commit: median(&mut line_counts),
334 },
335 );
336 }
337
338 for ((a, b), shared_revisions) in shared {
339 let revisions_a = revisions[a as usize];
340 let revisions_b = revisions[b as usize];
341 if revisions_a < settings.min_revisions
342 || revisions_b < settings.min_revisions
343 || shared_revisions < settings.min_shared_revisions
344 {
345 continue;
346 }
347 let degree = coupling_degree(shared_revisions, revisions_a, revisions_b);
348 if degree < settings.min_degree {
349 continue;
350 }
351 let (path_a, path_b) = (paths[a as usize], paths[b as usize]);
352 if links.linked(path_a, path_b) {
353 continue;
354 }
355 let (path_a, path_b, revisions_a, revisions_b) = if path_a <= path_b {
356 (path_a, path_b, revisions_a, revisions_b)
357 } else {
358 (path_b, path_a, revisions_b, revisions_a)
359 };
360 analysis.hidden_pairs.push(CoChangePair {
361 path_a: path_a.to_path_buf(),
362 path_b: path_b.to_path_buf(),
363 revisions_a,
364 revisions_b,
365 shared_revisions,
366 degree: (degree * 100.0).round() / 100.0,
367 });
368 }
369 analysis.hidden_pairs.sort_by(|x, y| {
370 y.degree
371 .partial_cmp(&x.degree)
372 .unwrap_or(std::cmp::Ordering::Equal)
373 .then_with(|| y.shared_revisions.cmp(&x.shared_revisions))
374 .then_with(|| x.path_a.cmp(&y.path_a))
375 .then_with(|| x.path_b.cmp(&y.path_b))
376 });
377 analysis
378}
379
380#[derive(Debug, Clone, PartialEq)]
382pub struct CoChangeGap {
383 pub changed: PathBuf,
385 pub partner: PathBuf,
387 pub shared_revisions: u32,
389 pub degree: f64,
391}
392
393pub struct PairScope<'a> {
396 pub root: &'a Path,
398 pub ignore_set: &'a globset::GlobSet,
400 pub ws_roots: Option<&'a WorkspaceScope>,
402 pub diff_index: Option<&'a fallow_output::DiffIndex>,
404}
405
406impl PairScope<'_> {
407 #[must_use]
410 pub fn contains(&self, path_a: &Path, path_b: &Path) -> bool {
411 let ignored = |path: &Path| {
412 !self.ignore_set.is_empty()
413 && self
414 .ignore_set
415 .is_match(path.strip_prefix(self.root).unwrap_or(path))
416 };
417 if ignored(path_a) || ignored(path_b) {
418 return false;
419 }
420 let in_workspace = |path: &Path| self.ws_roots.is_none_or(|scope| scope.contains(path));
421 if !in_workspace(path_a) && !in_workspace(path_b) {
422 return false;
423 }
424 let Some(diff_index) = self.diff_index else {
425 return true;
426 };
427 let in_diff = |path: &Path| match diff_index.key_for(path, self.root) {
428 Some(rel) => diff_index.touches_file(&rel),
429 None => true,
430 };
431 in_diff(path_a) || in_diff(path_b)
432 }
433}
434
435#[must_use]
437pub fn health_ignore_set(patterns: &[String]) -> globset::GlobSet {
438 crate::health::ignore::build_ignore_set(patterns)
439}
440
441#[must_use]
445#[expect(
446 clippy::implicit_hasher,
447 reason = "callers pass the audit changed-file FxHashSet"
448)]
449pub fn co_change_gaps(
450 analysis: &ChangeHistoryAnalysis,
451 changed: &FxHashSet<PathBuf>,
452) -> Vec<CoChangeGap> {
453 let mut gaps: Vec<CoChangeGap> = analysis
454 .hidden_pairs
455 .iter()
456 .filter_map(|pair| {
457 let (changed_path, partner) = match (
458 changed.contains(&pair.path_a),
459 changed.contains(&pair.path_b),
460 ) {
461 (true, false) => (&pair.path_a, &pair.path_b),
462 (false, true) => (&pair.path_b, &pair.path_a),
463 _ => return None,
464 };
465 Some(CoChangeGap {
466 changed: changed_path.clone(),
467 partner: partner.clone(),
468 shared_revisions: pair.shared_revisions,
469 degree: pair.degree,
470 })
471 })
472 .collect();
473 gaps.sort_by(|a, b| {
474 b.degree
475 .partial_cmp(&a.degree)
476 .unwrap_or(std::cmp::Ordering::Equal)
477 .then_with(|| b.shared_revisions.cmp(&a.shared_revisions))
478 .then_with(|| a.changed.cmp(&b.changed))
479 .then_with(|| a.partner.cmp(&b.partner))
480 });
481 gaps
482}
483
484fn coupling_degree(shared: u32, revisions_a: u32, revisions_b: u32) -> f64 {
486 let mean = f64::midpoint(f64::from(revisions_a), f64::from(revisions_b));
487 if mean <= 0.0 {
488 return 0.0;
489 }
490 (f64::from(shared) / mean).min(1.0)
491}
492
493fn median(values: &mut [u32]) -> f64 {
496 if values.is_empty() {
497 return 0.0;
498 }
499 values.sort_unstable();
500 let mid = values.len() / 2;
501 if values.len() % 2 == 1 {
502 f64::from(values[mid])
503 } else {
504 f64::midpoint(f64::from(values[mid - 1]), f64::from(values[mid]))
505 }
506}
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511 use crate::churn::{ChurnCommit, ChurnCommitFile};
512
513 fn path(name: &str) -> PathBuf {
514 PathBuf::from(format!("/project/src/{name}.ts"))
515 }
516
517 fn commit(id: usize, files: &[(&str, u32)]) -> ChurnCommit {
518 ChurnCommit {
519 sha: format!("{id:040x}"),
520 committed_at: 1_700_000_000 + id as u64,
521 files: files
522 .iter()
523 .map(|(name, lines)| ChurnCommitFile {
524 path: path(name),
525 lines_changed: *lines,
526 })
527 .collect(),
528 }
529 }
530
531 fn index(names: &[&str]) -> StaticLinkIndex {
532 let files: Vec<PathBuf> = names.iter().map(|name| path(name)).collect();
533 StaticLinkIndex::from_links(&files, &[], &[])
534 }
535
536 fn together(start: usize, count: usize, a: &str, b: &str) -> Vec<ChurnCommit> {
538 (start..start + count)
539 .map(|id| commit(id, &[(a, 1), (b, 1)]))
540 .collect()
541 }
542
543 #[test]
544 fn a_pair_that_meets_every_threshold_without_a_static_edge_is_hidden() {
545 let commits = together(0, 5, "a", "b");
546 let analysis = analyze_change_history(
547 &commits,
548 &index(&["a", "b"]),
549 &ChangeCouplingSettings::default(),
550 );
551
552 assert_eq!(analysis.hidden_pairs.len(), 1);
553 let pair = &analysis.hidden_pairs[0];
554 assert_eq!(
555 (pair.path_a.clone(), pair.path_b.clone()),
556 (path("a"), path("b"))
557 );
558 assert_eq!(pair.shared_revisions, 5);
559 assert!((pair.degree - 1.0).abs() < f64::EPSILON);
560 assert!(pair.is_strong());
561 }
562
563 #[test]
564 fn a_pair_below_the_shared_revision_minimum_is_not_reported() {
565 let commits = together(0, 4, "a", "b");
566 let analysis = analyze_change_history(
567 &commits,
568 &index(&["a", "b"]),
569 &ChangeCouplingSettings::default(),
570 );
571
572 assert!(analysis.hidden_pairs.is_empty());
573 }
574
575 #[test]
576 fn a_pair_below_the_degree_minimum_is_not_reported() {
577 let mut commits = together(0, 5, "a", "b");
579 commits.extend((100..130).map(|id| commit(id, &[("a", 1)])));
580 let analysis = analyze_change_history(
581 &commits,
582 &index(&["a", "b"]),
583 &ChangeCouplingSettings::default(),
584 );
585
586 assert!(analysis.hidden_pairs.is_empty());
587 }
588
589 #[test]
590 fn an_import_in_either_direction_hides_nothing() {
591 let commits = together(0, 6, "a", "b");
592 let files = vec![path("a"), path("b")];
593 let forward = StaticLinkIndex::from_links(&files, &[(0, 1)], &[]);
594 let backward = StaticLinkIndex::from_links(&files, &[(1, 0)], &[]);
595
596 for links in [forward, backward] {
597 let analysis =
598 analyze_change_history(&commits, &links, &ChangeCouplingSettings::default());
599 assert!(analysis.hidden_pairs.is_empty());
600 }
601 }
602
603 #[test]
604 fn a_re_export_chain_counts_as_a_static_edge() {
605 let commits = together(0, 6, "a", "b");
607 let files = vec![path("a"), path("barrel"), path("mid"), path("b")];
608 let links = StaticLinkIndex::from_links(&files, &[(0, 1)], &[(1, 2), (2, 3)]);
609
610 let analysis = analyze_change_history(&commits, &links, &ChangeCouplingSettings::default());
611 assert!(analysis.hidden_pairs.is_empty());
612 }
613
614 #[test]
615 fn a_plain_import_of_an_importer_is_not_a_static_edge() {
616 let commits = together(0, 6, "a", "b");
618 let files = vec![path("a"), path("mid"), path("b")];
619 let links = StaticLinkIndex::from_links(&files, &[(0, 1), (1, 2)], &[]);
620
621 let analysis = analyze_change_history(&commits, &links, &ChangeCouplingSettings::default());
622 assert_eq!(analysis.hidden_pairs.len(), 1);
623 }
624
625 #[test]
626 fn bulk_commits_are_skipped_and_counted() {
627 let mut commits = together(0, 4, "a", "b");
628 let names: Vec<String> = (0..31).map(|i| format!("f{i}")).collect();
629 let mut bulk: Vec<(&str, u32)> = names.iter().map(|name| (name.as_str(), 1)).collect();
630 bulk.push(("a", 1));
631 bulk.push(("b", 1));
632 commits.push(commit(50, &bulk));
633 let mut all: Vec<&str> = names.iter().map(String::as_str).collect();
634 all.extend(["a", "b"]);
635
636 let analysis =
637 analyze_change_history(&commits, &index(&all), &ChangeCouplingSettings::default());
638 assert_eq!(analysis.commits_skipped, 1);
639 assert_eq!(analysis.commits_analyzed, 4);
640 assert!(
641 analysis.hidden_pairs.is_empty(),
642 "the bulk commit must not lift the pair to 5 shared revisions"
643 );
644 }
645
646 #[test]
647 fn files_outside_the_analyzed_set_do_not_count() {
648 let commits: Vec<ChurnCommit> = (0..5)
650 .map(|id| commit(id, &[("a", 2), ("b", 3), ("lock", 500)]))
651 .collect();
652 let analysis = analyze_change_history(
653 &commits,
654 &index(&["a", "b"]),
655 &ChangeCouplingSettings::default(),
656 );
657
658 assert_eq!(analysis.hidden_pairs.len(), 1);
659 let dispersion = analysis.dispersion[&path("a")];
660 assert!((dispersion.median_files_per_commit - 2.0).abs() < f64::EPSILON);
661 assert!((dispersion.median_lines_per_commit - 5.0).abs() < f64::EPSILON);
662 assert!(!analysis.dispersion.contains_key(&path("lock")));
663 }
664
665 #[test]
666 fn dispersion_is_the_median_over_the_commits_that_touch_the_file() {
667 let commits = vec![
668 commit(0, &[("a", 1)]),
669 commit(1, &[("a", 1), ("b", 1), ("c", 1)]),
670 commit(2, &[("a", 10), ("b", 10)]),
671 commit(3, &[("a", 1), ("b", 1), ("c", 1), ("d", 1)]),
672 ];
673 let analysis = analyze_change_history(
674 &commits,
675 &index(&["a", "b", "c", "d"]),
676 &ChangeCouplingSettings::default(),
677 );
678
679 let a = analysis.dispersion[&path("a")];
680 assert!((a.median_files_per_commit - 2.5).abs() < f64::EPSILON);
682 assert!((a.median_lines_per_commit - 3.5).abs() < f64::EPSILON);
683 let d = analysis.dispersion[&path("d")];
684 assert!((d.median_files_per_commit - 4.0).abs() < f64::EPSILON);
685 }
686
687 #[test]
688 fn custom_settings_lower_the_thresholds() {
689 let commits = together(0, 2, "a", "b");
690 let settings = ChangeCouplingSettings {
691 max_files_per_commit: 30,
692 min_revisions: 2,
693 min_shared_revisions: 2,
694 min_degree: 0.3,
695 };
696 let analysis = analyze_change_history(&commits, &index(&["a", "b"]), &settings);
697 assert_eq!(analysis.hidden_pairs.len(), 1);
698 }
699
700 #[test]
701 fn a_gap_needs_exactly_one_side_of_a_hidden_pair_in_the_change() {
702 let mut commits = together(0, 5, "a", "b");
703 commits.extend(together(10, 5, "c", "d"));
704 let analysis = analyze_change_history(
705 &commits,
706 &index(&["a", "b", "c", "d"]),
707 &ChangeCouplingSettings::default(),
708 );
709 let changed: FxHashSet<PathBuf> = [path("a"), path("c"), path("d")].into_iter().collect();
710
711 let gaps = co_change_gaps(&analysis, &changed);
712 assert_eq!(
713 gaps.len(),
714 1,
715 "c and d changed together, so only a misses b"
716 );
717 assert_eq!(gaps[0].changed, path("a"));
718 assert_eq!(gaps[0].partner, path("b"));
719 assert_eq!(gaps[0].shared_revisions, 5);
720 }
721
722 #[test]
723 fn pairs_sort_by_degree_then_shared_revisions_then_path() {
724 let mut commits = together(0, 6, "c", "d");
725 commits.extend(together(10, 5, "a", "b"));
726 commits.extend((20..25).map(|id| commit(id, &[("e", 1), ("f", 1)])));
727 commits.extend((30..35).map(|id| commit(id, &[("e", 1)])));
728 let analysis = analyze_change_history(
729 &commits,
730 &index(&["a", "b", "c", "d", "e", "f"]),
731 &ChangeCouplingSettings::default(),
732 );
733
734 let order: Vec<PathBuf> = analysis
735 .hidden_pairs
736 .iter()
737 .map(|pair| pair.path_a.clone())
738 .collect();
739 assert_eq!(order, vec![path("c"), path("a"), path("e")]);
740 assert!((analysis.hidden_pairs[2].degree - 0.67).abs() < f64::EPSILON);
741 }
742}