Skip to main content

arbor_graph/
graph.rs

1//! Core graph data structure.
2//!
3//! The ArborGraph wraps petgraph and adds indexes for fast lookups.
4//! It's the central data structure that everything else works with.
5
6use crate::edge::{Edge, EdgeKind, GraphEdge};
7use crate::search_index::SearchIndex;
8use arbor_core::CodeNode;
9use petgraph::stable_graph::{NodeIndex, StableDiGraph};
10use petgraph::visit::{EdgeRef, IntoEdgeReferences}; // For edge_references
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13
14/// Unique identifier for a node in the graph.
15pub type NodeId = NodeIndex;
16
17/// The code relationship graph.
18///
19/// This is the heart of Arbor. It stores all code entities as nodes
20/// and their relationships as edges, with indexes for fast access.
21#[derive(Debug, Serialize, Deserialize)]
22pub struct ArborGraph {
23    /// The underlying petgraph graph.
24    pub(crate) graph: StableDiGraph<CodeNode, Edge>,
25
26    /// Maps string IDs to graph node indexes.
27    id_index: HashMap<String, NodeId>,
28
29    /// Maps node names to node IDs (for search).
30    name_index: HashMap<String, Vec<NodeId>>,
31
32    /// Maps file paths to node IDs (for incremental updates).
33    file_index: HashMap<String, Vec<NodeId>>,
34
35    /// Centrality scores for ranking.
36    centrality: HashMap<NodeId, f64>,
37
38    /// Search index for fast substring queries.
39    #[serde(skip)]
40    search_index: SearchIndex,
41}
42
43impl Default for ArborGraph {
44    fn default() -> Self {
45        Self::new()
46    }
47}
48
49impl ArborGraph {
50    /// Creates a new empty graph.
51    pub fn new() -> Self {
52        Self {
53            graph: StableDiGraph::new(),
54            id_index: HashMap::new(),
55            name_index: HashMap::new(),
56            file_index: HashMap::new(),
57            centrality: HashMap::new(),
58            search_index: SearchIndex::new(),
59        }
60    }
61
62    /// Rebuilds the search index from existing graph nodes.
63    /// Call after deserialization since search_index is not serialized.
64    pub fn rebuild_search_index(&mut self) {
65        self.search_index = SearchIndex::new();
66        for index in self.graph.node_indices() {
67            if let Some(node) = self.graph.node_weight(index) {
68                self.search_index.insert(&node.name, index);
69            }
70        }
71    }
72
73    /// Adds a code node to the graph.
74    ///
75    /// Returns the node's index for adding edges later.
76    pub fn add_node(&mut self, node: CodeNode) -> NodeId {
77        let id = node.id.clone();
78        let name = node.name.clone();
79        let file = node.file.clone();
80
81        let index = self.graph.add_node(node);
82
83        // Update indexes
84        self.id_index.insert(id, index);
85        self.name_index.entry(name.clone()).or_default().push(index);
86        self.file_index.entry(file).or_default().push(index);
87        self.search_index.insert(&name, index);
88
89        index
90    }
91
92    /// Adds an edge between two nodes.
93    pub fn add_edge(&mut self, from: NodeId, to: NodeId, edge: Edge) {
94        self.graph.add_edge(from, to, edge);
95    }
96
97    /// Gets a node by its string ID.
98    pub fn get_by_id(&self, id: &str) -> Option<&CodeNode> {
99        let index = self.id_index.get(id)?;
100        self.graph.node_weight(*index)
101    }
102
103    /// Gets a node by its graph index.
104    pub fn get(&self, index: NodeId) -> Option<&CodeNode> {
105        self.graph.node_weight(index)
106    }
107
108    /// Finds all nodes with a given name.
109    pub fn find_by_name(&self, name: &str) -> Vec<&CodeNode> {
110        self.name_index
111            .get(name)
112            .map(|indexes| {
113                indexes
114                    .iter()
115                    .filter_map(|idx| self.graph.node_weight(*idx))
116                    .collect()
117            })
118            .unwrap_or_default()
119    }
120
121    /// Finds all nodes in a file.
122    pub fn find_by_file(&self, file: &str) -> Vec<&CodeNode> {
123        self.file_index
124            .get(file)
125            .map(|indexes| {
126                indexes
127                    .iter()
128                    .filter_map(|idx| self.graph.node_weight(*idx))
129                    .collect()
130            })
131            .unwrap_or_default()
132    }
133
134    /// Searches for nodes whose name contains the query.
135    ///
136    /// Uses the search index for fast O(k) lookups where k is the number of matches,
137    /// instead of O(n) linear scan over all nodes.
138    pub fn search(&self, query: &str) -> Vec<&CodeNode> {
139        self.search_index
140            .search(query)
141            .iter()
142            .filter_map(|id| self.graph.node_weight(*id))
143            .collect()
144    }
145
146    /// Gets nodes that call the given node.
147    pub fn get_callers(&self, index: NodeId) -> Vec<&CodeNode> {
148        self.graph
149            .neighbors_directed(index, petgraph::Direction::Incoming)
150            .filter_map(|idx| {
151                // Check if the edge is a call
152                let edge_idx = self.graph.find_edge(idx, index)?;
153                let edge = self.graph.edge_weight(edge_idx)?;
154                if edge.kind == EdgeKind::Calls {
155                    self.graph.node_weight(idx)
156                } else {
157                    None
158                }
159            })
160            .collect()
161    }
162
163    /// Gets nodes that this node calls.
164    pub fn get_callees(&self, index: NodeId) -> Vec<&CodeNode> {
165        self.graph
166            .neighbors_directed(index, petgraph::Direction::Outgoing)
167            .filter_map(|idx| {
168                let edge_idx = self.graph.find_edge(index, idx)?;
169                let edge = self.graph.edge_weight(edge_idx)?;
170                if edge.kind == EdgeKind::Calls {
171                    self.graph.node_weight(idx)
172                } else {
173                    None
174                }
175            })
176            .collect()
177    }
178
179    /// Gets all nodes that depend on the given node (directly or transitively).
180    pub fn get_dependents(&self, index: NodeId, max_depth: usize) -> Vec<(NodeId, usize)> {
181        let mut result = Vec::new();
182        let mut visited = std::collections::HashSet::new();
183        let mut queue = vec![(index, 0usize)];
184
185        while let Some((current, depth)) = queue.pop() {
186            if depth > max_depth || visited.contains(&current) {
187                continue;
188            }
189            visited.insert(current);
190
191            if current != index {
192                result.push((current, depth));
193            }
194
195            // Get incoming edges (callers)
196            for neighbor in self
197                .graph
198                .neighbors_directed(current, petgraph::Direction::Incoming)
199            {
200                if !visited.contains(&neighbor) {
201                    queue.push((neighbor, depth + 1));
202                }
203            }
204        }
205
206        result
207    }
208
209    /// Removes all nodes from a file. Used for incremental updates.
210    pub fn remove_file(&mut self, file: &str) {
211        if let Some(indexes) = self.file_index.remove(file) {
212            for index in indexes {
213                if let Some(node) = self.graph.node_weight(index) {
214                    // Remove from name index
215                    let name = node.name.clone();
216                    if let Some(name_list) = self.name_index.get_mut(&name) {
217                        name_list.retain(|&idx| idx != index);
218                    }
219                    // Remove from id index
220                    self.id_index.remove(&node.id);
221                    // Remove from search index
222                    self.search_index.remove(&name, index);
223                }
224                self.graph.remove_node(index);
225            }
226        }
227    }
228
229    /// Gets the centrality score for a node.
230    pub fn centrality(&self, index: NodeId) -> f64 {
231        self.centrality.get(&index).copied().unwrap_or(0.0)
232    }
233
234    /// Sets centrality scores (called after computation).
235    pub fn set_centrality(&mut self, scores: HashMap<NodeId, f64>) {
236        self.centrality = scores;
237    }
238
239    /// Returns the full centrality score map (e.g. to warm-start a recompute).
240    pub fn centrality_map(&self) -> &HashMap<NodeId, f64> {
241        &self.centrality
242    }
243
244    /// Returns the number of nodes.
245    pub fn node_count(&self) -> usize {
246        self.graph.node_count()
247    }
248
249    /// Returns the number of edges.
250    pub fn edge_count(&self) -> usize {
251        self.graph.edge_count()
252    }
253
254    /// Iterates over all nodes.
255    pub fn nodes(&self) -> impl Iterator<Item = &CodeNode> {
256        self.graph.node_weights()
257    }
258
259    /// Iterates over all edges.
260    pub fn edges(&self) -> impl Iterator<Item = &Edge> {
261        self.graph.edge_weights()
262    }
263
264    /// Returns all edges with source and target IDs for export.
265    pub fn export_edges(&self) -> Vec<GraphEdge> {
266        (&self.graph)
267            .edge_references()
268            .filter_map(|edge_ref| {
269                let source = self.graph.node_weight(edge_ref.source())?.id.clone();
270                let target = self.graph.node_weight(edge_ref.target())?.id.clone();
271                let weight = edge_ref.weight(); // &Edge
272                Some(GraphEdge {
273                    source,
274                    target,
275                    kind: weight.kind,
276                })
277            })
278            .collect()
279    }
280
281    /// Iterates over all node indexes.
282    pub fn node_indexes(&self) -> impl Iterator<Item = NodeId> + '_ {
283        self.graph.node_indices()
284    }
285
286    /// Finds the shortest path between two nodes.
287    pub fn find_path(&self, from: NodeId, to: NodeId) -> Option<Vec<&CodeNode>> {
288        let path_indices = petgraph::algo::astar(
289            &self.graph,
290            from,
291            |finish| finish == to,
292            |_| 1, // weight of 1 for all edges (BFS-like)
293            |_| 0, // heuristic
294        )?;
295
296        Some(
297            path_indices
298                .1
299                .into_iter()
300                .filter_map(|idx| self.graph.node_weight(idx))
301                .collect(),
302        )
303    }
304
305    /// Gets the node index for a string ID.
306    pub fn get_index(&self, id: &str) -> Option<NodeId> {
307        self.id_index.get(id).copied()
308    }
309
310    /// Returns all nodes detected as production entry points.
311    pub fn list_entry_points(&self) -> Vec<&CodeNode> {
312        use crate::heuristics::HeuristicsMatcher;
313        self.graph
314            .node_weights()
315            .filter(|n| HeuristicsMatcher::is_likely_entry_point(n))
316            .collect()
317    }
318
319    /// Returns all nodes in a file and the call edges between them.
320    /// Edges returned as (caller_name, callee_name, edge_kind_debug_str) triples.
321    pub fn nodes_in_file_with_edges(
322        &self,
323        file: &str,
324    ) -> (Vec<&CodeNode>, Vec<(String, String, String)>) {
325        let node_ids: std::collections::HashSet<NodeId> = self
326            .file_index
327            .get(file)
328            .map(|ids| ids.iter().copied().collect())
329            .unwrap_or_default();
330
331        let nodes: Vec<&CodeNode> = node_ids
332            .iter()
333            .filter_map(|&id| self.graph.node_weight(id))
334            .collect();
335
336        let mut edges = Vec::new();
337        for &from in &node_ids {
338            for edge_ref in self
339                .graph
340                .edges_directed(from, petgraph::Direction::Outgoing)
341            {
342                let to = edge_ref.target();
343                if node_ids.contains(&to) {
344                    if let (Some(from_node), Some(to_node)) =
345                        (self.graph.node_weight(from), self.graph.node_weight(to))
346                    {
347                        edges.push((
348                            from_node.name.clone(),
349                            to_node.name.clone(),
350                            format!("{:?}", edge_ref.weight().kind),
351                        ));
352                    }
353                }
354            }
355        }
356        (nodes, edges)
357    }
358}
359
360/// Graph statistics for the info endpoint.
361#[derive(Debug, Serialize, Deserialize)]
362pub struct GraphStats {
363    pub node_count: usize,
364    pub edge_count: usize,
365    pub files: usize,
366}
367
368impl ArborGraph {
369    /// Returns graph statistics.
370    pub fn stats(&self) -> GraphStats {
371        GraphStats {
372            node_count: self.node_count(),
373            edge_count: self.edge_count(),
374            files: self.file_index.len(),
375        }
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382    use crate::edge::{Edge, EdgeKind};
383    use arbor_core::{CodeNode, NodeKind};
384
385    fn make_node(name: &str, file: &str) -> CodeNode {
386        CodeNode::new(name, name, NodeKind::Function, file)
387    }
388
389    #[test]
390    fn test_graph_new_is_empty() {
391        let g = ArborGraph::new();
392        assert_eq!(g.node_count(), 0);
393        assert_eq!(g.edge_count(), 0);
394        assert!(g.nodes().next().is_none());
395    }
396
397    #[test]
398    fn test_graph_add_and_get_node() {
399        let mut g = ArborGraph::new();
400        let node = make_node("foo", "main.rs");
401        let id = g.add_node(node.clone());
402        assert_eq!(g.node_count(), 1);
403
404        let got = g.get(id).unwrap();
405        assert_eq!(got.name, "foo");
406    }
407
408    #[test]
409    fn test_graph_find_by_name() {
410        let mut g = ArborGraph::new();
411        g.add_node(make_node("alpha", "a.rs"));
412        g.add_node(make_node("beta", "b.rs"));
413
414        let found = g.find_by_name("alpha");
415        assert_eq!(found.len(), 1);
416        assert_eq!(found[0].name, "alpha");
417
418        let not_found = g.find_by_name("gamma");
419        assert!(not_found.is_empty());
420    }
421
422    #[test]
423    fn test_graph_find_by_file() {
424        let mut g = ArborGraph::new();
425        g.add_node(make_node("foo", "main.rs"));
426        g.add_node(make_node("bar", "main.rs"));
427        g.add_node(make_node("baz", "other.rs"));
428
429        let main_nodes = g.find_by_file("main.rs");
430        assert_eq!(main_nodes.len(), 2);
431
432        let other_nodes = g.find_by_file("other.rs");
433        assert_eq!(other_nodes.len(), 1);
434
435        let empty = g.find_by_file("nonexistent.rs");
436        assert!(empty.is_empty());
437    }
438
439    #[test]
440    fn test_graph_search_substring() {
441        let mut g = ArborGraph::new();
442        g.add_node(make_node("validate_user", "a.rs"));
443        g.add_node(make_node("validate_email", "b.rs"));
444        g.add_node(make_node("send_email", "c.rs"));
445
446        let results = g.search("validate");
447        assert_eq!(results.len(), 2);
448        assert!(results.iter().any(|n| n.name == "validate_user"));
449        assert!(results.iter().any(|n| n.name == "validate_email"));
450    }
451
452    #[test]
453    fn test_graph_callers_callees() {
454        let mut g = ArborGraph::new();
455        let a = g.add_node(make_node("caller", "a.rs"));
456        let b = g.add_node(make_node("callee", "b.rs"));
457        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
458
459        let callees = g.get_callees(a);
460        assert_eq!(callees.len(), 1);
461        assert_eq!(callees[0].name, "callee");
462
463        let callers = g.get_callers(b);
464        assert_eq!(callers.len(), 1);
465        assert_eq!(callers[0].name, "caller");
466
467        // No callers/callees for disconnected nodes
468        assert!(g.get_callers(a).is_empty());
469        assert!(g.get_callees(b).is_empty());
470    }
471
472    #[test]
473    fn test_graph_get_dependents() {
474        // a -> b -> c
475        let mut g = ArborGraph::new();
476        let a = g.add_node(make_node("a", "a.rs"));
477        let b = g.add_node(make_node("b", "b.rs"));
478        let c = g.add_node(make_node("c", "c.rs"));
479        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
480        g.add_edge(b, c, Edge::new(EdgeKind::Calls));
481
482        // Dependents of c at depth 2 should include a and b
483        let deps = g.get_dependents(c, 2);
484        assert!(deps.iter().any(|(idx, _)| g.get(*idx).unwrap().name == "b"));
485        assert!(deps.iter().any(|(idx, _)| g.get(*idx).unwrap().name == "a"));
486    }
487
488    #[test]
489    fn test_graph_remove_file_cleanup() {
490        let mut g = ArborGraph::new();
491        g.add_node(make_node("foo", "remove_me.rs"));
492        g.add_node(make_node("bar", "remove_me.rs"));
493        g.add_node(make_node("keep", "keep.rs"));
494
495        assert_eq!(g.node_count(), 3);
496
497        g.remove_file("remove_me.rs");
498
499        // Nodes from removed file are gone
500        assert!(g.find_by_name("foo").is_empty());
501        assert!(g.find_by_name("bar").is_empty());
502        // Node from other file remains
503        assert_eq!(g.find_by_name("keep").len(), 1);
504        assert!(g.find_by_file("remove_me.rs").is_empty());
505    }
506
507    #[test]
508    fn test_graph_find_path() {
509        // a -> b -> c
510        let mut g = ArborGraph::new();
511        let a = g.add_node(make_node("start", "a.rs"));
512        let b = g.add_node(make_node("middle", "b.rs"));
513        let c = g.add_node(make_node("end", "c.rs"));
514        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
515        g.add_edge(b, c, Edge::new(EdgeKind::Calls));
516
517        let path = g.find_path(a, c).unwrap();
518        assert_eq!(path.len(), 3);
519        assert_eq!(path[0].name, "start");
520        assert_eq!(path[1].name, "middle");
521        assert_eq!(path[2].name, "end");
522    }
523
524    #[test]
525    fn test_graph_find_path_no_connection() {
526        let mut g = ArborGraph::new();
527        let a = g.add_node(make_node("island_a", "a.rs"));
528        let b = g.add_node(make_node("island_b", "b.rs"));
529
530        // No edges → no path
531        assert!(g.find_path(a, b).is_none());
532    }
533
534    #[test]
535    fn test_graph_export_edges() {
536        let mut g = ArborGraph::new();
537        let a = g.add_node(make_node("a", "a.rs"));
538        let b = g.add_node(make_node("b", "b.rs"));
539        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
540
541        let exported = g.export_edges();
542        assert_eq!(exported.len(), 1);
543        assert_eq!(exported[0].kind, EdgeKind::Calls);
544    }
545
546    #[test]
547    fn test_graph_stats() {
548        let mut g = ArborGraph::new();
549        g.add_node(make_node("a", "x.rs"));
550        g.add_node(make_node("b", "y.rs"));
551
552        let stats = g.stats();
553        assert_eq!(stats.node_count, 2);
554        assert_eq!(stats.edge_count, 0);
555        assert_eq!(stats.files, 2);
556    }
557
558    #[test]
559    fn test_graph_get_index_and_get_by_id() {
560        let mut g = ArborGraph::new();
561        let node = make_node("lookup_me", "test.rs");
562        let node_id_str = node.id.clone();
563        let idx = g.add_node(node);
564
565        assert_eq!(g.get_index(&node_id_str), Some(idx));
566        assert!(g.get_by_id(&node_id_str).is_some());
567        assert!(g.get_index("nonexistent").is_none());
568        assert!(g.get_by_id("nonexistent").is_none());
569    }
570
571    #[test]
572    fn test_graph_centrality_default_zero() {
573        let mut g = ArborGraph::new();
574        let idx = g.add_node(make_node("a", "a.rs"));
575        assert_eq!(g.centrality(idx), 0.0);
576    }
577
578    #[test]
579    fn test_graph_set_centrality() {
580        let mut g = ArborGraph::new();
581        let idx = g.add_node(make_node("a", "a.rs"));
582
583        let mut scores = HashMap::new();
584        scores.insert(idx, 0.75);
585        g.set_centrality(scores);
586
587        assert!((g.centrality(idx) - 0.75).abs() < f64::EPSILON);
588    }
589}
590
591#[cfg(test)]
592mod new_query_tests {
593    use super::*;
594    use crate::edge::{Edge, EdgeKind};
595    use arbor_core::{CodeNode, NodeKind};
596
597    fn make_node(name: &str, kind: NodeKind, file: &str) -> CodeNode {
598        CodeNode::new(name, format!("{}::{}", file, name), kind, file)
599    }
600
601    #[test]
602    fn test_list_entry_points_returns_main() {
603        let mut g = ArborGraph::new();
604        g.add_node(make_node("main", NodeKind::Function, "src/main.rs"));
605        g.add_node(make_node("helper", NodeKind::Function, "src/util.rs"));
606        let eps = g.list_entry_points();
607        assert!(
608            eps.iter().any(|n| n.name == "main"),
609            "main must be an entry point"
610        );
611        assert!(
612            !eps.iter().any(|n| n.name == "helper"),
613            "helper must not be an entry point"
614        );
615    }
616
617    #[test]
618    fn test_nodes_in_file_with_edges_returns_edges() {
619        let mut g = ArborGraph::new();
620        let a = g.add_node(make_node("foo", NodeKind::Function, "src/a.rs"));
621        let b = g.add_node(make_node("bar", NodeKind::Function, "src/a.rs"));
622        let _c = g.add_node(make_node("baz", NodeKind::Function, "src/b.rs"));
623        g.add_edge(
624            a,
625            b,
626            Edge {
627                kind: EdgeKind::Calls,
628                file: None,
629                line: None,
630            },
631        );
632        let (nodes, edges) = g.nodes_in_file_with_edges("src/a.rs");
633        assert_eq!(nodes.len(), 2);
634        assert_eq!(edges.len(), 1);
635        assert_eq!(edges[0].0, "foo");
636        assert_eq!(edges[0].1, "bar");
637    }
638
639    #[test]
640    fn test_nodes_in_file_with_edges_excludes_cross_file_edges() {
641        use crate::edge::{Edge, EdgeKind};
642        let mut g = ArborGraph::new();
643        let a = g.add_node(make_node("foo", NodeKind::Function, "src/a.rs"));
644        let c = g.add_node(make_node("baz", NodeKind::Function, "src/b.rs"));
645        // Edge from a.rs to b.rs — should NOT appear in get_file_graph for a.rs
646        g.add_edge(
647            a,
648            c,
649            Edge {
650                kind: EdgeKind::Calls,
651                file: None,
652                line: None,
653            },
654        );
655        let (nodes, edges) = g.nodes_in_file_with_edges("src/a.rs");
656        assert_eq!(nodes.len(), 1); // only foo
657        assert_eq!(edges.len(), 0); // cross-file edge excluded
658    }
659}