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
//! Prophet: Link Prediction Engine.
//!
//! Why do some nodes connect while others remain isolated? The [`Prophet`] engine attempts to
//! answer this by predicting missing links in the graph. Unlike traditional link prediction
//! that relies solely on graph topology (like mutual friends), `Prophet` bridges the gap
//! between **structural topology** and **semantic vector similarity**.
//!
//! It combines the Adamic-Adar index (which measures topological closeness) with cosine
//! similarity of the nodes' vector embeddings. This means it recommends connections not just
//! because nodes share a neighborhood, but because they are structurally positioned *and*
//! conceptually aligned to connect.
//!
//! # The Algorithm
//! The prediction score between two unconnected nodes $A$ and $B$ is calculated as:
//!
//! `Score(A, B) = AdamicAdar(A, B) * (1.0 + VectorSimilarity(A, B))`
//!
//! - **Adamic-Adar:** Sum of $\frac{1}{\log(degree(z))}$ for all shared neighbors $z$.
//! - **Vector Similarity:** Cosine similarity of the vector embeddings between $A$ and $B$.
//!
//! If vectors are perfectly orthogonal, the score reverts to standard Adamic-Adar. If they
//! are similar, the topological score is boosted, surfacing structurally valid but semantically
//! richer recommendations.
//!
//! # Examples
//!
//! > ⚠️ **REQUIRES FEATURE: nova**
//!
//! ```rust
//! // [dependencies]
//! // aletheiadb = { version = "0.1", features = ["nova"] }
//!
//! # #[cfg(feature = "semantic-reasoning")]
//! use aletheiadb::AletheiaDB;
//! # #[cfg(feature = "semantic-reasoning")]
//! use aletheiadb::experimental::prophet::Prophet;
//! # #[cfg(feature = "semantic-reasoning")]
//! use aletheiadb::core::property::PropertyMapBuilder;
//!
//! # #[cfg(feature = "semantic-reasoning")]
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let db = AletheiaDB::new()?;
//!
//! // Assume we have a graph of users and their interests.
//! // We want to recommend new connections for User A.
//! # let props = PropertyMapBuilder::new().build();
//! # let node_a = db.create_node("User", props.clone())?;
//! # let node_b = db.create_node("User", props.clone())?;
//! # let node_c = db.create_node("User", props.clone())?;
//! # db.create_edge(node_a, node_b, "KNOWS", props.clone())?;
//! # db.create_edge(node_b, node_c, "KNOWS", props)?;
//!
//! let prophet = Prophet::new(&db);
//!
//! // Predict the top 5 most likely future connections for node_a
//! let predictions = prophet.predict_links(node_a, 5)?;
//!
//! for (target_node, score) in predictions {
//!     println!("Predicted connection to node {} with confidence score {}", target_node, score);
//! }
//! # Ok(())
//! # }
//! # #[cfg(not(feature = "semantic-reasoning"))]
//! # fn main() {}
//! ```

use crate::AletheiaDB;
use crate::core::error::Result;
use crate::core::id::NodeId;
use crate::core::vector::cosine_similarity;
use std::collections::HashSet;

/// The engine for predicting missing or future connections in the graph.
///
/// `Prophet` operates by combining topological network structure with vector semantics.
/// It uses the Adamic-Adar index to find structurally likely connections, and then scales
/// that probability by the cosine similarity of the nodes' vector embeddings.
///
/// This requires a [`AletheiaDB`] instance to query both the graph topology and the
/// vector properties. By default, it will use the first registered vector index it finds.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "semantic-reasoning")]
/// use aletheiadb::AletheiaDB;
/// # #[cfg(feature = "semantic-reasoning")]
/// use aletheiadb::experimental::prophet::Prophet;
///
/// # #[cfg(feature = "semantic-reasoning")]
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = AletheiaDB::new()?;
/// // Initialize the prophet engine attached to the database
/// let prophet = Prophet::new(&db);
/// # Ok(())
/// # }
/// # #[cfg(not(feature = "semantic-reasoning"))]
/// # fn main() {}
/// ```
pub struct Prophet<'a> {
    db: &'a AletheiaDB,
    /// Optional vector property override.
    property_name: Option<String>,
}

impl<'a> Prophet<'a> {
    /// Initializes a new link prediction engine bound to the given database.
    ///
    /// By default, the engine will attempt to automatically discover the primary vector property
    /// by querying the database's registered vector indexes. If you have multiple vector indexes
    /// and need to target a specific one, use [`Prophet::with_property`] after initialization.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "semantic-reasoning")]
    /// use aletheiadb::AletheiaDB;
    /// # #[cfg(feature = "semantic-reasoning")]
    /// use aletheiadb::experimental::prophet::Prophet;
    ///
    /// # #[cfg(feature = "semantic-reasoning")]
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let db = AletheiaDB::new()?;
    /// let prophet = Prophet::new(&db);
    /// # Ok(())
    /// # }
    /// # #[cfg(not(feature = "semantic-reasoning"))]
    /// # fn main() {}
    /// ```
    pub fn new(db: &'a AletheiaDB) -> Self {
        Self {
            db,
            property_name: None,
        }
    }

    /// Specifies the exact vector property name to use for calculating semantic similarity.
    ///
    /// This is required if the database contains multiple vector properties (e.g., "title_embedding"
    /// and "body_embedding") and you want to base predictions on a specific semantic domain.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "semantic-reasoning")]
    /// use aletheiadb::AletheiaDB;
    /// # #[cfg(feature = "semantic-reasoning")]
    /// use aletheiadb::experimental::prophet::Prophet;
    ///
    /// # #[cfg(feature = "semantic-reasoning")]
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let db = AletheiaDB::new()?;
    /// // Force the prophet to only consider the "bio_embedding" property for similarity
    /// let prophet = Prophet::new(&db).with_property("bio_embedding");
    /// # Ok(())
    /// # }
    /// # #[cfg(not(feature = "semantic-reasoning"))]
    /// # fn main() {}
    /// ```
    pub fn with_property(mut self, name: impl Into<String>) -> Self {
        self.property_name = Some(name.into());
        self
    }

    /// Resolve the property name to use.
    fn get_property_name(&self) -> Result<String> {
        if let Some(ref name) = self.property_name {
            return Ok(name.clone());
        }

        let indexes = self.db.list_vector_indexes();
        if let Some(idx_info) = indexes.first() {
            Ok(idx_info.property_name.clone())
        } else {
            // It's okay if no vector index exists, we just won't use vector scoring.
            Ok("".to_string())
        }
    }

    /// Get neighbors of a node (undirected: outgoing U incoming).
    fn get_neighbors(&self, node_id: NodeId) -> Result<HashSet<NodeId>> {
        let out_edges = self.db.get_outgoing_edges(node_id);
        let in_edges = self.db.get_incoming_edges(node_id);

        let mut neighbors = HashSet::with_capacity(out_edges.len() + in_edges.len());

        for eid in out_edges {
            let target = self.db.get_edge_target(eid)?;
            neighbors.insert(target);
        }
        for eid in in_edges {
            let source = self.db.get_edge_source(eid)?;
            neighbors.insert(source);
        }

        Ok(neighbors)
    }

    /// Calculate Adamic-Adar score between two nodes.
    /// Sum(1 / log(degree(z))) for z in CommonNeighbors(x, y).
    fn adamic_adar(&self, neighbors_a: &HashSet<NodeId>, neighbors_b: &HashSet<NodeId>) -> f32 {
        let mut score = 0.0;
        for &neighbor in neighbors_a {
            if neighbors_b.contains(&neighbor) {
                // We use out_degree + in_degree as total degree proxy.
                let degree = self.db.out_degree(neighbor) + self.db.in_degree(neighbor);
                if degree > 1 {
                    score += 1.0 / (degree as f32).ln();
                }
            }
        }
        score
    }

    /// Get vector similarity between two nodes.
    fn vector_similarity(&self, a: NodeId, b: NodeId, property: &str) -> f32 {
        if property.is_empty() {
            return 0.0;
        }

        // Helper to get vector
        let get_vec = |id| -> Option<Vec<f32>> {
            self.db
                .get_node(id)
                .ok()?
                .properties
                .get(property)?
                .as_vector()
                .map(|v| v.to_vec())
        };

        let vec_a = match get_vec(a) {
            Some(v) => v,
            None => return 0.0,
        };
        let vec_b = match get_vec(b) {
            Some(v) => v,
            None => return 0.0,
        };

        // Cosine Similarity
        cosine_similarity(&vec_a, &vec_b).unwrap_or(0.0)
    }

    /// Predicts the most likely new connections for the given target node.
    ///
    /// This method performs a graph traversal to find "neighbors of neighbors" and evaluates them
    /// as candidates. It calculates an Adamic-Adar score for topological closeness and then multiplies
    /// it by `(1.0 + vector_similarity)`.
    ///
    /// The algorithm deliberately returns the top `k` candidates, ranked by this combined score.
    ///
    /// # Arguments
    ///
    /// * `target` - The `NodeId` for which you want to predict new links.
    /// * `k` - The maximum number of recommendations to return (e.g., "Top 5").
    ///
    /// # Returns
    ///
    /// A sorted vector of tuples containing `(CandidateNodeId, PredictionScore)`,
    /// ordered descending from most likely to least likely.
    ///
    /// # Edge Cases
    ///
    /// - If `target` has no neighbors, it will have no "neighbors of neighbors" to evaluate, returning an empty list.
    /// - If the database has no vector properties or missing vectors, the similarity score defaults to 0.0 (falling back to pure Adamic-Adar).
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "semantic-reasoning")]
    /// use aletheiadb::AletheiaDB;
    /// # #[cfg(feature = "semantic-reasoning")]
    /// use aletheiadb::experimental::prophet::Prophet;
    /// # #[cfg(feature = "semantic-reasoning")]
    /// use aletheiadb::core::property::PropertyMapBuilder;
    ///
    /// # #[cfg(feature = "semantic-reasoning")]
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let db = AletheiaDB::new()?;
    /// # let props = PropertyMapBuilder::new().build();
    /// # let user = db.create_node("User", props.clone())?;
    /// # let intermediate = db.create_node("User", props.clone())?;
    /// # let candidate = db.create_node("User", props.clone())?;
    /// # db.create_edge(user, intermediate, "KNOWS", props.clone())?;
    /// # db.create_edge(intermediate, candidate, "KNOWS", props)?;
    ///
    /// let prophet = Prophet::new(&db);
    ///
    /// // Recommend top 3 connections
    /// let recommendations = prophet.predict_links(user, 3)?;
    ///
    /// if let Some((top_candidate, top_score)) = recommendations.first() {
    ///     println!("Top recommendation: {} (score: {})", top_candidate, top_score);
    /// }
    /// # Ok(())
    /// # }
    /// # #[cfg(not(feature = "semantic-reasoning"))]
    /// # fn main() {}
    /// ```
    pub fn predict_links(&self, target: NodeId, k: usize) -> Result<Vec<(NodeId, f32)>> {
        let neighbors = self.get_neighbors(target)?;

        // 1. Gather candidates (Neighbors of Neighbors)
        // We exclude existing neighbors and self.
        let mut candidates = HashSet::new();
        for &neighbor in &neighbors {
            if let Ok(neighbor_neighbors) = self.get_neighbors(neighbor) {
                for &candidate in &neighbor_neighbors {
                    if candidate != target && !neighbors.contains(&candidate) {
                        candidates.insert(candidate);
                    }
                }
            }
        }

        // 2. Score candidates
        let property = self.get_property_name()?;
        let mut scored_candidates = Vec::with_capacity(candidates.len());

        for candidate in candidates {
            if let Ok(candidate_neighbors) = self.get_neighbors(candidate) {
                let topo_score = self.adamic_adar(&neighbors, &candidate_neighbors);
                let vec_score = self.vector_similarity(target, candidate, &property);

                // Final Score = Topo * (1 + Vec)
                // This boosts topologically relevant nodes if they are also semantically similar.
                let final_score = topo_score * (1.0 + vec_score);

                if final_score > 0.0 {
                    scored_candidates.push((candidate, final_score));
                }
            }
        }

        // 3. Sort and truncate
        scored_candidates
            .sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        if scored_candidates.len() > k {
            scored_candidates.truncate(k);
        }

        Ok(scored_candidates)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::property::PropertyMapBuilder;
    use crate::index::vector::{DistanceMetric, HnswConfig};

    #[test]
    fn test_prophet_diamond_prediction() {
        // Create a diamond-like structure where A and D share common neighbors B and C.
        // A -> B, A -> C
        // B -> D, C -> D
        // Prophet should predict A -> D.

        let db = AletheiaDB::new().unwrap();
        let props = PropertyMapBuilder::new().build();

        let a = db.create_node("Node", props.clone()).unwrap();
        let b = db.create_node("Node", props.clone()).unwrap();
        let c = db.create_node("Node", props.clone()).unwrap();
        let d = db.create_node("Node", props.clone()).unwrap();

        db.create_edge(a, b, "KNOWS", props.clone()).unwrap();
        db.create_edge(a, c, "KNOWS", props.clone()).unwrap();
        db.create_edge(b, d, "KNOWS", props.clone()).unwrap();
        db.create_edge(c, d, "KNOWS", props.clone()).unwrap();

        let prophet = Prophet::new(&db);
        let predictions = prophet.predict_links(a, 5).unwrap();

        // Should find D
        assert!(!predictions.is_empty());
        assert_eq!(predictions[0].0, d);
        assert!(predictions[0].1 > 0.0);
    }

    #[test]
    fn test_prophet_vector_boost() {
        // A -> B, A -> C
        // B -> D, C -> D (D is a topological candidate)
        // B -> E, C -> E (E is also a topological candidate, same score as D)
        //
        // But A and D have similar vectors, A and E do not.
        // D should score higher than E.

        let db = AletheiaDB::new().unwrap();
        let config = HnswConfig::new(2, DistanceMetric::Cosine);
        db.enable_vector_index("embedding", config).unwrap();

        // A: [1, 0]
        let p_a = PropertyMapBuilder::new()
            .insert_vector("embedding", &[1.0, 0.0])
            .build();
        let a = db.create_node("Node", p_a).unwrap();

        // B, C (Connectors)
        let p_x = PropertyMapBuilder::new().build();
        let b = db.create_node("Node", p_x.clone()).unwrap();
        let c = db.create_node("Node", p_x.clone()).unwrap();

        // D: [1, 0] (Similar to A)
        let p_d = PropertyMapBuilder::new()
            .insert_vector("embedding", &[1.0, 0.0])
            .build();
        let d = db.create_node("Node", p_d).unwrap();

        // E: [0, 1] (Orthogonal to A)
        let p_e = PropertyMapBuilder::new()
            .insert_vector("embedding", &[0.0, 1.0])
            .build();
        let e = db.create_node("Node", p_e).unwrap();

        // Edges
        db.create_edge(a, b, "KNOWS", p_x.clone()).unwrap();
        db.create_edge(a, c, "KNOWS", p_x.clone()).unwrap();

        db.create_edge(b, d, "KNOWS", p_x.clone()).unwrap();
        db.create_edge(c, d, "KNOWS", p_x.clone()).unwrap();

        db.create_edge(b, e, "KNOWS", p_x.clone()).unwrap();
        db.create_edge(c, e, "KNOWS", p_x.clone()).unwrap();

        let prophet = Prophet::new(&db);
        let predictions = prophet.predict_links(a, 5).unwrap();

        assert!(predictions.len() >= 2);

        let d_score = predictions
            .iter()
            .find(|(id, _)| *id == d)
            .map(|(_, s)| *s)
            .unwrap();
        let e_score = predictions
            .iter()
            .find(|(id, _)| *id == e)
            .map(|(_, s)| *s)
            .unwrap();

        assert!(
            d_score > e_score,
            "D should rank higher than E due to vector similarity (D: {}, E: {})",
            d_score,
            e_score
        );
    }
}