interstellar 0.2.0

A high-performance graph database with Gremlin-style traversals and GQL query language
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
//! Integration tests for mutation steps.
//!
//! Tests for `addV()`, `addE()`, `property()`, and `drop()` mutation steps.

use std::collections::HashMap;

use interstellar::storage::{Graph, GraphMutWrapper, GraphStorage};
use interstellar::traversal::{MutationExecutor, MutationResult, PendingMutation};
use interstellar::value::{EdgeId, Value, VertexId};

// =============================================================================
// Helper functions
// =============================================================================

/// Creates a mutable test storage with some initial data.
/// Used for tests that need direct mutation access.
fn create_mutable_test_storage() -> Graph {
    let graph = Graph::new();

    // Add vertices
    let alice_id = graph.add_vertex(
        "person",
        HashMap::from([
            ("name".to_string(), Value::String("Alice".to_string())),
            ("age".to_string(), Value::Int(30)),
        ]),
    );

    let bob_id = graph.add_vertex(
        "person",
        HashMap::from([
            ("name".to_string(), Value::String("Bob".to_string())),
            ("age".to_string(), Value::Int(25)),
        ]),
    );

    let _software_id = graph.add_vertex(
        "software",
        HashMap::from([("name".to_string(), Value::String("Gremlin".to_string()))]),
    );

    // Add edges
    graph
        .add_edge(
            alice_id,
            bob_id,
            "knows",
            HashMap::from([("since".to_string(), Value::Int(2020))]),
        )
        .unwrap();

    graph
}

/// Creates a test graph with some initial data using the unified API.
fn create_test_graph() -> Graph {
    let graph = Graph::new();

    // Add vertices
    let alice_id = graph.add_vertex(
        "person",
        HashMap::from([
            ("name".to_string(), Value::String("Alice".to_string())),
            ("age".to_string(), Value::Int(30)),
        ]),
    );

    let bob_id = graph.add_vertex(
        "person",
        HashMap::from([
            ("name".to_string(), Value::String("Bob".to_string())),
            ("age".to_string(), Value::Int(25)),
        ]),
    );

    let _software_id = graph.add_vertex(
        "software",
        HashMap::from([("name".to_string(), Value::String("Gremlin".to_string()))]),
    );

    // Add edges
    graph
        .add_edge(
            alice_id,
            bob_id,
            "knows",
            HashMap::from([("since".to_string(), Value::Int(2020))]),
        )
        .unwrap();

    graph
}

/// Executes pending mutations from traversal results.
fn execute_mutations(
    storage: &mut GraphMutWrapper<'_>,
    traversers: impl Iterator<Item = interstellar::traversal::Traverser>,
) -> MutationResult {
    let mut executor = MutationExecutor::new(storage);
    executor.execute(traversers)
}

// =============================================================================
// AddV Tests
// =============================================================================

#[test]
fn add_v_creates_pending_vertex() {
    let graph = Graph::new();
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Execute add_v traversal - creates a pending mutation marker
    let results: Vec<Value> = g.add_v("person").to_list();

    assert_eq!(results.len(), 1);

    // The result should be a pending add_v marker
    if let Value::Map(map) = &results[0] {
        assert!(map.contains_key("__pending_add_v"));
        assert_eq!(map.get("label"), Some(&Value::String("person".to_string())));
    } else {
        panic!("Expected Map value with pending marker");
    }
}

#[test]
fn add_v_with_properties_creates_pending_vertex() {
    let graph = Graph::new();
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Execute add_v with properties
    let results: Vec<Value> = g
        .add_v("person")
        .property("name", "Charlie")
        .property("age", 35i64)
        .to_list();

    assert_eq!(results.len(), 1);

    // Verify the pending marker has properties
    if let Value::Map(map) = &results[0] {
        assert!(map.contains_key("__pending_add_v"));
        if let Some(Value::Map(props)) = map.get("properties") {
            assert_eq!(
                props.get("name"),
                Some(&Value::String("Charlie".to_string()))
            );
            assert_eq!(props.get("age"), Some(&Value::Int(35)));
        } else {
            panic!("Expected properties map");
        }
    } else {
        panic!("Expected Map value");
    }
}

#[test]
fn mutation_executor_creates_vertex() {
    let graph = Graph::new();
    let mut storage = graph.as_storage_mut();
    let initial_count = storage.vertex_count();

    // Create pending add_v mutation
    let mutation = PendingMutation::AddVertex {
        label: "person".to_string(),
        properties: HashMap::from([
            ("name".to_string(), Value::String("Diana".to_string())),
            ("age".to_string(), Value::Int(28)),
        ]),
    };

    // Execute the mutation
    let mut executor = MutationExecutor::new(&mut storage);
    let result = executor.execute_mutation(mutation);

    // Verify vertex was created
    assert!(result.is_some());
    if let Some(Value::Vertex(id)) = result {
        let vertex = storage.get_vertex(id).expect("Vertex should exist");
        assert_eq!(vertex.label, "person");
        assert_eq!(
            vertex.properties.get("name"),
            Some(&Value::String("Diana".to_string()))
        );
        assert_eq!(vertex.properties.get("age"), Some(&Value::Int(28)));
    }

    assert_eq!(storage.vertex_count(), initial_count + 1);
}

#[test]
fn mutation_executor_from_traversal() {
    let graph = Graph::new();
    let mut storage = graph.as_storage_mut();

    // First run the traversal to get pending mutations
    {
        let snapshot = graph.snapshot();
        let g = snapshot.gremlin();

        let traversers: Vec<_> = g
            .add_v("person")
            .property("name", "Eve")
            .execute()
            .collect();

        // Now execute mutations on the actual storage
        let result = execute_mutations(&mut storage, traversers.into_iter());

        assert_eq!(result.vertices_added, 1);
        assert_eq!(result.values.len(), 1);
    }

    // Verify the vertex exists
    assert_eq!(storage.vertex_count(), 1);
    let vertex = storage
        .all_vertices()
        .next()
        .expect("Should have one vertex");
    assert_eq!(vertex.label, "person");
    assert_eq!(
        vertex.properties.get("name"),
        Some(&Value::String("Eve".to_string()))
    );
}

// =============================================================================
// AddE Tests
// =============================================================================

#[test]
fn add_e_creates_pending_edge() {
    let graph = create_test_graph();
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Get vertex IDs
    let vertices: Vec<Value> = g.v().to_list();
    let v1 = vertices[0].as_vertex_id().unwrap();
    let v2 = vertices[1].as_vertex_id().unwrap();

    // Create add_e traversal
    let results: Vec<Value> = g.add_e("friend").from_vertex(v1).to_vertex(v2).to_list();

    assert_eq!(results.len(), 1);

    // Verify pending edge marker
    if let Value::Map(map) = &results[0] {
        assert!(map.contains_key("__pending_add_e"));
        assert_eq!(map.get("label"), Some(&Value::String("friend".to_string())));
        assert_eq!(map.get("from"), Some(&Value::Vertex(v1)));
        assert_eq!(map.get("to"), Some(&Value::Vertex(v2)));
    } else {
        panic!("Expected Map with pending edge marker");
    }
}

#[test]
fn add_e_from_bound_traversal() {
    let graph = create_test_graph();
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Get Alice's vertex ID
    let alice_vertex = g
        .v()
        .has_value("name", "Alice")
        .next()
        .expect("Alice should exist");
    let alice_id = alice_vertex.as_vertex_id().unwrap();

    // Get Bob's vertex ID
    let bob_vertex = g
        .v()
        .has_value("name", "Bob")
        .next()
        .expect("Bob should exist");
    let bob_id = bob_vertex.as_vertex_id().unwrap();

    // Create edge from Alice to Bob using bound traversal
    let results: Vec<Value> = g
        .v_ids([alice_id])
        .add_e("works_with")
        .to_vertex(bob_id)
        .property("project", "Interstellar")
        .to_list();

    assert_eq!(results.len(), 1);

    // Verify pending edge
    if let Value::Map(map) = &results[0] {
        assert!(map.contains_key("__pending_add_e"));
        assert_eq!(map.get("from"), Some(&Value::Vertex(alice_id)));
        assert_eq!(map.get("to"), Some(&Value::Vertex(bob_id)));

        if let Some(Value::Map(props)) = map.get("properties") {
            assert_eq!(
                props.get("project"),
                Some(&Value::String("Interstellar".to_string()))
            );
        }
    }
}

#[test]
fn mutation_executor_creates_edge() {
    let graph = create_mutable_test_storage();
    let mut storage = graph.as_storage_mut();
    let initial_edge_count = storage.edge_count();

    // Get two vertex IDs
    let vertices: Vec<_> = storage.all_vertices().collect();
    let v1 = vertices[0].id;
    let v2 = vertices[1].id;

    // Create pending add_e mutation
    let mutation = PendingMutation::AddEdge {
        label: "colleague".to_string(),
        from: v1,
        to: v2,
        properties: HashMap::from([("dept".to_string(), Value::String("Engineering".to_string()))]),
    };

    let mut executor = MutationExecutor::new(&mut storage);
    let result = executor.execute_mutation(mutation);

    // Verify edge was created
    assert!(result.is_some());
    if let Some(Value::Edge(id)) = result {
        let edge = storage.get_edge(id).expect("Edge should exist");
        assert_eq!(edge.label, "colleague");
        assert_eq!(edge.src, v1);
        assert_eq!(edge.dst, v2);
        assert_eq!(
            edge.properties.get("dept"),
            Some(&Value::String("Engineering".to_string()))
        );
    }

    assert_eq!(storage.edge_count(), initial_edge_count + 1);
}

// =============================================================================
// Property Tests
// =============================================================================

#[test]
fn property_on_vertex_creates_pending_update() {
    let graph = create_test_graph();
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Get a vertex and add a property
    let results: Vec<Value> = g
        .v()
        .has_value("name", "Alice")
        .property("status", "active")
        .to_list();

    assert_eq!(results.len(), 1);

    // Should be a pending property update
    if let Value::Map(map) = &results[0] {
        assert!(map.contains_key("__pending_property_vertex"));
        assert_eq!(map.get("key"), Some(&Value::String("status".to_string())));
        assert_eq!(map.get("value"), Some(&Value::String("active".to_string())));
    }
}

#[test]
fn mutation_executor_sets_vertex_property() {
    let graph = create_mutable_test_storage();
    let mut storage = graph.as_storage_mut();

    // Find Alice's vertex ID
    let alice_id = storage
        .all_vertices()
        .find(|v| v.properties.get("name") == Some(&Value::String("Alice".to_string())))
        .expect("Alice should exist")
        .id;

    // Create pending property mutation
    let mutation = PendingMutation::SetVertexProperty {
        id: alice_id,
        key: "email".to_string(),
        value: Value::String("alice@example.com".to_string()),
    };

    let mut executor = MutationExecutor::new(&mut storage);
    executor.execute_mutation(mutation);

    // Verify property was set
    let alice = storage.get_vertex(alice_id).expect("Alice should exist");
    assert_eq!(
        alice.properties.get("email"),
        Some(&Value::String("alice@example.com".to_string()))
    );
}

#[test]
fn mutation_executor_sets_edge_property() {
    let graph = create_mutable_test_storage();
    let mut storage = graph.as_storage_mut();

    // Get Alice's vertex (she has the outgoing edge)
    let alice = storage
        .all_vertices()
        .find(|v| v.properties.get("name") == Some(&Value::String("Alice".to_string())))
        .expect("Alice should exist");
    let edge = storage
        .out_edges(alice.id)
        .next()
        .expect("Alice should have an outgoing edge");
    let edge_id = edge.id;

    // Create pending edge property mutation
    let mutation = PendingMutation::SetEdgeProperty {
        id: edge_id,
        key: "weight".to_string(),
        value: Value::Float(0.8),
    };

    let mut executor = MutationExecutor::new(&mut storage);
    executor.execute_mutation(mutation);

    // Verify property was set
    let edge = storage.get_edge(edge_id).expect("Edge should exist");
    assert_eq!(edge.properties.get("weight"), Some(&Value::Float(0.8)));
}

// =============================================================================
// Drop Tests
// =============================================================================

#[test]
fn drop_vertex_creates_pending_deletion() {
    let graph = create_test_graph();
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Get a vertex and drop it
    let results: Vec<Value> = g.v().has_value("name", "Alice").drop().to_list();

    assert_eq!(results.len(), 1);

    // Should be a pending drop marker
    if let Value::Map(map) = &results[0] {
        assert!(map.contains_key("__pending_drop_vertex"));
    }
}

#[test]
fn mutation_executor_removes_vertex() {
    let graph = create_mutable_test_storage();
    let mut storage = graph.as_storage_mut();
    let initial_count = storage.vertex_count();

    // Find a vertex to remove
    let vertex_id = storage
        .all_vertices()
        .next()
        .expect("Should have vertices")
        .id;

    let mutation = PendingMutation::DropVertex { id: vertex_id };

    let mut executor = MutationExecutor::new(&mut storage);
    executor.execute_mutation(mutation);

    // Verify vertex was removed
    assert!(storage.get_vertex(vertex_id).is_none());
    assert_eq!(storage.vertex_count(), initial_count - 1);
}

#[test]
fn mutation_executor_removes_edge() {
    let graph = create_mutable_test_storage();
    let mut storage = graph.as_storage_mut();
    let initial_count = storage.edge_count();

    // Find an edge to remove - Alice has the outgoing edge
    let alice = storage
        .all_vertices()
        .find(|v| v.properties.get("name") == Some(&Value::String("Alice".to_string())))
        .expect("Alice should exist");
    let edge_id = storage
        .out_edges(alice.id)
        .next()
        .expect("Alice should have edges")
        .id;

    let mutation = PendingMutation::DropEdge { id: edge_id };

    let mut executor = MutationExecutor::new(&mut storage);
    executor.execute_mutation(mutation);

    // Verify edge was removed
    assert!(storage.get_edge(edge_id).is_none());
    assert_eq!(storage.edge_count(), initial_count - 1);
}

// =============================================================================
// MutationResult Tests
// =============================================================================

#[test]
fn mutation_result_tracks_statistics() {
    let graph = Graph::new();
    let mut storage = graph.as_storage_mut();

    // Create multiple pending mutations
    let traversers = vec![
        interstellar::traversal::Traverser::new(Value::Map(
            ::indexmap::IndexMap::<String, Value>::from_iter([
                ("__pending_add_v".to_string(), Value::Bool(true)),
                ("label".to_string(), Value::String("person".to_string())),
                ("properties".to_string(), Value::Map(Default::default())),
            ]),
        )),
        interstellar::traversal::Traverser::new(Value::Map(
            ::indexmap::IndexMap::<String, Value>::from_iter([
                ("__pending_add_v".to_string(), Value::Bool(true)),
                ("label".to_string(), Value::String("person".to_string())),
                ("properties".to_string(), Value::Map(Default::default())),
            ]),
        )),
    ];

    let result = execute_mutations(&mut storage, traversers.into_iter());

    assert_eq!(result.vertices_added, 2);
    assert_eq!(result.values.len(), 2);
}

#[test]
fn mutation_result_passes_through_non_mutations() {
    let graph = Graph::new();
    let mut storage = graph.as_storage_mut();

    // Mix of pending mutations and regular values
    let traversers = vec![
        interstellar::traversal::Traverser::new(Value::Int(42)),
        interstellar::traversal::Traverser::new(Value::Map(
            ::indexmap::IndexMap::<String, Value>::from_iter([
                ("__pending_add_v".to_string(), Value::Bool(true)),
                ("label".to_string(), Value::String("test".to_string())),
                ("properties".to_string(), Value::Map(Default::default())),
            ]),
        )),
        interstellar::traversal::Traverser::new(Value::String("hello".to_string())),
    ];

    let result = execute_mutations(&mut storage, traversers.into_iter());

    // Should have 3 values: the int, the new vertex, and the string
    assert_eq!(result.values.len(), 3);
    assert_eq!(result.vertices_added, 1);

    // First and third values should be passed through
    assert_eq!(result.values[0], Value::Int(42));
    assert_eq!(result.values[2], Value::String("hello".to_string()));
}

// =============================================================================
// Edge Cases
// =============================================================================

#[test]
fn drop_non_existent_vertex_is_silent() {
    let graph = Graph::new();
    let mut storage = graph.as_storage_mut();

    // Try to drop a vertex that doesn't exist
    let mutation = PendingMutation::DropVertex { id: VertexId(9999) };

    let mut executor = MutationExecutor::new(&mut storage);
    let result = executor.execute_mutation(mutation);

    // Should return None (no error, just silently fails)
    assert!(result.is_none());
}

#[test]
fn add_edge_to_non_existent_vertex_is_silent() {
    let graph = Graph::new();
    let mut storage = graph.as_storage_mut();

    // Try to add edge between non-existent vertices
    let mutation = PendingMutation::AddEdge {
        label: "test".to_string(),
        from: VertexId(1),
        to: VertexId(2),
        properties: HashMap::new(),
    };

    let mut executor = MutationExecutor::new(&mut storage);
    let result = executor.execute_mutation(mutation);

    // Should return None (edge not created)
    assert!(result.is_none());
    assert_eq!(storage.edge_count(), 0);
}

#[test]
fn property_on_non_existent_vertex_is_silent() {
    let graph = Graph::new();
    let mut storage = graph.as_storage_mut();

    let mutation = PendingMutation::SetVertexProperty {
        id: VertexId(9999),
        key: "test".to_string(),
        value: Value::Int(1),
    };

    let mut executor = MutationExecutor::new(&mut storage);
    let result = executor.execute_mutation(mutation);

    // Should return None (property not set)
    assert!(result.is_none());
}

// =============================================================================
// PendingMutation Parsing Tests
// =============================================================================

#[test]
fn pending_mutation_parses_add_v() {
    let value = Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([
        ("__pending_add_v".to_string(), Value::Bool(true)),
        ("label".to_string(), Value::String("test".to_string())),
        (
            "properties".to_string(),
            Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([(
                "key".to_string(),
                Value::String("value".to_string()),
            )])),
        ),
    ]));

    let mutation = PendingMutation::from_value(&value);
    assert!(matches!(
        mutation,
        Some(PendingMutation::AddVertex { label, properties })
        if label == "test" && properties.len() == 1
    ));
}

#[test]
fn pending_mutation_parses_add_e() {
    let value = Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([
        ("__pending_add_e".to_string(), Value::Bool(true)),
        ("label".to_string(), Value::String("edge".to_string())),
        ("from".to_string(), Value::Vertex(VertexId(1))),
        ("to".to_string(), Value::Vertex(VertexId(2))),
        ("properties".to_string(), Value::Map(Default::default())),
    ]));

    let mutation = PendingMutation::from_value(&value);
    assert!(matches!(
        mutation,
        Some(PendingMutation::AddEdge { label, from, to, .. })
        if label == "edge" && from == VertexId(1) && to == VertexId(2)
    ));
}

#[test]
fn pending_mutation_parses_drop_vertex() {
    let value = Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([
        ("__pending_drop_vertex".to_string(), Value::Bool(true)),
        ("id".to_string(), Value::Vertex(VertexId(42))),
    ]));

    let mutation = PendingMutation::from_value(&value);
    assert!(matches!(
        mutation,
        Some(PendingMutation::DropVertex { id }) if id == VertexId(42)
    ));
}

#[test]
fn pending_mutation_parses_drop_edge() {
    let value = Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([
        ("__pending_drop_edge".to_string(), Value::Bool(true)),
        ("id".to_string(), Value::Edge(EdgeId(7))),
    ]));

    let mutation = PendingMutation::from_value(&value);
    assert!(matches!(
        mutation,
        Some(PendingMutation::DropEdge { id }) if id == EdgeId(7)
    ));
}

#[test]
fn pending_mutation_ignores_regular_values() {
    assert!(PendingMutation::from_value(&Value::Int(42)).is_none());
    assert!(PendingMutation::from_value(&Value::String("test".to_string())).is_none());
    assert!(PendingMutation::from_value(&Value::Vertex(VertexId(1))).is_none());
    assert!(PendingMutation::from_value(&Value::Bool(true)).is_none());
}