Skip to main content

lean_ctx_ext/core/community/
graph.rs

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