Skip to main content

lean_ctx/core/community/
graph.rs

1//! Undirected, weighted adjacency representation of the file-level code graph.
2//!
3//! Parallel edges are merged (weights summed) and the adjacency is symmetric so
4//! modularity and connectivity computations are correct. The same structure is
5//! built from the PropertyGraph (SQLite) and from any [`GraphProvider`], which
6//! keeps community detection storage-agnostic.
7
8use std::collections::HashMap;
9
10use rusqlite::Connection;
11
12use crate::core::graph_provider::GraphProvider;
13
14/// Edge weight by semantic kind. Calls bind tighter than plain imports; purely
15/// structural `defines`/`exports` edges are weak ties. Accepts both the
16/// PropertyGraph kind spelling (`imports`, `calls`) and the graph-index spelling
17/// (`import`, `call`) so either backend yields identical weights.
18pub fn edge_weight(kind: &str) -> f64 {
19    match kind {
20        "imports" | "import" => 1.0,
21        "calls" | "call" => 1.5,
22        "type_ref" | "type" => 0.8,
23        "defines" | "exports" | "export" => 0.3,
24        _ => 0.5,
25    }
26}
27
28pub struct AdjGraph {
29    pub node_ids: Vec<String>,
30    #[cfg_attr(not(test), allow(dead_code))] // read by community integration tests
31    pub node_to_idx: HashMap<String, usize>,
32    /// Symmetric adjacency: every undirected edge `{i,j}` appears as `(i→j)` in
33    /// `adj[i]` and `(j→i)` in `adj[j]`. Neighbor lists are sorted by index.
34    pub adj: Vec<Vec<(usize, f64)>>,
35    pub degree: Vec<f64>,
36    /// Sum of unique undirected edge weights (each edge counted once).
37    pub total_weight: f64,
38}
39
40impl AdjGraph {
41    pub fn node_count(&self) -> usize {
42        self.node_ids.len()
43    }
44
45    /// Number of unique undirected edges.
46    pub fn edge_count(&self) -> usize {
47        self.adj.iter().map(Vec::len).sum::<usize>() / 2
48    }
49
50    /// Build from already-resolved index pairs. `raw` holds `(from, to, weight)`
51    /// in node-index space; self-loops and out-of-range endpoints are dropped and
52    /// duplicate/parallel edges are merged by summing weights.
53    fn from_pairs(node_ids: Vec<String>, raw: &[(usize, usize, f64)]) -> Self {
54        let n = node_ids.len();
55        let mut node_to_idx = HashMap::with_capacity(n);
56        for (idx, name) in node_ids.iter().enumerate() {
57            node_to_idx.insert(name.clone(), idx);
58        }
59
60        let mut merged: HashMap<(usize, usize), f64> = HashMap::new();
61        for &(a, b, w) in raw {
62            if a == b || a >= n || b >= n {
63                continue;
64            }
65            let key = if a < b { (a, b) } else { (b, a) };
66            *merged.entry(key).or_default() += w;
67        }
68
69        let mut adj: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
70        let mut degree = vec![0.0; n];
71        let mut total_weight = 0.0;
72
73        let mut entries: Vec<((usize, usize), f64)> = merged.into_iter().collect();
74        entries.sort_by_key(|e| e.0);
75        for ((i, j), w) in entries {
76            adj[i].push((j, w));
77            adj[j].push((i, w));
78            degree[i] += w;
79            degree[j] += w;
80            total_weight += w;
81        }
82        for list in &mut adj {
83            list.sort_by_key(|e| e.0);
84        }
85
86        Self {
87            node_ids,
88            node_to_idx,
89            adj,
90            degree,
91            total_weight,
92        }
93    }
94
95    pub fn from_property_graph(conn: &Connection) -> Self {
96        let files = query_files(conn);
97        let idx: HashMap<&str, usize> = files
98            .iter()
99            .enumerate()
100            .map(|(i, f)| (f.as_str(), i))
101            .collect();
102        let pairs: Vec<(usize, usize, f64)> = query_file_edges(conn)
103            .iter()
104            .filter_map(|(a, b, w)| Some((*idx.get(a.as_str())?, *idx.get(b.as_str())?, *w)))
105            .collect();
106        Self::from_pairs(files, &pairs)
107    }
108
109    pub fn from_provider(gp: &GraphProvider) -> Self {
110        let mut files = gp.file_paths();
111        files.sort();
112        files.dedup();
113        let idx: HashMap<&str, usize> = files
114            .iter()
115            .enumerate()
116            .map(|(i, f)| (f.as_str(), i))
117            .collect();
118        let pairs: Vec<(usize, usize, f64)> = gp
119            .edges()
120            .iter()
121            .filter_map(|e| {
122                let i = *idx.get(e.from.as_str())?;
123                let j = *idx.get(e.to.as_str())?;
124                Some((i, j, edge_weight(&e.kind)))
125            })
126            .collect();
127        Self::from_pairs(files, &pairs)
128    }
129
130    /// Induced subgraph over `members` (global node indices). Returns the
131    /// subgraph plus a `local → global` index map for translating results back.
132    pub fn induced_subgraph(&self, members: &[usize]) -> (AdjGraph, Vec<usize>) {
133        let mut local_of: HashMap<usize, usize> = HashMap::with_capacity(members.len());
134        let mut node_ids = Vec::with_capacity(members.len());
135        let mut local_to_global = Vec::with_capacity(members.len());
136        for &g in members {
137            local_of.insert(g, node_ids.len());
138            node_ids.push(self.node_ids[g].clone());
139            local_to_global.push(g);
140        }
141        let mut pairs = Vec::new();
142        for &g in members {
143            let li = local_of[&g];
144            for &(h, w) in &self.adj[g] {
145                if let Some(&lj) = local_of.get(&h)
146                    && li < lj
147                {
148                    pairs.push((li, lj, w));
149                }
150            }
151        }
152        (AdjGraph::from_pairs(node_ids, &pairs), local_to_global)
153    }
154
155    #[cfg(test)]
156    pub fn from_test_edges(node_ids: Vec<String>, edges: &[(usize, usize, &str)]) -> Self {
157        let pairs: Vec<(usize, usize, f64)> = edges
158            .iter()
159            .map(|&(a, b, kind)| (a, b, edge_weight(kind)))
160            .collect();
161        Self::from_pairs(node_ids, &pairs)
162    }
163}
164
165/// Internal vs. external edge endpoints for a community (symmetric adjacency, so
166/// each internal undirected edge contributes twice — the cohesion ratio is
167/// unaffected).
168pub fn edge_counts(graph: &AdjGraph, members: &[usize]) -> (usize, usize) {
169    let member_set: std::collections::HashSet<usize> = members.iter().copied().collect();
170    let mut internal = 0usize;
171    let mut external = 0usize;
172    for &i in members {
173        for &(j, _) in &graph.adj[i] {
174            if member_set.contains(&j) {
175                internal += 1;
176            } else {
177                external += 1;
178            }
179        }
180    }
181    (internal, external)
182}
183
184/// Fraction of a community's incident edges that stay inside it (`0.0..=1.0`).
185pub fn cohesion_of(graph: &AdjGraph, members: &[usize]) -> f64 {
186    let (internal, external) = edge_counts(graph, members);
187    let total = (internal + external).max(1) as f64;
188    internal as f64 / total
189}
190
191fn query_files(conn: &Connection) -> Vec<String> {
192    let Ok(mut stmt) = conn.prepare(
193        "SELECT DISTINCT p.path
194         FROM nodes n JOIN paths p ON p.id = n.file_id
195         WHERE n.kind = 'file' ORDER BY p.path",
196    ) else {
197        tracing::warn!("community: failed to prepare file query");
198        return Vec::new();
199    };
200    let mut files = Vec::new();
201    match stmt.query_map([], |row| row.get::<_, String>(0)) {
202        Ok(rows) => files.extend(rows.filter_map(std::result::Result::ok)),
203        Err(e) => tracing::warn!("community: file query failed: {e}"),
204    }
205    files
206}
207
208fn query_file_edges(conn: &Connection) -> Vec<(String, String, f64)> {
209    let sql = "
210        SELECT DISTINCT p1.path, p2.path, e.kind
211        FROM edges e
212        JOIN nodes n1 ON e.source_id = n1.id
213        JOIN nodes n2 ON e.target_id = n2.id
214        JOIN paths p1 ON p1.id = n1.file_id
215        JOIN paths p2 ON p2.id = n2.file_id
216        WHERE n1.kind = 'file' AND n2.kind = 'file'
217          AND n1.file_id != n2.file_id
218        ORDER BY p1.path, p2.path
219    ";
220    let Ok(mut stmt) = conn.prepare(sql) else {
221        tracing::warn!("community: failed to prepare edge query");
222        return Vec::new();
223    };
224    let mut edges = Vec::new();
225    match stmt.query_map([], |row| {
226        Ok((
227            row.get::<_, String>(0)?,
228            row.get::<_, String>(1)?,
229            row.get::<_, String>(2)?,
230        ))
231    }) {
232        Ok(rows) => edges.extend(
233            rows.filter_map(std::result::Result::ok)
234                .map(|(a, b, kind)| (a, b, edge_weight(&kind))),
235        ),
236        Err(e) => tracing::warn!("community: edge query failed: {e}"),
237    }
238    edges
239}