Skip to main content

lean_ctx/core/property_graph/
queries.rs

1//! Graph traversal queries: dependents, dependencies, impact analysis,
2//! dependency chains (BFS-based shortest path).
3//!
4//! All traversal queries support multi-edge traversal: imports, calls,
5//! exports, type_ref, tested_by, and more. Edge kinds are weighted
6//! for impact scoring.
7
8use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
9
10use rusqlite::{Connection, params};
11
12#[derive(Debug, Clone)]
13pub struct GraphQuery;
14
15#[derive(Debug, Clone)]
16pub struct ImpactResult {
17    pub root_file: String,
18    pub affected_files: Vec<String>,
19    /// Affected files reachable *only* through name-match guesses
20    /// (heuristic `calls` edges) — possibly not affected at all. Sorted.
21    pub weak_files: Vec<String>,
22    pub max_depth_reached: usize,
23    pub edges_traversed: usize,
24}
25
26#[derive(Debug, Clone)]
27pub struct DependencyChain {
28    pub path: Vec<String>,
29    pub depth: usize,
30}
31
32/// Edge kinds considered structural (code connectivity).
33const STRUCTURAL_EDGE_KINDS: &str = "'imports','calls','references','implements','extends','exports','type_ref','tested_by','module','cochange','sibling'";
34
35/// Weight multiplier per edge kind for impact scoring.
36pub fn edge_weight(kind: &str) -> f64 {
37    match kind {
38        "imports" => 1.0,
39        "calls" | "references" => 0.8,
40        "exports" | "implements" | "extends" => 0.7,
41        "module" => 0.6,
42        "type_ref" => 0.5,
43        "tested_by" => 0.4,
44        "cochange" => 0.35,
45        "defines" => 0.3,
46        "sibling" => 0.25,
47        "changed_in" => 0.2,
48        _ => 0.1,
49    }
50}
51
52/// Files that depend on `file_path` via structural edges (imports, calls, type_ref, etc.).
53pub(super) fn dependents(conn: &Connection, file_path: &str) -> anyhow::Result<Vec<String>> {
54    let sql = format!(
55        "SELECT DISTINCT p_src.path
56         FROM edges e
57         JOIN nodes n_src ON e.source_id = n_src.id
58         JOIN nodes n_tgt ON e.target_id = n_tgt.id
59         JOIN paths p_src ON p_src.id = n_src.file_id
60         JOIN paths p_tgt ON p_tgt.id = n_tgt.file_id
61         WHERE p_tgt.path = ?1
62           AND p_src.path != ?1
63           AND e.kind IN ({STRUCTURAL_EDGE_KINDS})"
64    );
65    let mut stmt = conn.prepare(&sql)?;
66
67    let mut results: Vec<String> = stmt
68        .query_map(params![file_path], |row| row.get(0))?
69        .filter_map(std::result::Result::ok)
70        .collect();
71
72    results.sort();
73    results.dedup();
74    Ok(results)
75}
76
77/// Files that `file_path` depends on via structural edges.
78pub(super) fn dependencies(conn: &Connection, file_path: &str) -> anyhow::Result<Vec<String>> {
79    let sql = format!(
80        "SELECT DISTINCT p_tgt.path
81         FROM edges e
82         JOIN nodes n_src ON e.source_id = n_src.id
83         JOIN nodes n_tgt ON e.target_id = n_tgt.id
84         JOIN paths p_src ON p_src.id = n_src.file_id
85         JOIN paths p_tgt ON p_tgt.id = n_tgt.file_id
86         WHERE p_src.path = ?1
87           AND p_tgt.path != ?1
88           AND e.kind IN ({STRUCTURAL_EDGE_KINDS})"
89    );
90    let mut stmt = conn.prepare(&sql)?;
91
92    let mut results: Vec<String> = stmt
93        .query_map(params![file_path], |row| row.get(0))?
94        .filter_map(std::result::Result::ok)
95        .collect();
96
97    results.sort();
98    results.dedup();
99    Ok(results)
100}
101
102/// Weighted BFS from `file_path` following reverse structural edges up to `max_depth`.
103/// Edge weights attenuate propagation: calls edges carry less impact than imports.
104/// Nodes only propagate when cumulative weight exceeds the threshold (0.1).
105pub(super) fn impact_analysis(
106    conn: &Connection,
107    file_path: &str,
108    max_depth: usize,
109) -> anyhow::Result<ImpactResult> {
110    // Graph node keys use canonical `/` separators (see the builder walk);
111    // accept native Windows input too.
112    let file_path = file_path.replace('\\', "/");
113    let file_path = file_path.as_str();
114    let reverse_graph = build_weighted_reverse_graph(conn)?;
115
116    let all = propagate(&reverse_graph, file_path, max_depth, false);
117    // Files also reachable over evidence-backed edges alone; the rest hang on
118    // name-match guesses only and are reported as such. A strong edge never
119    // weighs more than the pair's strongest edge overall, so the strong set
120    // is a subset of the full one.
121    let strong = propagate(&reverse_graph, file_path, max_depth, true);
122    let weak_files: Vec<String> = all.reached.difference(&strong.reached).cloned().collect();
123
124    Ok(ImpactResult {
125        root_file: file_path.to_string(),
126        affected_files: all.reached.into_iter().collect(),
127        weak_files,
128        max_depth_reached: all.max_depth_reached,
129        edges_traversed: all.edges_traversed,
130    })
131}
132
133struct Propagation {
134    reached: BTreeSet<String>,
135    max_depth_reached: usize,
136    edges_traversed: usize,
137}
138
139/// Weighted reverse propagation from `root` (excluded from the result) up
140/// to `max_depth` hops; a file is reached when some path to it keeps a
141/// cumulative weight ≥ 0.1. Exact, not first-come: a heavier path found
142/// later still propagates, unless an equally heavy or heavier one already
143/// arrived at the same or a shallower depth. Processing order is sorted, so
144/// the result is deterministic. With `strong_only`, name-match-only edges
145/// are not followed.
146fn propagate(
147    reverse_graph: &ReverseGraph,
148    root: &str,
149    max_depth: usize,
150    strong_only: bool,
151) -> Propagation {
152    const PROPAGATION_THRESHOLD: f64 = 0.1;
153    // Heaviest weight per file over all depths processed so far.
154    let mut best: HashMap<&str, f64> = HashMap::from([(root, 1.0)]);
155    let mut first_depth: BTreeMap<&str, usize> = BTreeMap::new();
156    let mut layer: BTreeMap<&str, f64> = BTreeMap::from([(root, 1.0)]);
157    let mut edges_traversed = 0;
158
159    for depth in 1..=max_depth {
160        let mut next: BTreeMap<&str, f64> = BTreeMap::new();
161        for (file, weight) in &layer {
162            for dep in reverse_graph.get(*file).into_iter().flatten() {
163                let Some(edge_weight) = (if strong_only {
164                    dep.strong_weight
165                } else {
166                    Some(dep.weight)
167                }) else {
168                    continue;
169                };
170                edges_traversed += 1;
171                let propagated = weight * edge_weight;
172                if propagated < PROPAGATION_THRESHOLD
173                    || best
174                        .get(dep.file.as_str())
175                        .is_some_and(|b| *b >= propagated)
176                {
177                    continue;
178                }
179                let slot = next.entry(dep.file.as_str()).or_insert(0.0);
180                *slot = slot.max(propagated);
181            }
182        }
183        if next.is_empty() {
184            break;
185        }
186        for (file, weight) in &next {
187            best.insert(file, *weight);
188            first_depth.entry(file).or_insert(depth);
189        }
190        layer = next;
191    }
192    first_depth.remove(root);
193    Propagation {
194        max_depth_reached: first_depth.values().copied().max().unwrap_or(0),
195        reached: first_depth.into_keys().map(str::to_string).collect(),
196        edges_traversed,
197    }
198}
199
200/// BFS shortest path from `from` to `to` following structural edges.
201pub(super) fn dependency_chain(
202    conn: &Connection,
203    from: &str,
204    to: &str,
205) -> anyhow::Result<Option<DependencyChain>> {
206    // Same canonicalization as `impact_analysis`.
207    let from = from.replace('\\', "/");
208    let to = to.replace('\\', "/");
209    let from = from.as_str();
210    let to = to.as_str();
211    let forward_graph = build_forward_graph(conn)?;
212
213    let mut visited: HashSet<String> = HashSet::new();
214    let mut parent: HashMap<String, String> = HashMap::new();
215    let mut queue: VecDeque<String> = VecDeque::new();
216
217    visited.insert(from.to_string());
218    queue.push_back(from.to_string());
219
220    while let Some(current) = queue.pop_front() {
221        if current == to {
222            let mut path = vec![to.to_string()];
223            let mut cursor = to.to_string();
224            while let Some(prev) = parent.get(&cursor) {
225                path.push(prev.clone());
226                cursor = prev.clone();
227            }
228            path.reverse();
229            let depth = path.len() - 1;
230            return Ok(Some(DependencyChain { path, depth }));
231        }
232
233        if let Some(deps) = forward_graph.get(&current) {
234            for dep in deps {
235                if visited.insert(dep.clone()) {
236                    parent.insert(dep.clone(), current.clone());
237                    queue.push_back(dep.clone());
238                }
239            }
240        }
241    }
242
243    Ok(None)
244}
245
246/// Related files for a given path: direct neighbors via any structural edge,
247/// sorted by edge weight (strongest relationship first). Returns (path, weight) pairs.
248pub fn related_files(
249    conn: &Connection,
250    file_path: &str,
251    limit: usize,
252) -> anyhow::Result<Vec<(String, f64)>> {
253    let sql = format!(
254        "SELECT p_other.path, e.kind, e.metadata
255         FROM edges e
256         JOIN nodes n_self ON (e.source_id = n_self.id OR e.target_id = n_self.id)
257         JOIN nodes n_other ON (
258             (e.source_id = n_other.id AND e.target_id = n_self.id)
259             OR (e.target_id = n_other.id AND e.source_id = n_self.id)
260         )
261         JOIN paths p_self ON p_self.id = n_self.file_id
262         JOIN paths p_other ON p_other.id = n_other.file_id
263         WHERE p_self.path = ?1
264           AND p_other.path != ?1
265           AND e.kind IN ({STRUCTURAL_EDGE_KINDS})"
266    );
267    let mut stmt = conn.prepare(&sql)?;
268
269    // One relationship can be stored several times — file→file plus
270    // symbol→symbol `calls` edges for the same call. Count each (file, kind)
271    // relationship once, at its strongest evidence, so finer-grained edges
272    // cannot inflate a neighbour's score.
273    // Ordered maps: floating-point sums must accumulate in a fixed order so
274    // equal relationships always yield bit-identical scores (#498).
275    let mut strongest: BTreeMap<(String, String), f64> = BTreeMap::new();
276    let rows = stmt.query_map(params![file_path], |row| {
277        Ok((
278            row.get::<_, String>(0)?,
279            row.get::<_, String>(1)?,
280            row.get::<_, Option<String>>(2)?,
281        ))
282    })?;
283    for row in rows {
284        let (path, kind, metadata) = row?;
285        let w = evidence_weight(&kind, metadata.as_deref());
286        let slot = strongest.entry((path, kind)).or_insert(0.0);
287        if w > *slot {
288            *slot = w;
289        }
290    }
291
292    let mut scores: BTreeMap<String, f64> = BTreeMap::new();
293    for ((path, _), w) in strongest {
294        *scores.entry(path).or_default() += w;
295    }
296
297    let mut results: Vec<(String, f64)> = scores.into_iter().collect();
298    // Equal weights are common; break ties by path so the cut below does not
299    // depend on hash order (planning must be identical across processes).
300    results.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
301    results.truncate(limit);
302    Ok(results)
303}
304
305/// Kind weight scaled by the edge's evidence grade (see
306/// [`crate::core::semantic::EdgeEvidence`]); edges without evidence keep
307/// their full kind weight.
308pub(super) fn evidence_weight(kind: &str, metadata: Option<&str>) -> f64 {
309    edge_weight(kind) * crate::core::semantic::EdgeEvidence::weight_factor_of(metadata)
310}
311
312/// Graph connectivity stats for a file: incoming/outgoing edge counts by kind.
313pub fn file_connectivity(
314    conn: &Connection,
315    file_path: &str,
316) -> anyhow::Result<HashMap<String, (usize, usize)>> {
317    let mut result: HashMap<String, (usize, usize)> = HashMap::new();
318
319    let mut stmt_out = conn.prepare(
320        "SELECT e.kind, COUNT(*)
321         FROM edges e JOIN nodes n ON e.source_id = n.id
322         JOIN paths p ON p.id = n.file_id
323         WHERE p.path = ?1
324         GROUP BY e.kind",
325    )?;
326    let rows = stmt_out.query_map(params![file_path], |row| {
327        Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
328    })?;
329    for row in rows {
330        let (kind, count) = row?;
331        result.entry(kind).or_insert((0, 0)).0 = count as usize;
332    }
333
334    let mut stmt_in = conn.prepare(
335        "SELECT e.kind, COUNT(*)
336         FROM edges e JOIN nodes n ON e.target_id = n.id
337         JOIN paths p ON p.id = n.file_id
338         WHERE p.path = ?1
339         GROUP BY e.kind",
340    )?;
341    let rows = stmt_in.query_map(params![file_path], |row| {
342        Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
343    })?;
344    for row in rows {
345        let (kind, count) = row?;
346        result.entry(kind).or_insert((0, 0)).1 = count as usize;
347    }
348
349    Ok(result)
350}
351
352/// A file depending on another, as seen from the dependency.
353struct Dependent {
354    file: String,
355    /// Strongest edge of the pair.
356    weight: f64,
357    /// Strongest edge of the pair that is not a name-match guess, if any.
358    strong_weight: Option<f64>,
359}
360
361/// Dependency → its dependents, both sorted by path.
362type ReverseGraph = BTreeMap<String, Vec<Dependent>>;
363
364fn build_weighted_reverse_graph(conn: &Connection) -> anyhow::Result<ReverseGraph> {
365    let sql = format!(
366        "SELECT p_tgt.path, p_src.path, e.kind, e.metadata
367         FROM edges e
368         JOIN nodes n_src ON e.source_id = n_src.id
369         JOIN nodes n_tgt ON e.target_id = n_tgt.id
370         JOIN paths p_src ON p_src.id = n_src.file_id
371         JOIN paths p_tgt ON p_tgt.id = n_tgt.file_id
372         WHERE e.kind IN ({STRUCTURAL_EDGE_KINDS})
373           AND p_src.path != p_tgt.path"
374    );
375    let mut stmt = conn.prepare(&sql)?;
376
377    let mut graph: BTreeMap<String, BTreeMap<String, (f64, Option<f64>)>> = BTreeMap::new();
378    let rows = stmt.query_map([], |row| {
379        Ok((
380            row.get::<_, String>(0)?,
381            row.get::<_, String>(1)?,
382            row.get::<_, String>(2)?,
383            row.get::<_, Option<String>>(3)?,
384        ))
385    })?;
386
387    for row in rows {
388        let (target, source, kind, metadata) = row?;
389        let w = evidence_weight(&kind, metadata.as_deref());
390        // Only a name-match guess is weak; scope-bound, verified and
391        // non-call structural edges (imports, type refs) are facts.
392        let strong = crate::core::semantic::EdgeEvidence::from_metadata(metadata.as_deref())
393            .is_none_or(|e| e.grade != crate::core::semantic::EvidenceGrade::HeuristicStructural);
394        let entry = graph
395            .entry(target)
396            .or_default()
397            .entry(source)
398            .or_insert((0.0, None));
399        entry.0 = entry.0.max(w);
400        if strong {
401            entry.1 = Some(entry.1.map_or(w, |s| s.max(w)));
402        }
403    }
404
405    Ok(graph
406        .into_iter()
407        .map(|(k, v)| {
408            (
409                k,
410                v.into_iter()
411                    .map(|(file, (weight, strong_weight))| Dependent {
412                        file,
413                        weight,
414                        strong_weight,
415                    })
416                    .collect(),
417            )
418        })
419        .collect())
420}
421
422fn build_forward_graph(conn: &Connection) -> anyhow::Result<HashMap<String, Vec<String>>> {
423    let sql = format!(
424        "SELECT DISTINCT p_src.path, p_tgt.path
425         FROM edges e
426         JOIN nodes n_src ON e.source_id = n_src.id
427         JOIN nodes n_tgt ON e.target_id = n_tgt.id
428         JOIN paths p_src ON p_src.id = n_src.file_id
429         JOIN paths p_tgt ON p_tgt.id = n_tgt.file_id
430         WHERE e.kind IN ({STRUCTURAL_EDGE_KINDS})
431           AND p_src.path != p_tgt.path"
432    );
433    let mut stmt = conn.prepare(&sql)?;
434
435    let mut graph: HashMap<String, Vec<String>> = HashMap::new();
436    let rows = stmt.query_map([], |row| {
437        Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
438    })?;
439
440    for row in rows {
441        let (source, target) = row?;
442        graph.entry(source).or_default().push(target);
443    }
444
445    for deps in graph.values_mut() {
446        deps.sort();
447        deps.dedup();
448    }
449    Ok(graph)
450}