velesdb-mobile 1.13.8

VelesDB mobile bindings for iOS and Android via UniFFI
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
//! Graph bindings for VelesDB Mobile (UniFFI).
//!
//! Provides UniFFI bindings for graph operations on iOS and Android.

use std::collections::HashMap;
use std::sync::Arc;

use parking_lot::RwLock;

/// A graph node for knowledge graph construction.
#[derive(Debug, Clone, uniffi::Record)]
pub struct MobileGraphNode {
    /// Unique identifier.
    pub id: u64,
    /// Node type/label.
    pub label: String,
    /// JSON properties as string.
    pub properties_json: Option<String>,
    /// Optional vector embedding.
    pub vector: Option<Vec<f32>>,
}

/// A graph edge representing a relationship.
#[derive(Debug, Clone, uniffi::Record)]
pub struct MobileGraphEdge {
    /// Unique identifier.
    pub id: u64,
    /// Source node ID.
    pub source: u64,
    /// Target node ID.
    pub target: u64,
    /// Relationship type.
    pub label: String,
    /// JSON properties as string.
    pub properties_json: Option<String>,
}

/// Traversal result from BFS.
#[derive(Debug, Clone, uniffi::Record)]
pub struct TraversalResult {
    /// Target node ID.
    pub node_id: u64,
    /// Depth from source.
    pub depth: u32,
}

/// In-memory graph store for mobile knowledge graphs.
#[derive(uniffi::Object)]
pub struct MobileGraphStore {
    nodes: RwLock<HashMap<u64, MobileGraphNode>>,
    edges: RwLock<HashMap<u64, MobileGraphEdge>>,
    outgoing: RwLock<HashMap<u64, Vec<u64>>>,
    incoming: RwLock<HashMap<u64, Vec<u64>>>,
}

#[uniffi::export]
impl MobileGraphStore {
    /// Creates a new empty graph store.
    #[uniffi::constructor]
    pub fn new() -> Arc<Self> {
        Arc::new(Self {
            nodes: RwLock::new(HashMap::new()),
            edges: RwLock::new(HashMap::new()),
            outgoing: RwLock::new(HashMap::new()),
            incoming: RwLock::new(HashMap::new()),
        })
    }

    /// Adds a node to the graph.
    pub fn add_node(&self, node: MobileGraphNode) {
        let mut nodes = self.nodes.write();
        nodes.insert(node.id, node);
    }

    /// Adds an edge to the graph.
    ///
    /// # Lock Order
    ///
    /// Acquires locks in consistent order: edges → outgoing → incoming
    /// WITHOUT dropping between operations to ensure atomicity.
    /// This prevents race conditions with concurrent remove_node() calls.
    pub fn add_edge(&self, edge: MobileGraphEdge) -> Result<(), crate::VelesError> {
        // CRITICAL FIX: Acquire all locks BEFORE any mutation
        // and hold them until the operation is complete.
        // Lock order: edges → outgoing → incoming (consistent with remove_node)
        let mut edges = self.edges.write();
        let mut outgoing = self.outgoing.write();
        let mut incoming = self.incoming.write();

        if edges.contains_key(&edge.id) {
            return Err(crate::VelesError::Database {
                message: format!("Edge with ID {} already exists", edge.id),
            });
        }

        let source = edge.source;
        let target = edge.target;
        let id = edge.id;

        // All mutations happen while holding all locks
        edges.insert(id, edge);
        outgoing.entry(source).or_default().push(id);
        incoming.entry(target).or_default().push(id);

        // Locks are released here (all at once) when guards go out of scope
        Ok(())
    }

    /// Gets a node by ID.
    pub fn get_node(&self, id: u64) -> Option<MobileGraphNode> {
        let nodes = self.nodes.read();
        nodes.get(&id).cloned()
    }

    /// Gets an edge by ID.
    pub fn get_edge(&self, id: u64) -> Option<MobileGraphEdge> {
        let edges = self.edges.read();
        edges.get(&id).cloned()
    }

    /// Returns the number of nodes.
    pub fn node_count(&self) -> u64 {
        let nodes = self.nodes.read();
        nodes.len() as u64
    }

    /// Returns the number of edges.
    pub fn edge_count(&self) -> u64 {
        let edges = self.edges.read();
        edges.len() as u64
    }

    /// Gets outgoing edges from a node.
    ///
    /// # Lock Order
    ///
    /// Acquires locks in consistent order: edges → outgoing
    /// to prevent ABBA deadlock with write operations.
    pub fn get_outgoing(&self, node_id: u64) -> Vec<MobileGraphEdge> {
        self.get_edges_from_index(node_id, &self.outgoing)
    }

    /// Gets incoming edges to a node.
    ///
    /// # Lock Order
    ///
    /// Acquires locks in consistent order: edges → incoming
    /// to prevent ABBA deadlock with write operations.
    pub fn get_incoming(&self, node_id: u64) -> Vec<MobileGraphEdge> {
        self.get_edges_from_index(node_id, &self.incoming)
    }

    /// Gets outgoing edges filtered by label.
    pub fn get_outgoing_by_label(&self, node_id: u64, label: String) -> Vec<MobileGraphEdge> {
        self.get_outgoing(node_id)
            .into_iter()
            .filter(|e| e.label == label)
            .collect()
    }

    /// Gets neighbors reachable from a node (1-hop).
    pub fn get_neighbors(&self, node_id: u64) -> Vec<u64> {
        self.get_outgoing(node_id)
            .into_iter()
            .map(|e| e.target)
            .collect()
    }

    /// Performs BFS traversal from a source node.
    ///
    /// # Arguments
    ///
    /// * `source_id` - Starting node ID
    /// * `max_depth` - Maximum traversal depth
    /// * `limit` - Maximum number of results
    pub fn bfs_traverse(&self, source_id: u64, max_depth: u32, limit: u32) -> Vec<TraversalResult> {
        self.bfs_traverse_parallel(vec![source_id], max_depth, limit)
    }

    /// Performs multi-source BFS traversal with deduplication.
    ///
    /// Starts BFS from multiple source nodes simultaneously and deduplicates
    /// results by target node ID (first-seen wins).
    ///
    /// # Arguments
    ///
    /// * `source_ids` - Starting node IDs
    /// * `max_depth` - Maximum traversal depth
    /// * `limit` - Maximum number of results
    pub fn bfs_traverse_parallel(
        &self,
        source_ids: Vec<u64>,
        max_depth: u32,
        limit: u32,
    ) -> Vec<TraversalResult> {
        use std::collections::{HashSet, VecDeque};

        let mut results: Vec<TraversalResult> = Vec::new();
        let mut visited: HashSet<u64> = HashSet::new();
        let mut queue: VecDeque<(u64, u32)> = VecDeque::new();

        for &source_id in &source_ids {
            if visited.insert(source_id) {
                queue.push_back((source_id, 0));
            }
        }

        while let Some((node_id, depth)) = queue.pop_front() {
            if results.len() >= limit as usize {
                break;
            }

            if depth > 0 {
                results.push(TraversalResult { node_id, depth });
            }

            if depth < max_depth {
                for edge in self.get_outgoing(node_id) {
                    if visited.insert(edge.target) {
                        queue.push_back((edge.target, depth + 1));
                    }
                }
            }
        }

        results
    }

    /// Removes a node and all connected edges.
    ///
    /// # Lock Order
    ///
    /// Acquires locks in consistent order: edges → outgoing → incoming → nodes
    /// to prevent deadlock with concurrent add_edge() calls.
    pub fn remove_node(&self, node_id: u64) {
        // CRITICAL: Acquire locks in consistent order (edges → outgoing → incoming → nodes)
        // to prevent deadlock with add_edge() which uses (edges → outgoing → incoming)
        let mut edges = self.edges.write();
        let mut outgoing = self.outgoing.write();
        let mut incoming = self.incoming.write();
        let mut nodes = self.nodes.write();

        nodes.remove(&node_id);

        let outgoing_ids: Vec<u64> = outgoing.remove(&node_id).unwrap_or_default();
        for edge_id in outgoing_ids {
            if let Some(edge) = edges.remove(&edge_id) {
                if let Some(ids) = incoming.get_mut(&edge.target) {
                    ids.retain(|&id| id != edge_id);
                }
            }
        }

        let incoming_ids: Vec<u64> = incoming.remove(&node_id).unwrap_or_default();
        for edge_id in incoming_ids {
            if let Some(edge) = edges.remove(&edge_id) {
                if let Some(ids) = outgoing.get_mut(&edge.source) {
                    ids.retain(|&id| id != edge_id);
                }
            }
        }
    }

    /// Removes an edge by ID.
    ///
    /// # Lock Order
    ///
    /// Acquires locks in consistent order: edges → outgoing → incoming
    /// WITHOUT dropping between operations to ensure atomicity.
    pub fn remove_edge(&self, edge_id: u64) {
        // CRITICAL FIX: Acquire all locks BEFORE any mutation
        let mut edges = self.edges.write();
        let mut outgoing = self.outgoing.write();
        let mut incoming = self.incoming.write();

        if let Some(edge) = edges.remove(&edge_id) {
            if let Some(ids) = outgoing.get_mut(&edge.source) {
                ids.retain(|&id| id != edge_id);
            }
            if let Some(ids) = incoming.get_mut(&edge.target) {
                ids.retain(|&id| id != edge_id);
            }
        }
        // All locks released here
    }

    /// Clears all nodes and edges.
    ///
    /// # Lock Order
    ///
    /// Acquires locks in consistent order: edges → outgoing → incoming → nodes
    pub fn clear(&self) {
        // Consistent lock order: edges → outgoing → incoming → nodes
        let mut edges = self.edges.write();
        let mut outgoing = self.outgoing.write();
        let mut incoming = self.incoming.write();
        let mut nodes = self.nodes.write();

        edges.clear();
        outgoing.clear();
        incoming.clear();
        nodes.clear();
    }

    /// Performs DFS traversal from a source node.
    ///
    /// # Arguments
    ///
    /// * `source_id` - Starting node ID
    /// * `max_depth` - Maximum traversal depth
    /// * `limit` - Maximum number of results
    pub fn dfs_traverse(&self, source_id: u64, max_depth: u32, limit: u32) -> Vec<TraversalResult> {
        use std::collections::HashSet;

        let mut results: Vec<TraversalResult> = Vec::new();
        let mut visited: HashSet<u64> = HashSet::new();
        let mut stack: Vec<(u64, u32)> = vec![(source_id, 0)];

        while let Some((node_id, depth)) = stack.pop() {
            if results.len() >= limit as usize {
                break;
            }

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

            if depth > 0 {
                results.push(TraversalResult { node_id, depth });
            }

            if depth < max_depth {
                let neighbors: Vec<_> = self
                    .get_outgoing(node_id)
                    .into_iter()
                    .filter(|e| !visited.contains(&e.target))
                    .collect();

                for edge in neighbors.into_iter().rev() {
                    stack.push((edge.target, depth + 1));
                }
            }
        }

        results
    }

    /// Checks if a node exists.
    pub fn has_node(&self, id: u64) -> bool {
        let nodes = self.nodes.read();
        nodes.contains_key(&id)
    }

    /// Checks if an edge exists.
    pub fn has_edge(&self, id: u64) -> bool {
        let edges = self.edges.read();
        edges.contains_key(&id)
    }

    /// Gets the out-degree (number of outgoing edges) of a node.
    #[allow(clippy::cast_possible_truncation)]
    pub fn out_degree(&self, node_id: u64) -> u32 {
        let outgoing = self.outgoing.read();
        // Safe: graph degree unlikely to exceed u32::MAX (4 billion edges from one node)
        outgoing.get(&node_id).map_or(0, |v| v.len() as u32)
    }

    /// Gets the in-degree (number of incoming edges) of a node.
    #[allow(clippy::cast_possible_truncation)]
    pub fn in_degree(&self, node_id: u64) -> u32 {
        let incoming = self.incoming.read();
        // Safe: graph degree unlikely to exceed u32::MAX (4 billion edges to one node)
        incoming.get(&node_id).map_or(0, |v| v.len() as u32)
    }

    /// Gets all nodes with a specific label.
    pub fn get_nodes_by_label(&self, label: String) -> Vec<MobileGraphNode> {
        let nodes = self.nodes.read();
        nodes
            .values()
            .filter(|n| n.label == label)
            .cloned()
            .collect()
    }

    /// Gets all edges with a specific label.
    pub fn get_edges_by_label(&self, label: String) -> Vec<MobileGraphEdge> {
        let edges = self.edges.read();
        edges
            .values()
            .filter(|e| e.label == label)
            .cloned()
            .collect()
    }
}

/// Internal helpers (not exposed via UniFFI).
impl MobileGraphStore {
    /// Resolves edge IDs from an adjacency index to full edge objects.
    ///
    /// # Lock Order
    ///
    /// Acquires `edges` read-lock first, then the `index` read-lock, matching
    /// the write-side lock order (edges -> outgoing -> incoming).
    fn get_edges_from_index(
        &self,
        node_id: u64,
        index: &RwLock<HashMap<u64, Vec<u64>>>,
    ) -> Vec<MobileGraphEdge> {
        let edges = self.edges.read();
        let idx = index.read();
        idx.get(&node_id)
            .map(|ids| ids.iter().filter_map(|id| edges.get(id).cloned()).collect())
            .unwrap_or_default()
    }
}

impl Default for MobileGraphStore {
    fn default() -> Self {
        Self {
            nodes: RwLock::new(HashMap::new()),
            edges: RwLock::new(HashMap::new()),
            outgoing: RwLock::new(HashMap::new()),
            incoming: RwLock::new(HashMap::new()),
        }
    }
}

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

    /// Creates a test node with the given ID and "Person" label.
    fn person_node(id: u64) -> MobileGraphNode {
        MobileGraphNode {
            id,
            label: "Person".to_string(),
            properties_json: None,
            vector: None,
        }
    }

    /// Creates a test edge with the given ID, source, and target ("KNOWS" label).
    fn knows_edge(id: u64, source: u64, target: u64) -> MobileGraphEdge {
        MobileGraphEdge {
            id,
            source,
            target,
            label: "KNOWS".to_string(),
            properties_json: None,
        }
    }

    /// Creates a store with nodes [1..=count] and returns it.
    fn store_with_nodes(count: u64) -> Arc<MobileGraphStore> {
        let store = MobileGraphStore::new();
        for i in 1..=count {
            store.add_node(person_node(i));
        }
        store
    }

    #[test]
    fn test_mobile_graph_node_creation() {
        let node = MobileGraphNode {
            id: 1,
            label: "Person".to_string(),
            properties_json: Some(r#"{"name": "John"}"#.to_string()),
            vector: None,
        };
        assert_eq!(node.id, 1);
        assert_eq!(node.label, "Person");
    }

    #[test]
    fn test_mobile_graph_edge_creation() {
        let edge = knows_edge(100, 1, 2);
        assert_eq!(edge.id, 100);
        assert_eq!(edge.source, 1);
        assert_eq!(edge.target, 2);
    }

    #[test]
    fn test_mobile_graph_store_add_nodes() {
        let store = store_with_nodes(1);
        assert_eq!(store.node_count(), 1);
    }

    #[test]
    fn test_mobile_graph_store_add_edges() {
        let store = store_with_nodes(2);
        let result = store.add_edge(knows_edge(100, 1, 2));
        assert!(result.is_ok());
        assert_eq!(store.edge_count(), 1);
    }

    #[test]
    fn test_mobile_graph_store_duplicate_edge_error() {
        let store = store_with_nodes(2);
        let _ = store.add_edge(knows_edge(100, 1, 2));
        let result = store.add_edge(knows_edge(100, 1, 2));
        assert!(result.is_err());
    }

    #[test]
    fn test_mobile_graph_store_get_outgoing() {
        let store = store_with_nodes(3);
        let _ = store.add_edge(knows_edge(100, 1, 2));
        let _ = store.add_edge(knows_edge(101, 1, 3));
        assert_eq!(store.get_outgoing(1).len(), 2);
    }

    #[test]
    fn test_mobile_graph_store_bfs_traverse() {
        let store = store_with_nodes(4);

        // Create chain: 1 -> 2 -> 3 -> 4
        let _ = store.add_edge(knows_edge(100, 1, 2));
        let _ = store.add_edge(knows_edge(101, 2, 3));
        let _ = store.add_edge(knows_edge(102, 3, 4));

        let results = store.bfs_traverse(1, 3, 100);

        // Should find nodes 2, 3, 4 at depths 1, 2, 3
        assert_eq!(results.len(), 3);
        assert!(results.iter().any(|r| r.node_id == 2 && r.depth == 1));
        assert!(results.iter().any(|r| r.node_id == 3 && r.depth == 2));
        assert!(results.iter().any(|r| r.node_id == 4 && r.depth == 3));
    }

    #[test]
    fn test_mobile_graph_store_remove_node() {
        let store = store_with_nodes(2);
        let _ = store.add_edge(knows_edge(100, 1, 2));

        assert_eq!(store.node_count(), 2);
        assert_eq!(store.edge_count(), 1);

        store.remove_node(1);

        assert_eq!(store.node_count(), 1);
        assert_eq!(store.edge_count(), 0); // Edge should be removed too
    }

    #[test]
    fn test_mobile_graph_store_remove_edge() {
        let store = store_with_nodes(2);
        let _ = store.add_edge(knows_edge(100, 1, 2));

        assert_eq!(store.edge_count(), 1);

        store.remove_edge(100);

        assert_eq!(store.edge_count(), 0);
        assert!(store.get_outgoing(1).is_empty());
        assert!(store.get_incoming(2).is_empty());
    }

    #[test]
    fn test_mobile_graph_store_clear() {
        let store = store_with_nodes(2);
        let _ = store.add_edge(knows_edge(100, 1, 2));

        store.clear();

        assert_eq!(store.node_count(), 0);
        assert_eq!(store.edge_count(), 0);
    }
}