aletheiadb 0.1.0

A high-performance bi-temporal graph database for LLM integration
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
//! Semantic Pathfinding Module (Experimental)
//!
//! This module implements pathfinding algorithms that consider semantic similarity
//! (vector embeddings) as part of the cost function. Instead of just finding the shortest
//! structural path between two nodes, semantic pathfinding finds the *most contextually relevant*
//! path, allowing queries to be guided by a concept.
//!
//! # Features
//! - **Semantic A***: Finds paths where intermediate nodes are semantically similar to a query concept.
//! - **Time-Travel Pathfinding**: Finds paths that were valid at a specific historical point in time.
//!
//! # Examples
//!
//! ```no_run
//! use aletheiadb::db::AletheiaDB;
//! use aletheiadb::core::property::PropertyMapBuilder;
//! use aletheiadb::query::semantic_pathfinding::SemanticPathfinder;
//! use aletheiadb::index::vector::{HnswConfig, DistanceMetric};
//! use aletheiadb::api::transaction::WriteOps;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // 1. Setup Database with vector index
//! let db = AletheiaDB::new()?;
//! db.vector_index("embedding")
//!     .hnsw(HnswConfig::new(3, DistanceMetric::Cosine))
//!     .enable()?;
//!
//! // 2. Create nodes with vector embeddings
//! let start = db.create_node("Start", PropertyMapBuilder::new().insert_vector("embedding", &[0.5, 0.5, 0.0]).build())?;
//! let end = db.create_node("End", PropertyMapBuilder::new().insert_vector("embedding", &[0.5, 0.5, 0.0]).build())?;
//!
//! // Intermediate nodes
//! let apple = db.create_node("Apple", PropertyMapBuilder::new().insert_vector("embedding", &[1.0, 0.0, 0.0]).build())?; // Fruit
//! let laptop = db.create_node("Laptop", PropertyMapBuilder::new().insert_vector("embedding", &[0.0, 1.0, 0.0]).build())?; // Tech
//!
//! // Create edges: Start -> [Apple, Laptop] -> End
//! db.create_edge(start, apple, "NEXT", PropertyMapBuilder::new().build())?;
//! db.create_edge(apple, end, "NEXT", PropertyMapBuilder::new().build())?;
//! db.create_edge(start, laptop, "NEXT", PropertyMapBuilder::new().build())?;
//! db.create_edge(laptop, end, "NEXT", PropertyMapBuilder::new().build())?;
//!
//! // 3. Find path using a query vector (e.g., "Banana", which is closer to "Apple" than "Laptop")
//! let query_embedding = vec![0.9, 0.1, 0.0];
//! let pathfinder = SemanticPathfinder::new(&db, "embedding");
//!
//! // The pathfinder will prefer the route through 'Apple' because it's semantically closer
//! let path = pathfinder.find_path(start, end, &query_embedding, 10, false)?.unwrap();
//! assert_eq!(path, vec![start, apple, end]);
//! # Ok(())
//! # }
//! ```
//!
//! # Errors
//! Methods in this module will return a [`Result`] indicating failure if:
//! - An underlying database read operation fails.
//! - Property maps contain malformed vector properties.
//!
//! # Panics
//! This module does not intentionally panic. If any node has a vector that differs in dimension from the `query_embedding`,
//! it treats the cost as infinite (effectively blocking the path) instead of panicking.

use crate::core::error::Result;
use crate::core::hasher::IdentityHasher;
use crate::core::id::NodeId;
use crate::core::temporal::Timestamp;
use crate::core::vector::cosine_similarity;
use crate::query::traits::GraphView;
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap};
use std::hash::BuildHasherDefault;

/// Per-hop structural cost to prefer shorter paths when semantic costs are equal.
const STRUCTURAL_HOP_COST: f32 = 0.1;

/// Default cost assigned to nodes without embeddings.
const NO_EMBEDDING_COST: f32 = 1.0;

/// State for priority queue (min-heap based on cost).
#[derive(Debug, Clone, Copy, PartialEq)]
struct State {
    cost: f32,
    node: NodeId,
    depth: usize,
}

impl Eq for State {}

impl Ord for State {
    fn cmp(&self, other: &Self) -> Ordering {
        // Reverse order for min-heap (we want smallest cost)
        // Handle NaN by treating it as "greater than" (lowest priority)
        if self.cost.is_nan() {
            return Ordering::Less; // self > other (in reverse logic)
        }
        if other.cost.is_nan() {
            return Ordering::Greater; // other > self
        }
        other
            .cost
            .partial_cmp(&self.cost)
            .unwrap_or(Ordering::Equal)
    }
}

impl PartialOrd for State {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// A pathfinder that uses semantic similarity as a heuristic/cost.
pub struct SemanticPathfinder<'a, G: GraphView + ?Sized> {
    db: &'a G,
    vector_property: String,
}

impl<'a, G: GraphView + ?Sized> SemanticPathfinder<'a, G> {
    /// Creates a new [`SemanticPathfinder`].
    ///
    /// # Arguments
    /// * `db` - Reference to the graph view (e.g., database instance).
    /// * `vector_property` - Name of the property containing vector embeddings.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aletheiadb::db::AletheiaDB;
    /// use aletheiadb::query::semantic_pathfinding::SemanticPathfinder;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let db = AletheiaDB::new()?;
    /// let pathfinder = SemanticPathfinder::new(&db, "embedding");
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(db: &'a G, vector_property: &str) -> Self {
        Self {
            db,
            vector_property: vector_property.to_string(),
        }
    }

    /// Finds a path from `start` to `end` that minimizes semantic distance to the `query_embedding`.
    ///
    /// Uses Dijkstra's algorithm where the edge weight is calculated as:
    /// `1.0 - cosine_similarity(target_node, query_embedding)`.
    /// This heavily favors paths through nodes that are semantically relevant to the query concept.
    /// A small structural cost (0.1) is added per hop to prefer shorter paths when semantics are equal.
    ///
    /// # Arguments
    /// * `start` - Starting [`NodeId`].
    /// * `end` - Target [`NodeId`].
    /// * `query_embedding` - Vector representing the semantic concept to follow.
    /// * `max_depth` - Maximum path length (to prevent infinite loops in large graphs).
    /// * `bidirectional` - If `true`, traverses both outgoing and incoming edges.
    ///
    /// # Returns
    /// An `Ok(Some(Vec<NodeId>))` representing the path from start to end, or `Ok(None)` if no valid path exists within the `max_depth`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aletheiadb::db::AletheiaDB;
    /// use aletheiadb::core::id::NodeId;
    /// use aletheiadb::query::semantic_pathfinding::SemanticPathfinder;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let db = AletheiaDB::new()?;
    /// let pathfinder = SemanticPathfinder::new(&db, "embedding");
    ///
    /// let start = NodeId::new(1).unwrap();
    /// let end = NodeId::new(2).unwrap();
    /// let concept = vec![0.5, 0.5, 0.0];
    ///
    /// if let Some(path) = pathfinder.find_path(start, end, &concept, 5, true)? {
    ///     println!("Found semantic path: {:?}", path);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    /// Returns an error if an underlying database operation fails.
    pub fn find_path(
        &self,
        start: NodeId,
        end: NodeId,
        query_embedding: &[f32],
        max_depth: usize,
        bidirectional: bool,
    ) -> Result<Option<Vec<NodeId>>> {
        let mut pq = BinaryHeap::new();
        // ⚡ Bolt: Use `IdentityHasher` instead of the default SipHash.
        // `NodeId` is already a unique wrapper over `u64`. In pathfinding (like A*),
        // we perform thousands of map insertions and lookups. Bypassing SipHash eliminates
        // unnecessary hashing overhead on already-unique integer keys.
        let mut dist: HashMap<NodeId, f32, BuildHasherDefault<IdentityHasher>> = HashMap::default();
        let mut came_from: HashMap<NodeId, NodeId, BuildHasherDefault<IdentityHasher>> =
            HashMap::default();

        // Initialize start node
        dist.insert(start, 0.0);
        pq.push(State {
            cost: 0.0,
            node: start,
            depth: 0,
        });

        // Reuse allocation across iterations
        // ⚡ Bolt: Pre-allocate neighbor vector with typical branching factor (32) to avoid standard 0->4->8->16->32 heap reallocation chain.
        let mut neighbors = Vec::with_capacity(32);

        while let Some(State { cost, node, depth }) = pq.pop() {
            if node == end {
                return Ok(Some(self.reconstruct_path(came_from, end)));
            }

            // Optimization: Skip if we found a better path already
            #[allow(clippy::collapsible_if)]
            if let Some(&d) = dist.get(&node) {
                if cost > d {
                    continue;
                }
            }

            // Check depth limit
            if depth >= max_depth {
                continue;
            }

            // Collect neighbors (outgoing, or both directions if bidirectional)
            neighbors.clear();

            // Get outgoing edges
            for edge_id in self.db.get_outgoing_edges(node) {
                if let Ok(target) = self.db.get_edge_target(edge_id) {
                    neighbors.push(target);
                }
            }

            // Also get incoming edges if bidirectional
            if bidirectional {
                for edge_id in self.db.get_incoming_edges(node) {
                    if let Ok(edge) = self.db.get_edge(edge_id) {
                        neighbors.push(edge.source);
                    }
                }
            }

            // Process all neighbors
            for &target in &neighbors {
                // Calculate semantic cost of moving to target
                let semantic_cost = self.calculate_semantic_cost(target, query_embedding)?;

                let new_cost = cost + semantic_cost + STRUCTURAL_HOP_COST;

                if new_cost < *dist.get(&target).unwrap_or(&f32::INFINITY) {
                    dist.insert(target, new_cost);
                    came_from.insert(target, node);
                    pq.push(State {
                        cost: new_cost,
                        node: target,
                        depth: depth + 1,
                    });
                }
            }
        }

        Ok(None)
    }

    /// Finds a path at a specific point in time.
    ///
    /// Similar to [`find_path`](Self::find_path), but only considers nodes and edges valid at the specified `time`.
    /// Uses the temporal adjacency index to find edges that existed at the specified
    /// time, even if they have since been deleted from current storage.
    ///
    /// # Arguments
    /// * `start` - Starting [`NodeId`].
    /// * `end` - Target [`NodeId`].
    /// * `query_embedding` - Vector representing the semantic concept to follow.
    /// * `time` - The [`Timestamp`] at which to evaluate the graph state.
    /// * `max_depth` - Maximum path length (to prevent infinite loops in large graphs).
    /// * `bidirectional` - If `true`, traverses both outgoing and incoming edges.
    ///
    /// # Returns
    /// An `Ok(Some(Vec<NodeId>))` representing the path from start to end as it existed at `time`, or `Ok(None)` if no valid path existed within the `max_depth`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aletheiadb::db::AletheiaDB;
    /// use aletheiadb::core::id::NodeId;
    /// use aletheiadb::core::temporal::Timestamp;
    /// use aletheiadb::query::semantic_pathfinding::SemanticPathfinder;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let db = AletheiaDB::new()?;
    /// let pathfinder = SemanticPathfinder::new(&db, "embedding");
    ///
    /// let start = NodeId::new(1).unwrap();
    /// let end = NodeId::new(2).unwrap();
    /// let concept = vec![0.5, 0.5, 0.0];
    /// let historical_time: Timestamp = 1622505600.into();
    ///
    /// if let Some(path) = pathfinder.find_path_at_time(start, end, &concept, historical_time, 5, false)? {
    ///     println!("Found historical semantic path: {:?}", path);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    /// Returns an error if an underlying database operation fails.
    pub fn find_path_at_time(
        &self,
        start: NodeId,
        end: NodeId,
        query_embedding: &[f32],
        time: Timestamp,
        max_depth: usize,
        bidirectional: bool,
    ) -> Result<Option<Vec<NodeId>>> {
        let mut pq = BinaryHeap::new();
        // ⚡ Bolt: Use `IdentityHasher` instead of the default SipHash.
        // `NodeId` is already a unique wrapper over `u64`. In pathfinding (like A*),
        // we perform thousands of map insertions and lookups. Bypassing SipHash eliminates
        // unnecessary hashing overhead on already-unique integer keys.
        let mut dist: HashMap<NodeId, f32, BuildHasherDefault<IdentityHasher>> = HashMap::default();
        let mut came_from: HashMap<NodeId, NodeId, BuildHasherDefault<IdentityHasher>> =
            HashMap::default();

        // Verify start node existed
        if self.db.get_node_at_time(start, time, time).is_err() {
            return Ok(None);
        }

        dist.insert(start, 0.0);
        pq.push(State {
            cost: 0.0,
            node: start,
            depth: 0,
        });

        // Reuse allocation across iterations
        // ⚡ Bolt: Pre-allocate neighbor vector with typical branching factor (32) to avoid standard 0->4->8->16->32 heap reallocation chain.
        let mut neighbor_edges = Vec::with_capacity(32);

        while let Some(State { cost, node, depth }) = pq.pop() {
            if node == end {
                return Ok(Some(self.reconstruct_path(came_from, end)));
            }

            #[allow(clippy::collapsible_if)]
            if let Some(&d) = dist.get(&node) {
                if cost > d {
                    continue;
                }
            }

            // Check depth limit to prevent infinite loops
            if depth >= max_depth {
                continue;
            }

            // Collect neighbors (outgoing, or both directions if bidirectional)
            neighbor_edges.clear();

            // Get outgoing edges at the specified time
            for edge_id in self.db.get_outgoing_edges_at_time(node, time, time) {
                neighbor_edges.push((edge_id, true)); // true = outgoing
            }

            // Also get incoming edges if bidirectional
            if bidirectional {
                for edge_id in self.db.get_incoming_edges_at_time(node, time, time) {
                    neighbor_edges.push((edge_id, false)); // false = incoming
                }
            }

            for &(edge_id, is_outgoing) in &neighbor_edges {
                // Get edge details at the specified time
                if let Ok(edge) = self.db.get_edge_at_time(edge_id, time, time) {
                    // For outgoing edges, target is the neighbor; for incoming, source is the neighbor
                    let target = if is_outgoing {
                        edge.target
                    } else {
                        edge.source
                    };

                    // Check if target node existed at time T (and get embedding)
                    if let Ok(target_node) = self.db.get_node_at_time(target, time, time) {
                        // Calculate semantic cost using historical embedding
                        let target_embedding = target_node
                            .properties
                            .get(&self.vector_property)
                            .and_then(|v| v.as_vector());

                        let semantic_cost =
                            self.compute_semantic_cost(target_embedding, query_embedding)?;

                        let new_cost = cost + semantic_cost + STRUCTURAL_HOP_COST;

                        if new_cost < *dist.get(&target).unwrap_or(&f32::INFINITY) {
                            dist.insert(target, new_cost);
                            came_from.insert(target, node);
                            pq.push(State {
                                cost: new_cost,
                                node: target,
                                depth: depth + 1,
                            });
                        }
                    }
                }
            }
        }

        Ok(None)
    }

    /// Calculate cost based on semantic similarity (1.0 - similarity).
    /// Returns 1.0 (max cost) if node has no embedding.
    fn calculate_semantic_cost(&self, node_id: NodeId, query: &[f32]) -> Result<f32> {
        let node = self.db.get_node(node_id)?;
        let embedding = node
            .properties
            .get(&self.vector_property)
            .and_then(|v| v.as_vector());

        self.compute_semantic_cost(embedding, query)
    }

    /// Helper to compute semantic cost from an embedding slice.
    ///
    /// Handles dimension mismatches gracefully by returning infinite cost.
    fn compute_semantic_cost(&self, embedding: Option<&[f32]>, query: &[f32]) -> Result<f32> {
        if let Some(emb) = embedding {
            match cosine_similarity(emb, query) {
                Ok(sim) => {
                    // Clamp to [0, 2] (cosine sim is [-1, 1])
                    // We want high similarity -> low cost
                    // 1.0 - 1.0 = 0.0 (perfect match)
                    // 1.0 - (-1.0) = 2.0 (opposite)
                    Ok(1.0 - sim)
                }
                Err(crate::core::error::Error::Vector(
                    crate::core::error::VectorError::DimensionMismatch { .. },
                )) => {
                    // Sentry 🛡️: Dimension mismatch implies incompatibility.
                    // Return infinite cost to strictly avoid this node unless no other path exists.
                    // This prevents the entire search from failing due to one malformed node.
                    Ok(f32::INFINITY)
                }
                Err(e) => Err(e),
            }
        } else {
            // Penalize nodes without embeddings
            Ok(NO_EMBEDDING_COST)
        }
    }

    fn reconstruct_path(
        &self,
        came_from: HashMap<NodeId, NodeId, BuildHasherDefault<IdentityHasher>>,
        current: NodeId,
    ) -> Vec<NodeId> {
        let mut path = vec![current];
        let mut curr = current;
        while let Some(&prev) = came_from.get(&curr) {
            path.push(prev);
            curr = prev;
        }
        path.reverse();
        path
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::transaction::WriteOps;
    use crate::core::error::Error;
    use crate::core::property::PropertyMapBuilder;
    use crate::db::AletheiaDB;
    use crate::index::vector::{DistanceMetric, HnswConfig};

    fn create_test_db() -> AletheiaDB {
        let db = AletheiaDB::new().unwrap();
        // Enable vector index to ensure vector properties are handled correctly
        // (though SemanticPathfinder works with raw properties too)
        db.vector_index("embedding")
            .hnsw(HnswConfig::new(3, DistanceMetric::Cosine))
            .enable()
            .unwrap();
        db
    }

    #[test]
    fn test_semantic_pathfinding_prefers_similar_nodes() {
        let db = create_test_db();

        // Topic: "Fruits" (Query will be close to this)
        let fruit_vec = vec![1.0, 0.0, 0.0];

        // Topic: "Tech" (Dissimilar)
        let tech_vec = vec![0.0, 1.0, 0.0];

        // Start
        let start = db
            .create_node(
                "Start",
                PropertyMapBuilder::new()
                    .insert_vector("embedding", &[0.5, 0.5, 0.0])
                    .build(),
            )
            .unwrap();

        // End
        let end = db
            .create_node(
                "End",
                PropertyMapBuilder::new()
                    .insert_vector("embedding", &[0.5, 0.5, 0.0])
                    .build(),
            )
            .unwrap();

        // Path 1: "Apple" (Fruit) -> End
        let apple = db
            .create_node(
                "Apple",
                PropertyMapBuilder::new()
                    .insert_vector("embedding", &fruit_vec)
                    .build(),
            )
            .unwrap();

        // Path 2: "Laptop" (Tech) -> End
        let laptop = db
            .create_node(
                "Laptop",
                PropertyMapBuilder::new()
                    .insert_vector("embedding", &tech_vec)
                    .build(),
            )
            .unwrap();

        // Edges
        db.create_edge(start, apple, "NEXT", PropertyMapBuilder::new().build())
            .unwrap();
        db.create_edge(apple, end, "NEXT", PropertyMapBuilder::new().build())
            .unwrap();

        db.create_edge(start, laptop, "NEXT", PropertyMapBuilder::new().build())
            .unwrap();
        db.create_edge(laptop, end, "NEXT", PropertyMapBuilder::new().build())
            .unwrap();

        // Find path with query "Banana" (Fruit-like)
        let query = vec![0.9, 0.1, 0.0];

        let pathfinder = SemanticPathfinder::new(&db, "embedding");
        let path = pathfinder
            .find_path(start, end, &query, 10, false)
            .unwrap()
            .unwrap();

        // Should prefer Apple over Laptop
        assert_eq!(path.len(), 3);
        assert_eq!(path[0], start);
        assert_eq!(path[1], apple);
        assert_eq!(path[2], end);
    }

    #[test]
    fn test_semantic_pathfinding_time_travel() {
        use crate::core::temporal::time;

        let db = create_test_db();
        let _now = time::now();

        // Create nodes
        let start = db
            .create_node("Start", PropertyMapBuilder::new().build())
            .unwrap();
        let middle = db
            .create_node(
                "Middle",
                PropertyMapBuilder::new()
                    .insert_vector("embedding", &[1.0, 0.0, 0.0])
                    .build(),
            )
            .unwrap();
        let end = db
            .create_node("End", PropertyMapBuilder::new().build())
            .unwrap();

        // Create edges at t0
        // Use write_with_timestamp to ensure t0 covers the creation
        let (_, t_edges) = db
            .write_with_timestamp(|tx| {
                tx.create_edge(start, middle, "NEXT", PropertyMapBuilder::new().build())?;
                tx.create_edge(middle, end, "NEXT", PropertyMapBuilder::new().build())?;
                Ok::<_, Error>(())
            })
            .unwrap();

        let t0 = t_edges;

        let query = vec![1.0, 0.0, 0.0];
        let pathfinder = SemanticPathfinder::new(&db, "embedding");

        // Query at t0: Path should exist (BEFORE DELETION)
        let path_t0 = pathfinder
            .find_path_at_time(start, end, &query, t0, 10, false)
            .unwrap();
        assert!(path_t0.is_some(), "Path should exist at t0 before deletion");

        // Delete "Middle" node at t1 (which should break the path)
        // Use delete_node_cascade to ensure edges are also deleted from current storage
        let (_, t_delete) = db
            .write_with_timestamp(|tx| tx.delete_node_cascade(middle))
            .unwrap();
        let _t1 = t_delete;

        // Verify time monotonicity (HLC guarantees distinct timestamps)
        assert!(
            t_delete > t0,
            "Time must advance monotonically for subsequent transactions"
        );

        // Query at t0 AFTER deletion: With temporal adjacency index (enabled by default),
        // the path SHOULD be found even though edges are deleted from current storage
        let path_t0_after_delete = pathfinder
            .find_path_at_time(start, end, &query, t0, 10, false)
            .unwrap();
        assert!(
            path_t0_after_delete.is_some(),
            "Temporal adjacency index (enabled by default) should find path through deleted edges"
        );
        let path = path_t0_after_delete.unwrap();
        assert_eq!(path.len(), 3);
        assert_eq!(path[0], start);
        assert_eq!(path[1], middle);
        assert_eq!(path[2], end);

        // Test "Future Path" scenario: Path exists now but didn't in past

        let new_middle = db
            .create_node(
                "NewMiddle",
                PropertyMapBuilder::new()
                    .insert_vector("embedding", &[1.0, 0.0, 0.0])
                    .build(),
            )
            .unwrap();

        let (_, t_new_edges) = db
            .write_with_timestamp(|tx| {
                tx.create_edge(start, new_middle, "NEXT", PropertyMapBuilder::new().build())?;
                tx.create_edge(new_middle, end, "NEXT", PropertyMapBuilder::new().build())?;
                Ok::<_, Error>(())
            })
            .unwrap();

        let t2 = t_new_edges;

        // Path exists at t2
        let path_t2 = pathfinder
            .find_path_at_time(start, end, &query, t2, 10, false)
            .unwrap();
        assert!(path_t2.is_some(), "Path should exist at t2");

        // Query at t0 again: Should find the ORIGINAL path through middle
        // (not the new path through new_middle which was created at t2)
        // With temporal adjacency index, deleted edges are still accessible
        // when querying at times before they were deleted.
        let path_t0_check = pathfinder
            .find_path_at_time(start, end, &query, t0, 10, false)
            .unwrap();
        assert!(
            path_t0_check.is_some(),
            "Should find original path at t0 (through middle, not new_middle)"
        );
        // Verify it's the original middle node, not new_middle
        assert_eq!(path_t0_check.as_ref().unwrap()[1], middle);
    }

    mod sentry_tests {
        use super::*;

        #[test]
        fn test_pathfinding_zero_max_depth() {
            let db = create_test_db();
            // Create a minimal graph A -> B
            let a = db
                .create_node("A", PropertyMapBuilder::new().build())
                .unwrap();
            let b = db
                .create_node("B", PropertyMapBuilder::new().build())
                .unwrap();
            db.create_edge(a, b, "NEXT", PropertyMapBuilder::new().build())
                .unwrap();

            let query = vec![0.0; 3];
            let pathfinder = SemanticPathfinder::new(&db, "embedding");

            // Max depth 0 should fail to find path if A != B
            let path = pathfinder.find_path(a, b, &query, 0, false).unwrap();
            assert!(path.is_none(), "Depth 0 should not allow traversal");
        }

        #[test]
        fn test_pathfinding_start_equals_end() {
            let db = create_test_db();
            let a = db
                .create_node("A", PropertyMapBuilder::new().build())
                .unwrap();

            let query = vec![0.0; 3];
            let pathfinder = SemanticPathfinder::new(&db, "embedding");

            // Should find path [A] immediately
            let path = pathfinder.find_path(a, a, &query, 10, false).unwrap();
            assert!(path.is_some());
            assert_eq!(path.unwrap(), vec![a]);
        }

        #[test]
        fn test_pathfinding_disconnected() {
            let db = create_test_db();
            let a = db
                .create_node("A", PropertyMapBuilder::new().build())
                .unwrap();
            let b = db
                .create_node("B", PropertyMapBuilder::new().build())
                .unwrap();

            // No edges

            let query = vec![0.0; 3];
            let pathfinder = SemanticPathfinder::new(&db, "embedding");

            let path = pathfinder.find_path(a, b, &query, 10, false).unwrap();
            assert!(path.is_none());
        }

        #[test]
        fn test_pathfinding_cycle() {
            let db = create_test_db();
            let a = db
                .create_node("A", PropertyMapBuilder::new().build())
                .unwrap();
            let b = db
                .create_node("B", PropertyMapBuilder::new().build())
                .unwrap();

            // Cycle: A -> B -> A
            db.create_edge(a, b, "NEXT", PropertyMapBuilder::new().build())
                .unwrap();
            db.create_edge(b, a, "BACK", PropertyMapBuilder::new().build())
                .unwrap();

            let query = vec![0.0; 3];
            let pathfinder = SemanticPathfinder::new(&db, "embedding");

            // Search for unreachable C
            let c = db
                .create_node("C", PropertyMapBuilder::new().build())
                .unwrap();

            // Should terminate and return None, not hang
            let path = pathfinder.find_path(a, c, &query, 10, false).unwrap();
            assert!(path.is_none());
        }

        #[test]
        fn test_calculate_semantic_cost_dimension_mismatch() {
            let db = create_test_db();
            // Node with 3D vector
            let a = db
                .create_node(
                    "A",
                    PropertyMapBuilder::new()
                        .insert_vector("embedding", &[1.0, 0.0, 0.0])
                        .build(),
                )
                .unwrap();
            let b = db
                .create_node(
                    "B",
                    PropertyMapBuilder::new()
                        .insert_vector("embedding", &[0.0, 1.0, 0.0])
                        .build(),
                )
                .unwrap();

            db.create_edge(a, b, "NEXT", PropertyMapBuilder::new().build())
                .unwrap();

            // Query with 4D vector -> Mismatch!
            let query = vec![0.0; 4];
            let pathfinder = SemanticPathfinder::new(&db, "embedding");

            // Sentry 🛡️: Should handle dimension mismatch gracefully by treating the node as incompatible
            // (infinite cost), effectively blocking the path.
            // Since A->B is the only path, and B is incompatible, it should return Ok(None).
            let result = pathfinder.find_path(a, b, &query, 10, false);
            assert!(result.is_ok());
            assert!(
                result.unwrap().is_none(),
                "Path should be blocked due to dimension mismatch"
            );
        }
    }

    mod sentry_robustness_tests {
        use super::*;
        use crate::api::transaction::WriteOps;
        use crate::core::property::PropertyMapBuilder;
        use crate::db::AletheiaDB;
        use crate::index::vector::{DistanceMetric, HnswConfig}; // Import WriteOps to get create_node/update_node

        fn create_test_db() -> AletheiaDB {
            let db = AletheiaDB::new().unwrap();
            // Enable vector index
            db.vector_index("embedding")
                .hnsw(HnswConfig::new(3, DistanceMetric::Cosine))
                .enable()
                .unwrap();
            db
        }

        #[test]
        fn test_pathfinding_skips_incompatible_dimensions() {
            // 🛡️ Sentry Test: Mixed dimensions should not crash pathfinding.
            // Setup:
            // Start (3D) -> Broken (4D) -> End (3D)
            //            -> Valid (3D)  -> End (3D)
            //
            // Pathfinding should navigate around Broken and use Valid.

            let db = create_test_db();

            // Nodes
            let start = db
                .create_node(
                    "Start",
                    PropertyMapBuilder::new()
                        .insert_vector("embedding", &[1.0, 0.0, 0.0])
                        .build(),
                )
                .unwrap();

            let end = db
                .create_node(
                    "End",
                    PropertyMapBuilder::new()
                        .insert_vector("embedding", &[0.0, 0.0, 1.0])
                        .build(),
                )
                .unwrap();

            // Create nodes with different property name for "broken" 4D vector
            // to bypass potential index validation during creation.
            // We will tell pathfinder to use "embedding_mixed".

            let broken = db
                .create_node(
                    "Broken",
                    PropertyMapBuilder::new()
                        .insert_vector("embedding_mixed", &[0.5, 0.5, 0.5, 0.5])
                        .build(),
                )
                .unwrap();

            let valid = db
                .create_node(
                    "Valid",
                    PropertyMapBuilder::new()
                        .insert_vector("embedding_mixed", &[0.5, 0.5, 0.0])
                        .build(),
                )
                .unwrap();

            // Update Start and End to also use "embedding_mixed" using explicit transaction
            db.write(|tx| {
                tx.update_node(
                    start,
                    PropertyMapBuilder::new()
                        .insert_vector("embedding_mixed", &[1.0, 0.0, 0.0])
                        .build(),
                )
            })
            .unwrap();
            db.write(|tx| {
                tx.update_node(
                    end,
                    PropertyMapBuilder::new()
                        .insert_vector("embedding_mixed", &[0.0, 0.0, 1.0])
                        .build(),
                )
            })
            .unwrap();

            // Connect
            db.create_edge(start, broken, "NEXT", PropertyMapBuilder::new().build())
                .unwrap();
            db.create_edge(broken, end, "NEXT", PropertyMapBuilder::new().build())
                .unwrap();

            db.create_edge(start, valid, "NEXT", PropertyMapBuilder::new().build())
                .unwrap();
            db.create_edge(valid, end, "NEXT", PropertyMapBuilder::new().build())
                .unwrap();

            // Pathfinding
            let query = vec![1.0, 0.0, 0.0];
            let pathfinder = SemanticPathfinder::new(&db, "embedding_mixed");

            let result = pathfinder.find_path(start, end, &query, 10, false);

            match result {
                Ok(Some(p)) => {
                    // If it succeeds, verify it took the valid path
                    assert_eq!(p, vec![start, valid, end], "Should take valid path");
                }
                Ok(None) => panic!("Should find a path (returned None)"),
                Err(e) => {
                    panic!(
                        "Regression: Dimension mismatch error was not suppressed. Expected successful pathfinding skipping invalid node. Error: {}",
                        e
                    );
                }
            }
        }
    }
}