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
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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
//! Composition tests for complex traversal chains.
//!
//! Phase 3 of the integration test strategy. Tests for:
//! - Deep navigation chains (5+ tests)
//! - Mixed step type chains (5+ tests)
//! - Nested anonymous traversals (5+ tests)
//! - Complex real-world queries (10+ tests)

#![allow(unused_variables)]

use std::collections::HashMap;

use interstellar::p;
use interstellar::storage::Graph;
use interstellar::traversal::__;
use interstellar::value::{Value, VertexId};

use crate::common::graphs::{
    create_dense_graph, create_medium_graph, create_small_graph, create_social_graph,
};

// =============================================================================
// Deep Navigation Chains
// =============================================================================

#[test]
fn six_step_navigation_chain() {
    let tg = create_social_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // 6-step navigation chain through the social graph
    // Alice -> knows -> Bob -> knows -> Charlie -> knows -> Alice (cycle)
    // Then out to created/uses edges
    let results = g
        .v_ids([tg.alice])
        .out_labels(&["knows"]) // 1: Alice -> Bob
        .out_labels(&["knows"]) // 2: Bob -> Charlie
        .out_labels(&["knows"]) // 3: Charlie -> Alice (cycle)
        .out_labels(&["knows"]) // 4: Alice -> Bob again
        .out_labels(&["knows"]) // 5: Bob -> Charlie again
        .out_labels(&["knows"]) // 6: Charlie -> Alice again
        .dedup()
        .to_list();

    // With cycle, we should still get unique results
    assert!(!results.is_empty());
    assert!(results.len() <= 3); // At most 3 unique people in the cycle
}

#[test]
fn deep_out_in_alternating_chain() {
    let tg = create_social_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Alternating out/in creates interesting traversal patterns
    let results = g
        .v_ids([tg.alice])
        .out_labels(&["knows"]) // Alice -> Bob
        .in_labels(&["knows"]) // Bob <- Alice (back to Alice)
        .out_labels(&["knows"]) // Alice -> Bob
        .in_labels(&["knows"]) // Bob <- Alice
        .out_labels(&["knows"]) // Alice -> Bob
        .dedup()
        .to_list();

    // Should stabilize to vertices in the knows relationship
    assert!(!results.is_empty());
}

#[test]
fn deep_bidirectional_exploration() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Explore in both directions multiple times
    let results = g
        .v_ids([tg.bob])
        .both_labels(&["knows"]) // Bob's knows neighbors (Alice, Charlie)
        .both_labels(&["knows"]) // Their knows neighbors
        .both_labels(&["knows"]) // And again
        .dedup()
        .to_list();

    // Should find all people in the knows network
    let ids: Vec<VertexId> = results.iter().filter_map(|v| v.as_vertex_id()).collect();
    assert!(ids.contains(&tg.alice) || ids.contains(&tg.bob) || ids.contains(&tg.charlie));
}

#[test]
fn deep_chain_with_multiple_labels() {
    let tg = create_social_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Navigate through different edge types
    let results = g
        .v_ids([tg.alice])
        .out_labels(&["knows"]) // Alice -> Bob
        .out_labels(&["created"]) // Bob -> Redis (in social graph)
        .in_labels(&["uses"]) // Redis <- Eve (uses)
        .out_labels(&["uses"]) // Eve -> Redis (back)
        .in_labels(&["created"]) // Redis <- Bob
        .to_list();

    // Complex path through the graph
    // May be empty or have results depending on exact graph structure
    let _ = results;
}

#[test]
fn deep_chain_terminates_on_dead_end() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Chain that should hit a dead end
    let results = g
        .v_ids([tg.graphdb])
        .out() // GraphDB has no outgoing edges
        .out() // Still nothing
        .out() // Still nothing
        .out() // Still nothing
        .to_list();

    // Should be empty since GraphDB has no outgoing edges
    assert!(results.is_empty());
}

#[test]
fn deep_chain_with_limit_at_end() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Deep chain with limit to control result size
    let results = g
        .v_ids([tg.alice])
        .repeat(__.out_labels(&["knows"]))
        .times(5)
        .emit()
        .dedup()
        .limit(2)
        .to_list();

    assert!(results.len() <= 2);
}

// =============================================================================
// Mixed Step Type Chains
// =============================================================================

#[test]
fn filter_navigation_transform_chain() {
    let tg = create_social_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Mix filter, navigation, and transform steps
    let results = g
        .v()
        .has_label("person") // filter
        .has_where("age", p::gte(25i64)) // filter with predicate
        .out_labels(&["knows"]) // navigation
        .has_label("person") // filter
        .values("name") // transform
        .to_list();

    // Should get names of people known by people aged >= 25
    for result in &results {
        assert!(result.as_str().is_some());
    }
}

#[test]
fn navigation_filter_aggregate_chain() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Navigate, filter, then aggregate
    let count = g
        .v_ids([tg.alice])
        .out() // navigation
        .has_label("person") // filter
        .out() // navigation
        .dedup() // filter (dedup)
        .count(); // aggregate

    // Alice -> Bob (person) -> Charlie (person) and GraphDB (software)
    // After filter: only people, so Charlie
    let _ = count; // Count is usize, always >= 0
}

#[test]
fn transform_filter_navigation_chain() {
    let tg = create_medium_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Start with values, can't navigate from values - this tests the flow
    // Instead, use as_/select pattern
    let results = g
        .v()
        .has_label("person")
        .as_("person") // transform (label)
        .values("age") // transform
        .as_("age") // transform (label)
        .select_one("person") // transform (select back)
        .out_labels(&["knows"]) // navigation
        .to_list();

    // Should navigate from the labeled person vertices
    assert!(!results.is_empty());
}

#[test]
fn predicate_chain_with_navigation() {
    let tg = create_medium_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Chain multiple predicate-based filters with navigation
    let results = g
        .v()
        .has_label("person")
        .has_where("status", p::eq("active"))
        .has_where("age", p::gt(20i64))
        .out_labels(&["knows"])
        .has_where("age", p::lt(40i64))
        .to_list();

    // Active people over 20 who know people under 40
    for result in &results {
        if let Some(id) = result.as_vertex_id() {
            // Result should be a person vertex
            let _ = id;
        }
    }
}

#[test]
fn dedup_limit_skip_chain() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Chain deduplication and pagination steps
    let results = g
        .v_ids([tg.alice])
        .repeat(__.out_labels(&["knows"]))
        .times(4)
        .emit()
        .dedup() // remove duplicates
        .limit(10) // cap results
        .to_list();

    // Should have unique vertices, limited
    let ids: Vec<VertexId> = results.iter().filter_map(|v| v.as_vertex_id()).collect();
    let unique_count = ids.len();

    // All should be unique after dedup
    let mut sorted = ids.clone();
    sorted.sort();
    sorted.dedup();
    assert_eq!(sorted.len(), unique_count);
}

#[test]
fn order_limit_chain() {
    let tg = create_medium_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Order then limit (barrier step pattern)
    let results = g
        .v()
        .has_label("person")
        .values("age")
        .order()
        .by_asc()
        .build()
        .limit(2)
        .to_list();

    // Should get 2 youngest ages in order
    assert!(results.len() <= 2);
    if results.len() == 2 {
        let a = results[0].as_i64().unwrap_or(0);
        let b = results[1].as_i64().unwrap_or(0);
        assert!(a <= b);
    }
}

// =============================================================================
// Nested Anonymous Traversals
// =============================================================================

#[test]
fn nested_where_clauses() {
    let tg = create_social_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Nested where clauses for complex filtering
    let results = g
        .v()
        .has_label("person")
        .where_(
            __.out_labels(&["knows"])
                .where_(__.out_labels(&["created"]).has_label("software")),
        )
        .values("name")
        .to_list();

    // People who know someone who created software
    // Alice knows Bob, Bob created Redis -> Alice should be in results
    assert!(!results.is_empty());
}

#[test]
fn nested_or_and_conditions() {
    let tg = create_medium_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Complex nested boolean logic
    let results = g
        .v()
        .has_label("person")
        .or_(vec![
            // Either young (< 28)
            __.has_where("age", p::lt(28i64)),
            // Or (active AND has knows edges)
            __.and_(vec![
                __.has_where("status", p::eq("active")),
                __.out_labels(&["knows"]),
            ]),
        ])
        .to_list();

    // Should match young people OR active people with knows edges
    assert!(!results.is_empty());
}

#[test]
fn nested_choose_with_union() {
    let tg = create_medium_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Choose that branches to union
    let results = g
        .v()
        .has_label("person")
        .choose(
            __.has_where("status", p::eq("active")),
            // Active people: get their knows AND created edges
            __.union(vec![__.out_labels(&["knows"]), __.out_labels(&["created"])]),
            // Inactive people: just constant
            __.constant(Value::String("inactive".to_string())),
        )
        .to_list();

    // Should have results from both branches
    assert!(!results.is_empty());
}

#[test]
fn nested_coalesce_chain() {
    let tg = create_medium_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Nested coalesce for fallback chains
    let results = g
        .v()
        .has_label("person")
        .coalesce(vec![
            // Try to get nickname (doesn't exist)
            __.values("nickname"),
            // Fall back to name
            __.values("name"),
            // Ultimate fallback
            __.constant(Value::String("unknown".to_string())),
        ])
        .to_list();

    // Should get names (since nickname doesn't exist)
    assert_eq!(results.len(), 3); // 3 people
    for result in &results {
        assert!(result.as_str().is_some());
    }
}

#[test]
fn deeply_nested_anonymous_filter() {
    let tg = create_social_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Three levels of nesting
    let results = g
        .v()
        .has_label("person")
        .where_(
            __.out_labels(&["knows"])
                .where_(__.out_labels(&["knows"]).where_(__.has_label("person"))),
        )
        .values("name")
        .to_list();

    // People who know someone who knows a person
    // In the cycle Alice -> Bob -> Charlie -> Alice, all should match
    assert!(!results.is_empty());
}

#[test]
fn anonymous_in_repeat() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Complex anonymous traversal inside repeat
    let results = g
        .v_ids([tg.alice])
        .repeat(__.out_labels(&["knows"]).has_label("person"))
        .times(3)
        .emit()
        .dedup()
        .to_list();

    // Should traverse knows edges filtered to person vertices
    assert!(!results.is_empty());
}

// =============================================================================
// Complex Real-World Queries
// =============================================================================

#[test]
fn friends_of_friends_pattern() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Classic friends-of-friends query
    let fof = g
        .v_ids([tg.alice])
        .out_labels(&["knows"]) // Direct friends
        .out_labels(&["knows"]) // Friends of friends
        .dedup()
        .to_list();

    // Alice -> Bob -> Charlie
    assert!(!fof.is_empty());

    let ids: Vec<VertexId> = fof.iter().filter_map(|v| v.as_vertex_id()).collect();
    assert!(ids.contains(&tg.charlie));
}

#[test]
fn mutual_friends_pattern() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Find people who both Alice and Charlie know
    // In small_graph: Alice -> Bob, Charlie -> Alice
    // So mutual "knows" targets: Bob (from Alice), Alice (from Charlie)
    let alice_knows = g.v_ids([tg.alice]).out_labels(&["knows"]).to_list();

    let charlie_knows = g.v_ids([tg.charlie]).out_labels(&["knows"]).to_list();

    // Extract IDs for comparison
    let alice_friend_ids: Vec<VertexId> = alice_knows
        .iter()
        .filter_map(|v| v.as_vertex_id())
        .collect();
    let charlie_friend_ids: Vec<VertexId> = charlie_knows
        .iter()
        .filter_map(|v| v.as_vertex_id())
        .collect();

    // Find intersection
    let mutual: Vec<VertexId> = alice_friend_ids
        .iter()
        .filter(|id| charlie_friend_ids.contains(id))
        .copied()
        .collect();

    // In this graph, no direct mutual friends (Alice knows Bob, Charlie knows Alice)
    let _ = mutual;
}

#[test]
fn recommendation_pattern() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Recommend software: find what friends use that I don't
    // Alice uses GraphDB
    // Find: Alice -> knows -> X -> uses -> Software (excluding Alice's software)
    let recommendations = g
        .v_ids([tg.alice])
        .out_labels(&["knows"]) // Alice's friends
        .out_labels(&["uses"]) // Software they use
        .dedup()
        .to_list();

    // Bob uses GraphDB too (same as Alice), so no new recommendations
    // But we're testing the pattern works
    for rec in &recommendations {
        if let Some(id) = rec.as_vertex_id() {
            assert_eq!(id, tg.graphdb);
        }
    }
}

#[test]
fn co_creation_pattern() {
    let tg = create_social_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Find people who created the same software as Alice
    // Alice -> created -> Software <- created <- OtherPerson
    let co_creators = g
        .v_ids([tg.alice])
        .out_labels(&["created"]) // Software Alice created
        .in_labels(&["created"]) // Other creators of that software
        .has_label("person")
        .dedup()
        .to_list();

    // Only Alice created GraphDB in social graph
    // So result should be just Alice or empty depending on dedup logic
    let ids: Vec<VertexId> = co_creators
        .iter()
        .filter_map(|v| v.as_vertex_id())
        .collect();
    // At most one result (Alice herself)
    assert!(ids.len() <= 1);
}

#[test]
fn hierarchical_traversal_pattern() {
    // Create an org hierarchy for this test
    let graph = Graph::new();

    let ceo = graph.add_vertex("employee", {
        let mut props = HashMap::new();
        props.insert("name".to_string(), Value::String("CEO".to_string()));
        props.insert("level".to_string(), Value::Int(0));
        props
    });

    let cto = graph.add_vertex("employee", {
        let mut props = HashMap::new();
        props.insert("name".to_string(), Value::String("CTO".to_string()));
        props.insert("level".to_string(), Value::Int(1));
        props
    });
    graph
        .add_edge(cto, ceo, "reports_to", HashMap::new())
        .unwrap();

    let manager = graph.add_vertex("employee", {
        let mut props = HashMap::new();
        props.insert("name".to_string(), Value::String("Manager".to_string()));
        props.insert("level".to_string(), Value::Int(2));
        props
    });
    graph
        .add_edge(manager, cto, "reports_to", HashMap::new())
        .unwrap();

    let dev = graph.add_vertex("employee", {
        let mut props = HashMap::new();
        props.insert("name".to_string(), Value::String("Developer".to_string()));
        props.insert("level".to_string(), Value::Int(3));
        props
    });
    graph
        .add_edge(dev, manager, "reports_to", HashMap::new())
        .unwrap();

    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Find all managers in the chain from developer to CEO
    let chain = g
        .v_ids([dev])
        .repeat(__.out_labels(&["reports_to"]))
        .until(__.has_where("level", p::eq(0i64)))
        .emit()
        .values("name")
        .to_list();

    // emit() after repeat with until emits all intermediate + terminal vertices
    // The chain is: Dev -> Manager -> CTO -> CEO
    // With emit(), we get: Manager (iter 1), CTO (iter 2), CEO (iter 3, matches until)
    // But emit may also include Dev depending on emit_first behavior
    // Accept either 3 or 4 as valid
    assert!(chain.len() >= 3 && chain.len() <= 4);

    // Verify expected names are present
    let names: Vec<&str> = chain.iter().filter_map(|v| v.as_str()).collect();
    assert!(names.contains(&"Manager"));
    assert!(names.contains(&"CTO"));
    assert!(names.contains(&"CEO"));
}

#[test]
fn shortest_path_approximation() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Approximate shortest path by limiting repeat and taking first
    let path = g
        .v_ids([tg.alice])
        .with_path()
        .repeat(__.out_labels(&["knows"]))
        .until(__.has_where("name", p::eq("Charlie")))
        .limit(1)
        .path()
        .to_list();

    // Should find path Alice -> Bob -> Charlie
    if !path.is_empty() {
        if let Value::List(p) = &path[0] {
            assert!(p.len() >= 2); // At least Alice and Charlie
        }
    }
}

#[test]
fn degree_centrality_pattern() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Count total degree (in + out) for each person
    let people = g.v().has_label("person").to_list();

    for person in people {
        if let Some(id) = person.as_vertex_id() {
            let out_degree = g.v_ids([id]).out().count();
            let in_degree = g.v_ids([id]).in_().count();
            let total_degree = out_degree + in_degree;

            // Each person should have some connections
            assert!(total_degree > 0, "Person {:?} has no connections", id);
        }
    }
}

#[test]
fn find_isolated_vertices() {
    // Create graph with some isolated vertices
    let graph = Graph::new();

    let connected1 = graph.add_vertex("node", HashMap::new());
    let connected2 = graph.add_vertex("node", HashMap::new());
    let isolated = graph.add_vertex("node", {
        let mut props = HashMap::new();
        props.insert("name".to_string(), Value::String("isolated".to_string()));
        props
    });

    graph
        .add_edge(connected1, connected2, "link", HashMap::new())
        .unwrap();

    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Find vertices with no edges (in or out)
    let all_vertices = g.v().to_list();
    let mut isolated_count = 0;

    for vertex in &all_vertices {
        if let Some(id) = vertex.as_vertex_id() {
            let has_edges = g.v_ids([id]).both().has_next();
            if !has_edges {
                isolated_count += 1;
            }
        }
    }

    assert_eq!(isolated_count, 1); // The isolated vertex
}

#[test]
fn property_statistics_query() {
    let tg = create_medium_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Get min, max, sum of ages
    let min_age = g.v().has_label("person").values("age").min();
    let max_age = g.v().has_label("person").values("age").max();
    let sum_age = g.v().has_label("person").values("age").sum();
    let count = g.v().has_label("person").count();

    assert!(min_age.is_some());
    assert!(max_age.is_some());

    let min = min_age.unwrap().as_i64().unwrap();
    let max = max_age.unwrap().as_i64().unwrap();

    assert!(min <= max);
    assert!(sum_age.as_i64().unwrap_or(0) > 0);
    assert!(count > 0);
}

#[test]
fn path_with_labeled_steps() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Label steps and select them
    let results = g
        .v_ids([tg.alice])
        .as_("start")
        .out_labels(&["knows"])
        .as_("friend")
        .out_labels(&["knows"])
        .as_("fof")
        .select(&["start", "friend", "fof"])
        .to_list();

    // Should get maps with start, friend, fof keys
    assert!(!results.is_empty());

    for result in &results {
        if let Value::Map(map) = result {
            assert!(map.contains_key("start"));
            assert!(map.contains_key("friend"));
            assert!(map.contains_key("fof"));
        }
    }
}

#[test]
fn conditional_navigation_pattern() {
    let tg = create_medium_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Different navigation based on vertex properties
    let results = g
        .v()
        .has_label("person")
        .choose(
            __.has_where("status", p::eq("active")),
            __.out_labels(&["created"]),
            __.out_labels(&["knows"]),
        )
        .to_list();

    // Active people -> their creations
    // Inactive people -> their knows
    assert!(!results.is_empty());
}

#[test]
fn aggregation_after_complex_traversal() {
    let tg = create_social_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Complex traversal followed by aggregation
    let count = g
        .v()
        .has_label("person")
        .where_(__.out_labels(&["knows"]))
        .out_labels(&["knows"])
        .out_labels(&["knows"])
        .dedup()
        .count();

    // Count of unique vertices 3 hops via knows from people with knows edges
    let _ = count; // Count is usize, always >= 0
}

#[test]
fn union_with_different_depths() {
    let tg = create_small_graph();
    let snapshot = tg.graph.snapshot();
    let g = snapshot.gremlin();

    // Union of traversals with different hop counts
    let results = g
        .v_ids([tg.alice])
        .union(vec![
            __.out_labels(&["knows"]),                        // 1 hop
            __.out_labels(&["knows"]).out_labels(&["knows"]), // 2 hops
        ])
        .dedup()
        .to_list();

    // Should include both 1-hop and 2-hop results
    let ids: Vec<VertexId> = results.iter().filter_map(|v| v.as_vertex_id()).collect();

    // Alice -> Bob (1 hop), Alice -> Bob -> Charlie (2 hops)
    assert!(ids.contains(&tg.bob) || ids.contains(&tg.charlie));
}

// =============================================================================
// Dense Graph Stress Tests (using create_dense_graph fixture)
// =============================================================================

#[test]
fn dense_graph_deep_navigation() {
    // Create a dense graph with 50 vertices, 5 edges per vertex
    let graph = create_dense_graph(50, 5);
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Verify structure
    let vertex_count = g.v().count();
    assert_eq!(vertex_count, 50);

    // Navigate 4 hops deep from vertex 0
    let start_id = g
        .v()
        .has_where("index", p::eq(0i64))
        .to_list()
        .first()
        .and_then(|v| v.as_vertex_id());

    if let Some(id) = start_id {
        let results = g
            .v_ids([id])
            .out_labels(&["connects"])
            .out_labels(&["connects"])
            .out_labels(&["connects"])
            .out_labels(&["connects"])
            .dedup()
            .to_list();

        // With 5 edges per vertex, 4 hops should reach many vertices
        assert!(!results.is_empty());
        // With high connectivity, most of the 50 vertices should be reachable
        assert!(results.len() >= 10);
    }
}

#[test]
fn dense_graph_repeat_with_dedup() {
    let graph = create_dense_graph(30, 4);
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Get first vertex as starting point
    let start_id = g
        .v()
        .has_where("index", p::eq(0i64))
        .to_list()
        .first()
        .and_then(|v| v.as_vertex_id());

    if let Some(id) = start_id {
        // Repeat traversal, emit all, then dedup
        let results = g
            .v_ids([id])
            .repeat(__.out_labels(&["connects"]))
            .times(5)
            .emit()
            .dedup()
            .to_list();

        // Should find many unique vertices through the dense network
        assert!(results.len() >= 10);
        // Should not exceed total vertex count
        assert!(results.len() <= 30);
    }
}

#[test]
fn dense_graph_bidirectional_exploration() {
    let graph = create_dense_graph(40, 3);
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Start from middle vertex (index 20)
    let start_id = g
        .v()
        .has_where("index", p::eq(20i64))
        .to_list()
        .first()
        .and_then(|v| v.as_vertex_id());

    if let Some(id) = start_id {
        // Explore both directions
        let results = g
            .v_ids([id])
            .both_labels(&["connects"])
            .both_labels(&["connects"])
            .dedup()
            .to_list();

        // Bidirectional exploration should reach many vertices quickly
        assert!(!results.is_empty());
    }
}

#[test]
fn dense_graph_filter_chain_on_properties() {
    let graph = create_dense_graph(100, 5);
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Navigate and filter by property
    let results = g
        .v()
        .has_where("index", p::lt(10i64)) // Start from first 10 vertices
        .out_labels(&["connects"])
        .has_where("index", p::gte(50i64)) // Filter to vertices with index >= 50
        .dedup()
        .to_list();

    // With modular edge creation, should reach various indices
    // Not all paths will reach index >= 50, but some should
    let _ = results; // May or may not be empty depending on edge topology
}

#[test]
fn dense_graph_weighted_edges() {
    let graph = create_dense_graph(20, 4);
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Check that edges have weight properties
    let edges = g.e().to_list();
    assert!(!edges.is_empty());

    // Navigate via edges with properties
    let edge_weights = g.e().values("weight").to_list();
    assert!(!edge_weights.is_empty());

    // All weights should be floats between 0 and 1
    for weight in &edge_weights {
        if let Value::Float(w) = weight {
            assert!(*w > 0.0 && *w <= 1.0);
        }
    }
}

#[test]
fn dense_graph_complex_mixed_chain() {
    let graph = create_dense_graph(50, 4);
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Complex chain mixing filter, navigation, dedup, limit
    let results = g
        .v()
        .has_label("node") // All vertices have label "node"
        .has_where("index", p::lte(5i64)) // First 6 vertices
        .out_labels(&["connects"]) // Navigate
        .has_where("index", p::gt(10i64)) // Filter by property
        .out_labels(&["connects"]) // Navigate again
        .dedup()
        .limit(20) // Cap results
        .to_list();

    // Should have at most 20 results
    assert!(results.len() <= 20);
}

#[test]
fn dense_graph_union_from_multiple_starts() {
    let graph = create_dense_graph(30, 3);
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Get two starting vertices
    let vertices = g.v().has_where("index", p::lte(1i64)).to_list();
    let ids: Vec<VertexId> = vertices.iter().filter_map(|v| v.as_vertex_id()).collect();

    if ids.len() >= 2 {
        // Union of traversals from different starts
        let results = g
            .v_ids(ids)
            .union(vec![
                __.out_labels(&["connects"]),
                __.out_labels(&["connects"]).out_labels(&["connects"]),
            ])
            .dedup()
            .to_list();

        // Should get results from both 1-hop and 2-hop traversals from both starts
        assert!(!results.is_empty());
    }
}

#[test]
fn dense_graph_count_reachable_vertices() {
    let graph = create_dense_graph(50, 5);
    let snapshot = graph.snapshot();
    let g = snapshot.gremlin();

    // Start from vertex 0
    let start_id = g
        .v()
        .has_where("index", p::eq(0i64))
        .to_list()
        .first()
        .and_then(|v| v.as_vertex_id());

    if let Some(id) = start_id {
        // Count unique vertices reachable in 3 hops
        let reachable_count = g
            .v_ids([id])
            .repeat(__.out_labels(&["connects"]))
            .times(3)
            .emit()
            .dedup()
            .count();

        // With 5 edges per vertex, 3 hops in a 50-vertex graph should reach many
        assert!(reachable_count >= 15);
    }
}