graphrag-core 0.2.0

Core portable library for GraphRAG - works on native and WASM
Documentation
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! Graph Traversal Algorithms for GraphRAG
//!
//! This module implements deterministic graph traversal algorithms that don't require
//! machine learning, following NLP best practices for knowledge graph exploration:
//!
//! - **BFS (Breadth-First Search)**: Level-by-level exploration for shortest paths
//! - **DFS (Depth-First Search)**: Deep exploration for discovering all paths
//! - **Ego-Network Extraction**: K-hop neighborhoods around entities
//! - **Multi-Source Path Finding**: Simultaneous search from multiple entities
//! - **Query-Focused Subgraph Extraction**: Context-aware subgraph retrieval
//!
//! These algorithms are essential for the query phase of GraphRAG, enabling:
//! - Efficient entity-centric retrieval
//! - Relationship path discovery
//! - Context-aware information gathering
//! - Multi-hop reasoning without neural networks

use crate::core::{Entity, EntityId, KnowledgeGraph, Relationship, Result};
use std::collections::{HashMap, HashSet, VecDeque};

/// Configuration for graph traversal algorithms
#[derive(Debug, Clone)]
pub struct TraversalConfig {
    /// Maximum depth for BFS/DFS traversal
    pub max_depth: usize,
    /// Maximum number of paths to return
    pub max_paths: usize,
    /// Whether to include edge weights in path scoring
    pub use_edge_weights: bool,
    /// Minimum relationship strength to traverse
    pub min_relationship_strength: f32,
}

impl Default for TraversalConfig {
    fn default() -> Self {
        Self {
            max_depth: 3,
            max_paths: 100,
            use_edge_weights: true,
            min_relationship_strength: 0.5,
        }
    }
}

/// Result of a graph traversal operation
#[derive(Debug, Clone)]
pub struct TraversalResult {
    /// Entities discovered during traversal
    pub entities: Vec<Entity>,
    /// Relationships traversed
    pub relationships: Vec<Relationship>,
    /// Paths found (for path-finding operations)
    pub paths: Vec<Vec<EntityId>>,
    /// Distance/depth of each entity from source
    pub distances: HashMap<EntityId, usize>,
}

/// Graph traversal system implementing various search algorithms
pub struct GraphTraversal {
    config: TraversalConfig,
}

impl Default for GraphTraversal {
    fn default() -> Self {
        Self::new(TraversalConfig::default())
    }
}

impl GraphTraversal {
    /// Create a new graph traversal system
    pub fn new(config: TraversalConfig) -> Self {
        Self { config }
    }

    /// Breadth-First Search (BFS) from a source entity
    ///
    /// BFS explores the graph level by level, guaranteeing shortest paths.
    /// Ideal for finding entities within a certain distance from the source.
    ///
    /// # Arguments
    /// * `graph` - The knowledge graph to traverse
    /// * `source` - Starting entity ID
    ///
    /// # Returns
    /// TraversalResult with entities, relationships, and distances
    pub fn bfs(&self, graph: &KnowledgeGraph, source: &EntityId) -> Result<TraversalResult> {
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        let mut distances = HashMap::new();
        let mut discovered_entities = Vec::new();
        let mut discovered_relationships = Vec::new();

        // Initialize with source entity
        queue.push_back((source.clone(), 0));
        distances.insert(source.clone(), 0);

        while let Some((current_id, depth)) = queue.pop_front() {
            // Stop if we've reached max depth
            if depth >= self.config.max_depth {
                continue;
            }

            // Skip if already visited
            if visited.contains(&current_id) {
                continue;
            }
            visited.insert(current_id.clone());

            // Add current entity to results
            if let Some(entity) = graph.get_entity(&current_id) {
                discovered_entities.push(entity.clone());
            }

            // Get all neighbors (entities connected by relationships)
            let neighbors = self.get_neighbors(graph, &current_id);

            for (neighbor_id, relationship) in neighbors {
                // Filter by relationship confidence
                if relationship.confidence < self.config.min_relationship_strength {
                    continue;
                }

                // Add to queue if not visited
                if !visited.contains(&neighbor_id) {
                    queue.push_back((neighbor_id.clone(), depth + 1));
                    distances.entry(neighbor_id.clone()).or_insert(depth + 1);
                    discovered_relationships.push(relationship);
                }
            }
        }

        Ok(TraversalResult {
            entities: discovered_entities,
            relationships: discovered_relationships,
            paths: Vec::new(), // BFS doesn't track individual paths
            distances,
        })
    }

    /// Depth-First Search (DFS) from a source entity
    ///
    /// DFS explores as far as possible along each branch before backtracking.
    /// Useful for finding all possible paths and deep exploration.
    ///
    /// # Arguments
    /// * `graph` - The knowledge graph to traverse
    /// * `source` - Starting entity ID
    ///
    /// # Returns
    /// TraversalResult with entities, relationships, and discovered paths
    pub fn dfs(&self, graph: &KnowledgeGraph, source: &EntityId) -> Result<TraversalResult> {
        let mut visited = HashSet::new();
        let mut distances = HashMap::new();
        let mut discovered_entities = Vec::new();
        let mut discovered_relationships = Vec::new();

        self.dfs_recursive(
            graph,
            source,
            0,
            &mut visited,
            &mut distances,
            &mut discovered_entities,
            &mut discovered_relationships,
        )?;

        Ok(TraversalResult {
            entities: discovered_entities,
            relationships: discovered_relationships,
            paths: Vec::new(), // Basic DFS doesn't track paths
            distances,
        })
    }

    /// Recursive DFS helper
    #[allow(clippy::too_many_arguments)]
    fn dfs_recursive(
        &self,
        graph: &KnowledgeGraph,
        current_id: &EntityId,
        depth: usize,
        visited: &mut HashSet<EntityId>,
        distances: &mut HashMap<EntityId, usize>,
        discovered_entities: &mut Vec<Entity>,
        discovered_relationships: &mut Vec<Relationship>,
    ) -> Result<()> {
        // Stop if max depth reached
        if depth >= self.config.max_depth {
            return Ok(());
        }

        // Skip if already visited (avoid cycles)
        if visited.contains(current_id) {
            return Ok(());
        }

        visited.insert(current_id.clone());
        distances.insert(current_id.clone(), depth);

        // Add current entity
        if let Some(entity) = graph.get_entity(current_id) {
            discovered_entities.push(entity.clone());
        }

        // Recursively visit neighbors
        let neighbors = self.get_neighbors(graph, current_id);

        for (neighbor_id, relationship) in neighbors {
            if relationship.confidence < self.config.min_relationship_strength {
                continue;
            }

            if !visited.contains(&neighbor_id) {
                discovered_relationships.push(relationship);
                self.dfs_recursive(
                    graph,
                    &neighbor_id,
                    depth + 1,
                    visited,
                    distances,
                    discovered_entities,
                    discovered_relationships,
                )?;
            }
        }

        Ok(())
    }

    /// Extract K-hop ego-network around an entity
    ///
    /// An ego-network is a subgraph containing all entities within K hops
    /// of the source entity. This is useful for context-aware retrieval.
    ///
    /// # Arguments
    /// * `graph` - The knowledge graph
    /// * `entity_id` - Center entity for the ego-network
    /// * `k_hops` - Number of hops to include (defaults to config.max_depth)
    ///
    /// # Returns
    /// TraversalResult with the ego-network subgraph
    pub fn ego_network(
        &self,
        graph: &KnowledgeGraph,
        entity_id: &EntityId,
        k_hops: Option<usize>,
    ) -> Result<TraversalResult> {
        let hops = k_hops.unwrap_or(self.config.max_depth);

        let mut subgraph_entities = Vec::new();
        let mut subgraph_relationships = Vec::new();
        let mut visited = HashSet::new();
        let mut distances = HashMap::new();

        // Start with the ego entity
        visited.insert(entity_id.clone());
        distances.insert(entity_id.clone(), 0);

        if let Some(entity) = graph.get_entity(entity_id) {
            subgraph_entities.push(entity.clone());
        }

        // Use BFS to expand outward for k hops
        let mut current_layer = vec![entity_id.clone()];

        for hop in 1..=hops {
            let mut next_layer = Vec::new();

            for current_id in &current_layer {
                let neighbors = self.get_neighbors(graph, current_id);

                for (neighbor_id, relationship) in neighbors {
                    if relationship.confidence < self.config.min_relationship_strength {
                        continue;
                    }

                    // Add relationship
                    subgraph_relationships.push(relationship);

                    // Add neighbor if not visited
                    if !visited.contains(&neighbor_id) {
                        visited.insert(neighbor_id.clone());
                        distances.insert(neighbor_id.clone(), hop);

                        if let Some(entity) = graph.get_entity(&neighbor_id) {
                            subgraph_entities.push(entity.clone());
                        }

                        next_layer.push(neighbor_id);
                    }
                }
            }

            current_layer = next_layer;
        }

        Ok(TraversalResult {
            entities: subgraph_entities,
            relationships: subgraph_relationships,
            paths: Vec::new(),
            distances,
        })
    }

    /// Multi-source BFS pathfinding
    ///
    /// Performs simultaneous BFS from multiple source entities to find
    /// intersections and common neighbors efficiently.
    ///
    /// # Arguments
    /// * `graph` - The knowledge graph
    /// * `sources` - Multiple starting entity IDs
    ///
    /// # Returns
    /// TraversalResult with entities reachable from any source
    pub fn multi_source_bfs(
        &self,
        graph: &KnowledgeGraph,
        sources: &[EntityId],
    ) -> Result<TraversalResult> {
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        let mut distances = HashMap::new();
        let mut discovered_entities = Vec::new();
        let mut discovered_relationships = Vec::new();

        // Initialize queue with all sources
        for source in sources {
            queue.push_back((source.clone(), 0));
            distances.insert(source.clone(), 0);
        }

        while let Some((current_id, depth)) = queue.pop_front() {
            if depth >= self.config.max_depth {
                continue;
            }

            if visited.contains(&current_id) {
                continue;
            }
            visited.insert(current_id.clone());

            if let Some(entity) = graph.get_entity(&current_id) {
                discovered_entities.push(entity.clone());
            }

            let neighbors = self.get_neighbors(graph, &current_id);

            for (neighbor_id, relationship) in neighbors {
                if relationship.confidence < self.config.min_relationship_strength {
                    continue;
                }

                if !visited.contains(&neighbor_id) {
                    queue.push_back((neighbor_id.clone(), depth + 1));
                    distances.entry(neighbor_id.clone()).or_insert(depth + 1);
                    discovered_relationships.push(relationship);
                }
            }
        }

        Ok(TraversalResult {
            entities: discovered_entities,
            relationships: discovered_relationships,
            paths: Vec::new(),
            distances,
        })
    }

    /// Find all paths between two entities
    ///
    /// Uses DFS to discover all possible paths from source to target
    /// within the maximum depth limit.
    ///
    /// # Arguments
    /// * `graph` - The knowledge graph
    /// * `source` - Starting entity
    /// * `target` - Target entity
    ///
    /// # Returns
    /// TraversalResult with all discovered paths
    pub fn find_all_paths(
        &self,
        graph: &KnowledgeGraph,
        source: &EntityId,
        target: &EntityId,
    ) -> Result<TraversalResult> {
        let mut all_paths = Vec::new();
        let mut current_path = vec![source.clone()];
        let mut visited = HashSet::new();
        let mut discovered_relationships = Vec::new();

        self.find_paths_recursive(
            graph,
            source,
            target,
            &mut current_path,
            &mut visited,
            &mut all_paths,
            &mut discovered_relationships,
            0,
        )?;

        // Collect all unique entities from paths
        let mut unique_entities = HashSet::new();
        for path in &all_paths {
            unique_entities.extend(path.iter().cloned());
        }

        let discovered_entities: Vec<Entity> = unique_entities
            .iter()
            .filter_map(|id| graph.get_entity(id).cloned())
            .collect();

        Ok(TraversalResult {
            entities: discovered_entities,
            relationships: discovered_relationships,
            paths: all_paths,
            distances: HashMap::new(),
        })
    }

    /// Recursive helper for find_all_paths
    #[allow(clippy::too_many_arguments)]
    fn find_paths_recursive(
        &self,
        graph: &KnowledgeGraph,
        current: &EntityId,
        target: &EntityId,
        current_path: &mut Vec<EntityId>,
        visited: &mut HashSet<EntityId>,
        all_paths: &mut Vec<Vec<EntityId>>,
        discovered_relationships: &mut Vec<Relationship>,
        depth: usize,
    ) -> Result<()> {
        // Stop if max depth or max paths reached
        if depth >= self.config.max_depth || all_paths.len() >= self.config.max_paths {
            return Ok(());
        }

        // Found target - save path
        if current == target {
            all_paths.push(current_path.clone());
            return Ok(());
        }

        visited.insert(current.clone());

        let neighbors = self.get_neighbors(graph, current);

        for (neighbor_id, relationship) in neighbors {
            if relationship.confidence < self.config.min_relationship_strength {
                continue;
            }

            if !visited.contains(&neighbor_id) {
                current_path.push(neighbor_id.clone());
                discovered_relationships.push(relationship);

                self.find_paths_recursive(
                    graph,
                    &neighbor_id,
                    target,
                    current_path,
                    visited,
                    all_paths,
                    discovered_relationships,
                    depth + 1,
                )?;

                current_path.pop();
            }
        }

        visited.remove(current);

        Ok(())
    }

    /// Get neighbors of an entity with their connecting relationships
    fn get_neighbors(
        &self,
        graph: &KnowledgeGraph,
        entity_id: &EntityId,
    ) -> Vec<(EntityId, Relationship)> {
        let mut neighbors = Vec::new();

        // Get all relationships where this entity is the source
        for relationship in graph.get_all_relationships() {
            if &relationship.source == entity_id {
                neighbors.push((relationship.target.clone(), relationship.clone()));
            }
            // Also consider bidirectional traversal
            if &relationship.target == entity_id {
                neighbors.push((relationship.source.clone(), relationship.clone()));
            }
        }

        neighbors
    }

    /// Extract query-focused subgraph
    ///
    /// Extracts a subgraph relevant to a specific query by:
    /// 1. Identifying seed entities from query
    /// 2. Expanding via ego-networks
    /// 3. Filtering by relevance
    ///
    /// # Arguments
    /// * `graph` - The knowledge graph
    /// * `seed_entities` - Starting entities identified in query
    /// * `expansion_hops` - How many hops to expand
    ///
    /// # Returns
    /// TraversalResult with query-relevant subgraph
    pub fn query_focused_subgraph(
        &self,
        graph: &KnowledgeGraph,
        seed_entities: &[EntityId],
        expansion_hops: usize,
    ) -> Result<TraversalResult> {
        let mut combined_entities = Vec::new();
        let mut combined_relationships = Vec::new();
        let mut combined_distances = HashMap::new();
        let mut seen_entities = HashSet::new();
        let mut seen_relationships = HashSet::new();

        // Extract ego-network for each seed entity
        for seed in seed_entities {
            let ego_result = self.ego_network(graph, seed, Some(expansion_hops))?;

            for entity in ego_result.entities {
                if !seen_entities.contains(&entity.id) {
                    seen_entities.insert(entity.id.clone());
                    combined_entities.push(entity);
                }
            }

            for rel in ego_result.relationships {
                let rel_key = (
                    rel.source.clone(),
                    rel.target.clone(),
                    rel.relation_type.clone(),
                );
                if !seen_relationships.contains(&rel_key) {
                    seen_relationships.insert(rel_key);
                    combined_relationships.push(rel);
                }
            }

            for (entity_id, distance) in ego_result.distances {
                combined_distances
                    .entry(entity_id)
                    .and_modify(|d: &mut usize| *d = (*d).min(distance))
                    .or_insert(distance);
            }
        }

        Ok(TraversalResult {
            entities: combined_entities,
            relationships: combined_relationships,
            paths: Vec::new(),
            distances: combined_distances,
        })
    }
}

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

    fn create_test_graph() -> KnowledgeGraph {
        let mut graph = KnowledgeGraph::new();

        // Create entities: A -> B -> C
        //                  A -> D
        let entity_a = Entity::new(
            EntityId::new("A".to_string()),
            "Entity A".to_string(),
            "CONCEPT".to_string(),
            0.9,
        );
        let entity_b = Entity::new(
            EntityId::new("B".to_string()),
            "Entity B".to_string(),
            "CONCEPT".to_string(),
            0.9,
        );
        let entity_c = Entity::new(
            EntityId::new("C".to_string()),
            "Entity C".to_string(),
            "CONCEPT".to_string(),
            0.9,
        );
        let entity_d = Entity::new(
            EntityId::new("D".to_string()),
            "Entity D".to_string(),
            "CONCEPT".to_string(),
            0.9,
        );

        let _ = graph.add_entity(entity_a);
        let _ = graph.add_entity(entity_b);
        let _ = graph.add_entity(entity_c);
        let _ = graph.add_entity(entity_d);

        // Add relationships
        let _ = graph.add_relationship(Relationship {
            source: EntityId::new("A".to_string()),
            target: EntityId::new("B".to_string()),
            relation_type: "RELATED_TO".to_string(),
            confidence: 0.8,
            context: Vec::new(),
            embedding: None,
            temporal_type: None,
            temporal_range: None,
            causal_strength: None,
        });

        let _ = graph.add_relationship(Relationship {
            source: EntityId::new("B".to_string()),
            target: EntityId::new("C".to_string()),
            relation_type: "RELATED_TO".to_string(),
            confidence: 0.9,
            context: Vec::new(),
            embedding: None,
            temporal_type: None,
            temporal_range: None,
            causal_strength: None,
        });

        let _ = graph.add_relationship(Relationship {
            source: EntityId::new("A".to_string()),
            target: EntityId::new("D".to_string()),
            relation_type: "RELATED_TO".to_string(),
            confidence: 0.7,
            context: Vec::new(),
            embedding: None,
            temporal_type: None,
            temporal_range: None,
            causal_strength: None,
        });

        graph
    }

    #[test]
    fn test_bfs_traversal() {
        let graph = create_test_graph();
        let traversal = GraphTraversal::default();
        let source = EntityId::new("A".to_string());

        let result = traversal.bfs(&graph, &source).unwrap();

        // Should discover all connected entities
        assert!(!result.entities.is_empty());
        assert!(result.distances.contains_key(&source));
    }

    #[test]
    fn test_dfs_traversal() {
        let graph = create_test_graph();
        let traversal = GraphTraversal::default();
        let source = EntityId::new("A".to_string());

        let result = traversal.dfs(&graph, &source).unwrap();

        // Should discover entities through DFS
        assert!(!result.entities.is_empty());
        assert!(result.distances.contains_key(&source));
    }

    #[test]
    fn test_ego_network() {
        let graph = create_test_graph();
        let traversal = GraphTraversal::default();
        let entity_id = EntityId::new("A".to_string());

        let result = traversal.ego_network(&graph, &entity_id, Some(1)).unwrap();

        // 1-hop ego network of A should include A, B, and D
        assert!(result.entities.len() >= 2); // At least A and one neighbor
        assert_eq!(*result.distances.get(&entity_id).unwrap(), 0);
    }

    #[test]
    fn test_multi_source_bfs() {
        let graph = create_test_graph();
        let traversal = GraphTraversal::default();
        let sources = vec![
            EntityId::new("A".to_string()),
            EntityId::new("C".to_string()),
        ];

        let result = traversal.multi_source_bfs(&graph, &sources).unwrap();

        // Should discover entities from both sources
        assert!(result.entities.len() >= 2);
    }

    #[test]
    fn test_find_all_paths() {
        let graph = create_test_graph();
        let traversal = GraphTraversal::default();
        let source = EntityId::new("A".to_string());
        let target = EntityId::new("C".to_string());

        let result = traversal.find_all_paths(&graph, &source, &target).unwrap();

        // Should find at least one path from A to C (A -> B -> C)
        assert!(!result.paths.is_empty());
        assert!(result.paths[0].contains(&source));
        assert!(result.paths[0].contains(&target));
    }

    #[test]
    fn test_query_focused_subgraph() {
        let graph = create_test_graph();
        let traversal = GraphTraversal::default();
        let seeds = vec![EntityId::new("A".to_string())];

        let result = traversal.query_focused_subgraph(&graph, &seeds, 2).unwrap();

        // Should extract subgraph around seed entity
        assert!(!result.entities.is_empty());
        assert!(!result.relationships.is_empty());
    }
}