Skip to main content

lean_ctx_ext/core/graph_analysis/
surprising.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Surprising connections: dependency edges that bridge otherwise-unrelated
3//! parts of the codebase.
4//!
5//! Composite score per edge `(u, v)`:
6//!   `(1 - jaccard(N(u), N(v))) * cross_community_factor * ln(1 + deg(u) + deg(v))`
7//!
8//! High score = the two files share few neighbours (low overlap), live in
9//! different communities, and are non-trivially connected — i.e. an unexpected
10//! coupling worth a human's attention (graphify-style).
11
12use std::collections::{HashMap, HashSet};
13
14use serde::Serialize;
15
16use super::dependency_edges;
17use crate::core::graph_provider::EdgeInfo;
18
19/// An unexpected coupling between two files.
20#[derive(Debug, Clone, Serialize, PartialEq)]
21pub struct SurprisingConnection {
22    pub from: String,
23    pub to: String,
24    pub score: f64,
25    pub cross_community: bool,
26    pub shared_neighbors: usize,
27}
28
29/// Returns the top `limit` surprising connections, highest score first.
30/// Deterministic. `community` maps file path → community id (may be partial).
31pub fn find_surprising_connections(
32    edges: &[EdgeInfo],
33    community: &HashMap<String, usize>,
34    limit: usize,
35) -> Vec<SurprisingConnection> {
36    let deps = dependency_edges(edges);
37    if deps.is_empty() {
38        return Vec::new();
39    }
40
41    // Undirected neighbour sets over dependency edges.
42    let mut adj: HashMap<&str, HashSet<&str>> = HashMap::new();
43    for (u, v) in &deps {
44        adj.entry(*u).or_default().insert(*v);
45        adj.entry(*v).or_default().insert(*u);
46    }
47
48    let empty: HashSet<&str> = HashSet::new();
49    let mut seen: HashSet<(&str, &str)> = HashSet::new();
50    let mut out: Vec<SurprisingConnection> = Vec::new();
51
52    for (u, v) in &deps {
53        // Canonical undirected key so a↔b is scored once.
54        let key = if u <= v { (*u, *v) } else { (*v, *u) };
55        if !seen.insert(key) {
56            continue;
57        }
58
59        let nu = adj.get(*u).unwrap_or(&empty);
60        let nv = adj.get(*v).unwrap_or(&empty);
61        if nu.len() < 2 || nv.len() < 2 {
62            continue; // trivial leaf edge: not "surprising", just sparse
63        }
64
65        let shared = nu
66            .intersection(nv)
67            .filter(|n| **n != *u && **n != *v)
68            .count();
69        let mut union: HashSet<&str> = nu.iter().copied().collect();
70        union.extend(nv.iter().copied());
71        union.remove(*u);
72        union.remove(*v);
73        let union_len = union.len().max(1);
74        let jaccard = shared as f64 / union_len as f64;
75
76        let cross = match (community.get(*u), community.get(*v)) {
77            (Some(a), Some(b)) => a != b,
78            _ => true,
79        };
80
81        let deg = (nu.len() + nv.len()) as f64;
82        let score = (1.0 - jaccard) * (if cross { 1.0 } else { 0.35 }) * (1.0 + deg).ln();
83
84        out.push(SurprisingConnection {
85            from: (*u).to_string(),
86            to: (*v).to_string(),
87            score: (score * 1000.0).round() / 1000.0,
88            cross_community: cross,
89            shared_neighbors: shared,
90        });
91    }
92
93    out.sort_by(|a, b| {
94        b.score
95            .partial_cmp(&a.score)
96            .unwrap_or(std::cmp::Ordering::Equal)
97            .then_with(|| a.from.cmp(&b.from))
98            .then_with(|| a.to.cmp(&b.to))
99    });
100    out.truncate(limit);
101    out
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    fn e(from: &str, to: &str) -> EdgeInfo {
109        EdgeInfo {
110            from: from.into(),
111            to: to.into(),
112            kind: "import".into(),
113            weight: 1.0,
114        }
115    }
116
117    #[test]
118    fn bridge_edge_ranks_above_intra_cluster_edge() {
119        // Two triangles {a,b,c} and {x,y,z}, joined by a single bridge c<->x.
120        let edges = vec![
121            e("a", "b"),
122            e("b", "c"),
123            e("a", "c"),
124            e("x", "y"),
125            e("y", "z"),
126            e("x", "z"),
127            e("c", "x"), // the surprising bridge
128        ];
129        let mut community = HashMap::new();
130        for n in ["a", "b", "c"] {
131            community.insert(n.to_string(), 0);
132        }
133        for n in ["x", "y", "z"] {
134            community.insert(n.to_string(), 1);
135        }
136
137        let surprising = find_surprising_connections(&edges, &community, 10);
138        assert!(!surprising.is_empty(), "`surprising` is empty");
139        let top = &surprising[0];
140        assert_eq!((top.from.as_str(), top.to.as_str()), ("c", "x"));
141        assert!(top.cross_community);
142    }
143
144    #[test]
145    fn empty_without_dependency_edges() {
146        let edges = vec![EdgeInfo {
147            from: "a".into(),
148            to: "b".into(),
149            kind: "sibling".into(),
150            weight: 1.0,
151        }];
152        {
153            let found = &find_surprising_connections(&edges, &HashMap::new(), 10);
154            assert!(found.is_empty(), "{found:?}");
155        }
156    }
157}