aprender-graph 0.31.1

GPU-first embedded graph database for code analysis (call graphs, dependencies, AST traversals)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Topological algorithms: cycle detection and topological sort
//!
//! Provides graph ordering algorithms needed for dependency analysis:
//! - `is_cyclic`: Detect if a directed graph contains cycles
//! - `toposort`: Topological ordering of a DAG (Directed Acyclic Graph)
//!
//! # Example
//!
//! ```
//! use trueno_graph::{CsrGraph, NodeId, is_cyclic, toposort};
//!
//! // Build a DAG: 0 → 1 → 2
//! let edges = vec![
//!     (NodeId(0), NodeId(1), 1.0),
//!     (NodeId(1), NodeId(2), 1.0),
//! ];
//! let graph = CsrGraph::from_edge_list(&edges).unwrap();
//!
//! assert!(!is_cyclic(&graph));
//!
//! let order = toposort(&graph).unwrap();
//! assert_eq!(order, vec![NodeId(0), NodeId(1), NodeId(2)]);
//! ```

use crate::storage::CsrGraph;
use crate::NodeId;
use anyhow::{anyhow, Result};

/// Node state during DFS traversal
#[derive(Clone, Copy, PartialEq, Eq)]
enum NodeState {
    /// Not yet visited
    Unvisited,
    /// Currently in DFS stack (part of current path)
    InStack,
    /// Fully processed (all descendants visited)
    Finished,
}

/// Check if the graph contains any cycles
///
/// Uses depth-first search with three-color marking:
/// - Unvisited: not yet seen
/// - `InStack`: currently being explored (back edge = cycle)
/// - Finished: fully explored
///
/// # Arguments
///
/// * `graph` - The CSR graph to check
///
/// # Returns
///
/// `true` if the graph contains at least one cycle, `false` otherwise
///
/// # Example
///
/// ```
/// use trueno_graph::{CsrGraph, NodeId, is_cyclic};
///
/// // Acyclic: 0 → 1 → 2
/// let dag = CsrGraph::from_edge_list(&[
///     (NodeId(0), NodeId(1), 1.0),
///     (NodeId(1), NodeId(2), 1.0),
/// ]).unwrap();
/// assert!(!is_cyclic(&dag));
///
/// // Cyclic: 0 → 1 → 2 → 0
/// let cyclic = CsrGraph::from_edge_list(&[
///     (NodeId(0), NodeId(1), 1.0),
///     (NodeId(1), NodeId(2), 1.0),
///     (NodeId(2), NodeId(0), 1.0),
/// ]).unwrap();
/// assert!(is_cyclic(&cyclic));
/// ```
#[must_use]
pub fn is_cyclic(graph: &CsrGraph) -> bool {
    let n = graph.num_nodes();
    if n == 0 {
        return false;
    }

    let mut state = vec![NodeState::Unvisited; n];

    // Check all nodes (handles disconnected components)
    for start in 0..n {
        if state[start] == NodeState::Unvisited && has_cycle_from(graph, start, &mut state) {
            return true;
        }
    }

    false
}

/// DFS helper to detect cycle starting from a node
fn has_cycle_from(graph: &CsrGraph, node: usize, state: &mut [NodeState]) -> bool {
    state[node] = NodeState::InStack;

    // Check all outgoing neighbors
    #[allow(clippy::cast_possible_truncation)]
    let neighbors = graph.outgoing_neighbors(NodeId(node as u32));

    if let Ok(neighbors) = neighbors {
        for &neighbor in neighbors {
            let neighbor_idx = neighbor as usize;

            match state[neighbor_idx] {
                NodeState::InStack => {
                    // Back edge found - cycle detected!
                    return true;
                }
                NodeState::Unvisited => {
                    if has_cycle_from(graph, neighbor_idx, state) {
                        return true;
                    }
                }
                NodeState::Finished => {
                    // Already fully explored, skip
                }
            }
        }
    }

    state[node] = NodeState::Finished;
    false
}

/// Compute topological ordering of a directed acyclic graph (DAG)
///
/// Returns nodes in an order where for every edge u → v, u appears before v.
/// This is the order needed for dependency resolution (dependencies first).
///
/// # Arguments
///
/// * `graph` - The CSR graph to sort
///
/// # Returns
///
/// * `Ok(Vec<NodeId>)` - Nodes in topological order
/// * `Err` - If the graph contains a cycle
///
/// # Errors
///
/// Returns an error if the graph contains a cycle, making topological ordering impossible.
///
/// # Example
///
/// ```
/// use trueno_graph::{CsrGraph, NodeId, toposort};
///
/// // DAG: 0 → 1 → 2, 0 → 2
/// let graph = CsrGraph::from_edge_list(&[
///     (NodeId(0), NodeId(1), 1.0),
///     (NodeId(1), NodeId(2), 1.0),
///     (NodeId(0), NodeId(2), 1.0),
/// ]).unwrap();
///
/// let order = toposort(&graph).unwrap();
///
/// // Node 0 must come before 1 and 2
/// let pos_0 = order.iter().position(|&n| n == NodeId(0)).unwrap();
/// let pos_1 = order.iter().position(|&n| n == NodeId(1)).unwrap();
/// let pos_2 = order.iter().position(|&n| n == NodeId(2)).unwrap();
///
/// assert!(pos_0 < pos_1);
/// assert!(pos_0 < pos_2);
/// assert!(pos_1 < pos_2);
/// ```
pub fn toposort(graph: &CsrGraph) -> Result<Vec<NodeId>> {
    let n = graph.num_nodes();
    if n == 0 {
        return Ok(Vec::new());
    }

    let mut state = vec![NodeState::Unvisited; n];
    let mut result = Vec::with_capacity(n);

    // Visit all nodes (handles disconnected components)
    for start in 0..n {
        if state[start] == NodeState::Unvisited {
            toposort_dfs(graph, start, &mut state, &mut result)?;
        }
    }

    // Reverse to get correct order (DFS gives reverse topological order)
    result.reverse();
    Ok(result)
}

/// DFS helper for topological sort
fn toposort_dfs(
    graph: &CsrGraph,
    node: usize,
    state: &mut [NodeState],
    result: &mut Vec<NodeId>,
) -> Result<()> {
    state[node] = NodeState::InStack;

    // Visit all outgoing neighbors
    #[allow(clippy::cast_possible_truncation)]
    let neighbors = graph.outgoing_neighbors(NodeId(node as u32))?;

    for &neighbor in neighbors {
        let neighbor_idx = neighbor as usize;

        match state[neighbor_idx] {
            NodeState::InStack => {
                // Back edge found - cycle detected!
                return Err(anyhow!("Cycle detected: cannot compute topological order"));
            }
            NodeState::Unvisited => {
                toposort_dfs(graph, neighbor_idx, state, result)?;
            }
            NodeState::Finished => {
                // Already processed, skip
            }
        }
    }

    state[node] = NodeState::Finished;

    #[allow(clippy::cast_possible_truncation)]
    result.push(NodeId(node as u32));

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_graph_not_cyclic() {
        let graph = CsrGraph::new();
        assert!(!is_cyclic(&graph));
    }

    #[test]
    fn test_empty_graph_toposort() {
        let graph = CsrGraph::new();
        let order = toposort(&graph).unwrap();
        assert!(order.is_empty());
    }

    #[test]
    fn test_single_node_not_cyclic() {
        let mut graph = CsrGraph::new();
        graph.add_edge(NodeId(0), NodeId(1), 1.0).unwrap();
        // Node 0 exists with edge to node 1
        assert!(!is_cyclic(&graph));
    }

    #[test]
    fn test_self_loop_is_cyclic() {
        let edges = vec![(NodeId(0), NodeId(0), 1.0)]; // Self-loop
        let graph = CsrGraph::from_edge_list(&edges).unwrap();
        assert!(is_cyclic(&graph));
    }

    #[test]
    fn test_simple_dag_not_cyclic() {
        // 0 → 1 → 2
        let edges = vec![(NodeId(0), NodeId(1), 1.0), (NodeId(1), NodeId(2), 1.0)];
        let graph = CsrGraph::from_edge_list(&edges).unwrap();
        assert!(!is_cyclic(&graph));
    }

    #[test]
    fn test_simple_cycle() {
        // 0 → 1 → 2 → 0 (cycle)
        let edges = vec![
            (NodeId(0), NodeId(1), 1.0),
            (NodeId(1), NodeId(2), 1.0),
            (NodeId(2), NodeId(0), 1.0),
        ];
        let graph = CsrGraph::from_edge_list(&edges).unwrap();
        assert!(is_cyclic(&graph));
    }

    #[test]
    fn test_diamond_dag_not_cyclic() {
        // Diamond: 0 → 1 → 3, 0 → 2 → 3
        let edges = vec![
            (NodeId(0), NodeId(1), 1.0),
            (NodeId(0), NodeId(2), 1.0),
            (NodeId(1), NodeId(3), 1.0),
            (NodeId(2), NodeId(3), 1.0),
        ];
        let graph = CsrGraph::from_edge_list(&edges).unwrap();
        assert!(!is_cyclic(&graph));
    }

    #[test]
    fn test_toposort_simple_chain() {
        // 0 → 1 → 2
        let edges = vec![(NodeId(0), NodeId(1), 1.0), (NodeId(1), NodeId(2), 1.0)];
        let graph = CsrGraph::from_edge_list(&edges).unwrap();

        let order = toposort(&graph).unwrap();
        assert_eq!(order, vec![NodeId(0), NodeId(1), NodeId(2)]);
    }

    #[test]
    fn test_toposort_diamond() {
        // Diamond: 0 → 1 → 3, 0 → 2 → 3
        let edges = vec![
            (NodeId(0), NodeId(1), 1.0),
            (NodeId(0), NodeId(2), 1.0),
            (NodeId(1), NodeId(3), 1.0),
            (NodeId(2), NodeId(3), 1.0),
        ];
        let graph = CsrGraph::from_edge_list(&edges).unwrap();

        let order = toposort(&graph).unwrap();

        // Verify constraints
        let pos = |n: u32| order.iter().position(|&x| x == NodeId(n)).unwrap();

        assert!(pos(0) < pos(1), "0 must come before 1");
        assert!(pos(0) < pos(2), "0 must come before 2");
        assert!(pos(1) < pos(3), "1 must come before 3");
        assert!(pos(2) < pos(3), "2 must come before 3");
    }

    #[test]
    fn test_toposort_fails_on_cycle() {
        // 0 → 1 → 2 → 0 (cycle)
        let edges = vec![
            (NodeId(0), NodeId(1), 1.0),
            (NodeId(1), NodeId(2), 1.0),
            (NodeId(2), NodeId(0), 1.0),
        ];
        let graph = CsrGraph::from_edge_list(&edges).unwrap();

        let result = toposort(&graph);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Cycle"));
    }

    #[test]
    fn test_disconnected_components() {
        // Two disconnected chains: 0 → 1, 2 → 3
        let edges = vec![(NodeId(0), NodeId(1), 1.0), (NodeId(2), NodeId(3), 1.0)];
        let graph = CsrGraph::from_edge_list(&edges).unwrap();

        assert!(!is_cyclic(&graph));

        let order = toposort(&graph).unwrap();
        assert_eq!(order.len(), 4);

        // Verify ordering constraints
        let pos = |n: u32| order.iter().position(|&x| x == NodeId(n)).unwrap();
        assert!(pos(0) < pos(1));
        assert!(pos(2) < pos(3));
    }

    #[test]
    fn test_complex_dag() {
        // Complex DAG with multiple paths
        //     0
        //    /|\
        //   1 2 3
        //    \|/
        //     4
        let edges = vec![
            (NodeId(0), NodeId(1), 1.0),
            (NodeId(0), NodeId(2), 1.0),
            (NodeId(0), NodeId(3), 1.0),
            (NodeId(1), NodeId(4), 1.0),
            (NodeId(2), NodeId(4), 1.0),
            (NodeId(3), NodeId(4), 1.0),
        ];
        let graph = CsrGraph::from_edge_list(&edges).unwrap();

        assert!(!is_cyclic(&graph));

        let order = toposort(&graph).unwrap();

        // 0 must be first, 4 must be last
        assert_eq!(order[0], NodeId(0));
        assert_eq!(order[4], NodeId(4));
    }

    #[test]
    fn test_two_node_cycle() {
        // Simple 2-node cycle: 0 ↔ 1
        let edges = vec![(NodeId(0), NodeId(1), 1.0), (NodeId(1), NodeId(0), 1.0)];
        let graph = CsrGraph::from_edge_list(&edges).unwrap();
        assert!(is_cyclic(&graph));
    }

    #[test]
    fn test_cycle_in_subgraph() {
        // DAG with cycle in subgraph: 0 → 1 → 2 → 1 (cycle), 3 → 4
        let edges = vec![
            (NodeId(0), NodeId(1), 1.0),
            (NodeId(1), NodeId(2), 1.0),
            (NodeId(2), NodeId(1), 1.0), // Creates cycle
            (NodeId(3), NodeId(4), 1.0),
        ];
        let graph = CsrGraph::from_edge_list(&edges).unwrap();
        assert!(is_cyclic(&graph));
    }
}