Skip to main content

lean_ctx_ext/core/graph_analysis/
god_nodes.rs

1// SPDX-License-Identifier: Apache-2.0
2//! God-Nodes: the most connected abstractions in the dependency graph.
3
4use std::collections::{HashMap, HashSet};
5
6use serde::Serialize;
7
8use super::dependency_edges;
9use crate::core::graph_provider::EdgeInfo;
10
11/// A highly connected file in the dependency graph.
12#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
13pub struct GodNode {
14    pub path: String,
15    /// Files that depend on this one (fan-in).
16    pub in_degree: usize,
17    /// Files this one depends on (fan-out).
18    pub out_degree: usize,
19    /// `in_degree + out_degree`.
20    pub degree: usize,
21}
22
23/// Ranks files by total dependency degree (fan-in + fan-out) and returns the top
24/// `limit`. Deterministic: ties broken by path so the output is stable across
25/// rebuilds.
26pub fn compute_god_nodes(edges: &[EdgeInfo], limit: usize) -> Vec<GodNode> {
27    let deps = dependency_edges(edges);
28    let mut incoming: HashMap<&str, usize> = HashMap::new();
29    let mut outgoing: HashMap<&str, usize> = HashMap::new();
30    let mut nodes: HashSet<&str> = HashSet::new();
31
32    for (from, to) in &deps {
33        *outgoing.entry(*from).or_default() += 1;
34        *incoming.entry(*to).or_default() += 1;
35        nodes.insert(*from);
36        nodes.insert(*to);
37    }
38
39    let mut ranked: Vec<GodNode> = nodes
40        .into_iter()
41        .map(|n| {
42            let in_degree = incoming.get(n).copied().unwrap_or(0);
43            let out_degree = outgoing.get(n).copied().unwrap_or(0);
44            GodNode {
45                path: n.to_string(),
46                in_degree,
47                out_degree,
48                degree: in_degree + out_degree,
49            }
50        })
51        .collect();
52
53    ranked.sort_by(|a, b| b.degree.cmp(&a.degree).then_with(|| a.path.cmp(&b.path)));
54    ranked.truncate(limit);
55    ranked
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    fn e(from: &str, to: &str, kind: &str) -> EdgeInfo {
63        EdgeInfo {
64            from: from.into(),
65            to: to.into(),
66            kind: kind.into(),
67            weight: 1.0,
68        }
69    }
70
71    #[test]
72    fn ranks_by_total_degree() {
73        let edges = vec![
74            e("a.rs", "b.rs", "import"),
75            e("a.rs", "c.rs", "import"),
76            e("d.rs", "a.rs", "import"),
77        ];
78        let god = compute_god_nodes(&edges, 10);
79        assert_eq!(god[0].path, "a.rs");
80        assert_eq!(god[0].out_degree, 2);
81        assert_eq!(god[0].in_degree, 1);
82        assert_eq!(god[0].degree, 3);
83    }
84
85    #[test]
86    fn ignores_heuristic_edges() {
87        // sibling / cochange are co-location heuristics, not dependencies.
88        let edges = vec![e("a.rs", "b.rs", "sibling"), e("a.rs", "c.rs", "cochange")];
89        {
90            let found = &compute_god_nodes(&edges, 10);
91            assert!(found.is_empty(), "{found:?}");
92        }
93    }
94
95    #[test]
96    fn respects_limit_and_is_deterministic() {
97        let edges = vec![
98            e("a.rs", "x.rs", "import"),
99            e("b.rs", "x.rs", "import"),
100            e("c.rs", "x.rs", "import"),
101        ];
102        let god = compute_god_nodes(&edges, 2);
103        assert_eq!(god.len(), 2);
104        // x.rs has degree 3 (top); next are a/b/c with degree 1, tie-broken by path.
105        assert_eq!(god[0].path, "x.rs");
106        assert_eq!(god[1].path, "a.rs");
107    }
108}