grafeo-engine 0.5.42

Query engine and database management for Grafeo
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
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
//! Integration tests for search operations covering uncovered paths.
//!
//! Targets low-coverage areas in `database/search.rs`:
//! - hybrid_search (previously untested)
//! - text_search error paths
//! - batch_vector_search with filters
//! - mmr_search with filters
//!
//! ```bash
//! cargo test -p grafeo-engine --features full --test search_operations
//! ```

// ============================================================================
// Vector search tests
// ============================================================================

#[cfg(feature = "vector-index")]
mod vector {
    use grafeo_common::types::Value;
    use grafeo_engine::GrafeoDB;
    use std::collections::HashMap;

    fn vec3(x: f32, y: f32, z: f32) -> Value {
        Value::Vector(vec![x, y, z].into())
    }

    fn setup_vector_db() -> GrafeoDB {
        let db = GrafeoDB::new_in_memory();

        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(n1, "emb", vec3(1.0, 0.0, 0.0));
        db.set_node_property(n1, "category", Value::String("science".into()));

        let n2 = db.create_node(&["Doc"]);
        db.set_node_property(n2, "emb", vec3(0.0, 1.0, 0.0));
        db.set_node_property(n2, "category", Value::String("science".into()));

        let n3 = db.create_node(&["Doc"]);
        db.set_node_property(n3, "emb", vec3(0.0, 0.0, 1.0));
        db.set_node_property(n3, "category", Value::String("art".into()));

        let n4 = db.create_node(&["Doc"]);
        db.set_node_property(n4, "emb", vec3(0.9, 0.1, 0.0));
        db.set_node_property(n4, "category", Value::String("science".into()));

        db.create_property_index("category");
        db.create_vector_index("Doc", "emb", Some(3), Some("cosine"), None, None, None)
            .expect("create vector index");

        db
    }

    #[test]
    fn test_vector_search_no_index_error() {
        let db = GrafeoDB::new_in_memory();
        let n = db.create_node(&["Doc"]);
        db.set_node_property(n, "emb", vec3(1.0, 0.0, 0.0));

        // No vector index created: search should fail
        let result = db.vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 5, None, None);
        assert!(result.is_err(), "search without index should error");
    }

    #[test]
    fn test_vector_search_with_ef_parameter() {
        let db = setup_vector_db();

        // ef parameter controls search quality (higher = better, slower)
        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 2, Some(50), None)
            .expect("search with ef");

        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_batch_vector_search_multiple_queries() {
        let db = setup_vector_db();

        let queries = vec![vec![1.0_f32, 0.0, 0.0], vec![0.0, 1.0, 0.0]];

        let results = db
            .batch_vector_search("Doc", "emb", &queries, 2, None, None)
            .expect("batch search");

        assert_eq!(results.len(), 2);
        // Each query should return up to 2 results
        for result_set in &results {
            assert!(result_set.len() <= 2);
            assert!(!result_set.is_empty());
        }
    }

    #[test]
    fn test_batch_vector_search_with_filter() {
        let db = setup_vector_db();

        let mut filters = HashMap::new();
        filters.insert("category".to_string(), Value::String("science".into()));

        let queries = vec![vec![1.0_f32, 0.0, 0.0]];

        let results = db
            .batch_vector_search("Doc", "emb", &queries, 10, None, Some(&filters))
            .expect("batch search with filter");

        assert_eq!(results.len(), 1);
        // Only science docs should be returned (3 out of 4)
        assert_eq!(results[0].len(), 3);
    }

    #[test]
    fn test_mmr_search_with_filter() {
        let db = setup_vector_db();

        let mut filters = HashMap::new();
        filters.insert("category".to_string(), Value::String("science".into()));

        let results = db
            .mmr_search(
                "Doc",
                "emb",
                &[1.0, 0.0, 0.0],
                2,
                None,
                None,
                None,
                Some(&filters),
            )
            .expect("mmr with filter");

        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_vector_search_k_larger_than_dataset() {
        let db = setup_vector_db();

        // Request more results than nodes exist
        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 100, None, None)
            .expect("k > dataset");

        // Should return all 4 nodes, not error
        assert_eq!(results.len(), 4);
    }

    #[test]
    fn test_drop_and_recreate_vector_index() {
        let db = setup_vector_db();

        // Search works
        let r1 = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 2, None, None)
            .expect("search before drop");
        assert_eq!(r1.len(), 2);

        // Drop index
        assert!(db.drop_vector_index("Doc", "emb"));

        // Search should fail
        let err = db.vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 2, None, None);
        assert!(err.is_err(), "search after drop should error");

        // Recreate index
        db.create_vector_index("Doc", "emb", Some(3), Some("cosine"), None, None, None)
            .expect("recreate index");

        // Search works again
        let r2 = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 2, None, None)
            .expect("search after recreate");
        assert_eq!(r2.len(), 2);
    }

    #[test]
    fn test_vector_index_auto_inserts_on_set_property() {
        let db = GrafeoDB::new_in_memory();

        // Create index FIRST, on empty data
        db.create_vector_index("Doc", "emb", Some(3), Some("cosine"), None, None, None)
            .expect("create empty index");

        // Add nodes AFTER index exists (no rebuild)
        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(n1, "emb", vec3(1.0, 0.0, 0.0));

        let n2 = db.create_node(&["Doc"]);
        db.set_node_property(n2, "emb", vec3(0.0, 1.0, 0.0));

        // Search should find both nodes WITHOUT calling rebuild_vector_index
        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 5, None, None)
            .expect("search without rebuild");

        assert_eq!(
            results.len(),
            2,
            "auto-inserted nodes should be searchable without rebuild"
        );

        // The closest node to [1,0,0] should be n1
        assert_eq!(results[0].0, n1, "n1 should be the closest match");
    }

    #[test]
    fn test_rebuild_vector_index_preserves_results() {
        let db = setup_vector_db();
        let query = &[1.0_f32, 0.0, 0.0];

        // Search before rebuild
        let before = db
            .vector_search("Doc", "emb", query, 4, None, None)
            .expect("search before rebuild");

        // Rebuild
        db.rebuild_vector_index("Doc", "emb").expect("rebuild");

        // Search after rebuild
        let after = db
            .vector_search("Doc", "emb", query, 4, None, None)
            .expect("search after rebuild");

        // Same nodes, same distances (within floating point tolerance).
        // Sort by node ID because HNSW does not guarantee ordering for
        // equal-distance ties, and rebuild changes the internal graph.
        assert_eq!(before.len(), after.len(), "same result count after rebuild");

        let mut before_sorted: Vec<_> = before.iter().collect();
        let mut after_sorted: Vec<_> = after.iter().collect();
        before_sorted.sort_by_key(|(id, _)| *id);
        after_sorted.sort_by_key(|(id, _)| *id);

        for (b, a) in before_sorted.iter().zip(after_sorted.iter()) {
            assert_eq!(b.0, a.0, "same node IDs after rebuild");
            assert!(
                (b.1 - a.1).abs() < 1e-5,
                "same distances after rebuild: {} vs {}",
                b.1,
                a.1,
            );
        }
    }

    // ── Quantized vector index tests ─────────────────────────────────

    #[test]
    fn test_scalar_quantized_vector_index() {
        let db = GrafeoDB::new_in_memory();
        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(n1, "emb", vec3(1.0, 0.0, 0.0));
        let n2 = db.create_node(&["Doc"]);
        db.set_node_property(n2, "emb", vec3(0.0, 1.0, 0.0));
        let n3 = db.create_node(&["Doc"]);
        db.set_node_property(n3, "emb", vec3(0.0, 0.0, 1.0));

        db.create_vector_index(
            "Doc",
            "emb",
            Some(3),
            Some("cosine"),
            None,
            None,
            Some("scalar"),
        )
        .expect("create scalar quantized index");

        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 2, None, None)
            .expect("search scalar quantized");
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].0, n1);
    }

    #[test]
    fn test_binary_quantized_vector_index() {
        let db = GrafeoDB::new_in_memory();
        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(n1, "emb", vec3(1.0, 0.0, 0.0));
        let n2 = db.create_node(&["Doc"]);
        db.set_node_property(n2, "emb", vec3(0.0, 1.0, 0.0));

        db.create_vector_index(
            "Doc",
            "emb",
            Some(3),
            Some("euclidean"),
            None,
            None,
            Some("binary"),
        )
        .expect("create binary quantized index");

        let results = db
            .vector_search("Doc", "emb", &[0.9, 0.1, 0.0], 2, None, None)
            .expect("search binary quantized");
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_product_quantized_vector_index() {
        // Product quantization needs dims divisible by num_subvectors (default 8),
        // so use 8-dim vectors.
        let db = GrafeoDB::new_in_memory();
        for i in 0..10 {
            let n = db.create_node(&["Doc"]);
            let vec: Vec<f32> = (0..8).map(|j| ((i * 8 + j) as f32) / 80.0).collect();
            db.set_node_property(n, "emb", Value::Vector(vec.into()));
        }

        db.create_vector_index(
            "Doc",
            "emb",
            Some(8),
            Some("euclidean"),
            None,
            None,
            Some("product"),
        )
        .expect("create product quantized index");

        let results = db
            .vector_search("Doc", "emb", &[0.5; 8], 3, None, None)
            .expect("search product quantized");
        assert_eq!(results.len(), 3);
    }

    #[test]
    fn test_empty_quantized_index_auto_inserts() {
        let db = GrafeoDB::new_in_memory();

        // Create quantized index on empty data with explicit dimensions
        db.create_vector_index(
            "Doc",
            "emb",
            Some(3),
            Some("cosine"),
            None,
            None,
            Some("scalar"),
        )
        .expect("create empty scalar index");

        // Add nodes after index creation
        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(n1, "emb", vec3(1.0, 0.0, 0.0));
        let n2 = db.create_node(&["Doc"]);
        db.set_node_property(n2, "emb", vec3(0.0, 1.0, 0.0));

        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 2, None, None)
            .expect("search after late insert into quantized index");
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_rebuild_preserves_quantization_type() {
        let db = GrafeoDB::new_in_memory();
        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(n1, "emb", vec3(1.0, 0.0, 0.0));
        let n2 = db.create_node(&["Doc"]);
        db.set_node_property(n2, "emb", vec3(0.0, 1.0, 0.0));

        db.create_vector_index(
            "Doc",
            "emb",
            Some(3),
            Some("cosine"),
            None,
            None,
            Some("binary"),
        )
        .expect("create binary index");

        db.rebuild_vector_index("Doc", "emb").expect("rebuild");

        // Search should still work after rebuild
        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 2, None, None)
            .expect("search after rebuild of quantized index");
        assert_eq!(results.len(), 2);
    }
}

// ============================================================================
// Text search tests
// ============================================================================

#[cfg(feature = "text-index")]
mod text {
    use grafeo_common::types::Value;
    use grafeo_engine::GrafeoDB;

    fn setup_text_db() -> GrafeoDB {
        let db = GrafeoDB::new_in_memory();

        let n1 = db.create_node(&["Article"]);
        db.set_node_property(n1, "title", Value::String("Rust graph database".into()));

        let n2 = db.create_node(&["Article"]);
        db.set_node_property(n2, "title", Value::String("Python machine learning".into()));

        let n3 = db.create_node(&["Article"]);
        db.set_node_property(
            n3,
            "title",
            Value::String("Rust systems programming".into()),
        );

        db.create_text_index("Article", "title")
            .expect("create text index");

        db
    }

    #[test]
    fn test_text_search_basic() {
        let db = setup_text_db();

        let results = db.text_search("Article", "title", "Rust", 10).unwrap();

        // Should match articles with "Rust"
        assert!(results.len() >= 2, "expected at least 2 Rust articles");
    }

    #[test]
    fn test_text_search_no_index_error() {
        let db = GrafeoDB::new_in_memory();
        let n = db.create_node(&["Article"]);
        db.set_node_property(n, "title", Value::String("test".into()));

        // No text index: should error
        let result = db.text_search("Article", "title", "test", 10);
        assert!(result.is_err(), "text search without index should error");
    }

    #[test]
    fn test_text_search_no_matches() {
        let db = setup_text_db();

        let results = db
            .text_search("Article", "title", "nonexistentxyz", 10)
            .unwrap();

        assert!(results.is_empty(), "no matches expected for nonsense query");
    }

    #[test]
    fn test_text_search_after_mutation() {
        let db = setup_text_db();

        // Add a new article
        let n = db.create_node(&["Article"]);
        db.set_node_property(n, "title", Value::String("Rust web framework".into()));

        let results = db.text_search("Article", "title", "Rust", 10).unwrap();

        // Should now include the new article
        assert!(
            results.len() >= 3,
            "expected at least 3 Rust articles after mutation"
        );
    }

    #[test]
    fn test_drop_and_rebuild_text_index() {
        let db = setup_text_db();

        // Search works
        let r1 = db.text_search("Article", "title", "Rust", 10).unwrap();
        assert!(!r1.is_empty());

        // Drop index
        assert!(db.drop_text_index("Article", "title"));

        // Search should fail
        let err = db.text_search("Article", "title", "Rust", 10);
        assert!(err.is_err());

        // Rebuild index
        db.rebuild_text_index("Article", "title").unwrap();

        // Search works again
        let r2 = db.text_search("Article", "title", "Rust", 10).unwrap();
        assert!(!r2.is_empty());
    }
}

// ============================================================================
// Hybrid search tests
// ============================================================================

#[cfg(feature = "hybrid-search")]
mod hybrid {
    use grafeo_common::types::Value;
    use grafeo_engine::GrafeoDB;

    fn vec3(x: f32, y: f32, z: f32) -> Value {
        Value::Vector(vec![x, y, z].into())
    }

    fn setup_hybrid_db() -> GrafeoDB {
        let db = GrafeoDB::new_in_memory();

        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(
            n1,
            "content",
            Value::String("Rust graph database engine".into()),
        );
        db.set_node_property(n1, "emb", vec3(1.0, 0.0, 0.0));

        let n2 = db.create_node(&["Doc"]);
        db.set_node_property(
            n2,
            "content",
            Value::String("Python machine learning framework".into()),
        );
        db.set_node_property(n2, "emb", vec3(0.0, 1.0, 0.0));

        let n3 = db.create_node(&["Doc"]);
        db.set_node_property(
            n3,
            "content",
            Value::String("Rust systems programming language".into()),
        );
        db.set_node_property(n3, "emb", vec3(0.9, 0.1, 0.0));

        let n4 = db.create_node(&["Doc"]);
        db.set_node_property(
            n4,
            "content",
            Value::String("Graph neural network research".into()),
        );
        db.set_node_property(n4, "emb", vec3(0.5, 0.5, 0.0));

        // Create both indexes
        db.create_text_index("Doc", "content")
            .expect("create text index");
        db.create_vector_index("Doc", "emb", Some(3), Some("cosine"), None, None, None)
            .expect("create vector index");

        db
    }

    #[test]
    fn test_hybrid_search_basic() {
        let db = setup_hybrid_db();

        let results = db
            .hybrid_search(
                "Doc",
                "content",
                "emb",
                "Rust graph",
                Some(&[1.0, 0.0, 0.0]),
                4,
                None,
            )
            .expect("hybrid search");

        assert!(!results.is_empty(), "hybrid search should return results");

        // "Rust graph database engine" should rank highest: matches both
        // text ("Rust graph") and vector (closest to [1,0,0])
        let top_node = results[0].0;
        let top_props = db.get_node(top_node).expect("top node exists");
        let content = top_props
            .properties
            .get(&grafeo_common::types::PropertyKey::new("content"))
            .expect("has content");
        if let Value::String(s) = content {
            assert!(
                s.contains("Rust") || s.contains("graph"),
                "top result should match query terms, got: {s}"
            );
        }
    }

    #[test]
    fn test_hybrid_search_text_only() {
        let db = setup_hybrid_db();

        // No vector query: only text search contributes
        let results = db
            .hybrid_search("Doc", "content", "emb", "Rust", None, 4, None)
            .expect("text-only hybrid");

        assert!(
            !results.is_empty(),
            "text-only hybrid should return results"
        );
    }

    #[test]
    fn test_hybrid_search_no_matches() {
        let db = setup_hybrid_db();

        let results = db
            .hybrid_search(
                "Doc",
                "content",
                "emb",
                "nonexistentxyzquery",
                Some(&[0.0, 0.0, 0.0]),
                4,
                None,
            )
            .expect("hybrid no matches");

        // Even with no text matches, vector search may return results
        // Just verify it doesn't error
        let _ = results;
    }

    #[test]
    fn test_hybrid_search_scores_descending() {
        let db = setup_hybrid_db();

        let results = db
            .hybrid_search(
                "Doc",
                "content",
                "emb",
                "Rust graph",
                Some(&[1.0, 0.0, 0.0]),
                4,
                None,
            )
            .expect("hybrid search");

        assert!(
            results.len() >= 2,
            "need at least 2 results to verify order"
        );

        // Verify scores are in descending order (higher = better)
        for window in results.windows(2) {
            assert!(
                window[0].1 >= window[1].1,
                "hybrid_search scores should be descending (higher = better): {} >= {}",
                window[0].1,
                window[1].1,
            );
        }

        // Verify all scores are positive
        for (_, score) in &results {
            assert!(
                *score > 0.0,
                "hybrid_search fusion scores should be positive"
            );
        }
    }

    #[test]
    fn test_hybrid_search_without_text_index() {
        let db = GrafeoDB::new_in_memory();

        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(n1, "content", Value::String("Rust graph database".into()));
        db.set_node_property(n1, "emb", vec3(1.0, 0.0, 0.0));

        let n2 = db.create_node(&["Doc"]);
        db.set_node_property(n2, "content", Value::String("Python ML".into()));
        db.set_node_property(n2, "emb", vec3(0.0, 1.0, 0.0));

        // Create ONLY vector index, no text index
        db.create_vector_index("Doc", "emb", Some(3), Some("cosine"), None, None, None)
            .expect("create vector index");

        // hybrid_search should work, using only vector source
        let results = db
            .hybrid_search(
                "Doc",
                "content",
                "emb",
                "Rust",
                Some(&[1.0, 0.0, 0.0]),
                4,
                None,
            )
            .expect("hybrid without text index should not error");

        assert!(
            !results.is_empty(),
            "should return results from vector source only"
        );
    }

    #[test]
    fn test_hybrid_search_without_vector_index() {
        let db = GrafeoDB::new_in_memory();

        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(n1, "content", Value::String("Rust graph database".into()));
        db.set_node_property(n1, "emb", vec3(1.0, 0.0, 0.0));

        // Create ONLY text index, no vector index
        db.create_text_index("Doc", "content")
            .expect("create text index");

        // hybrid_search with a vector query should still work, using only text source
        let results = db
            .hybrid_search(
                "Doc",
                "content",
                "emb",
                "Rust",
                Some(&[1.0, 0.0, 0.0]),
                4,
                None,
            )
            .expect("hybrid without vector index should not error");

        assert!(
            !results.is_empty(),
            "should return results from text source only"
        );
    }

    #[test]
    fn test_hybrid_search_without_any_index() {
        let db = GrafeoDB::new_in_memory();

        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(n1, "content", Value::String("Rust graph database".into()));
        db.set_node_property(n1, "emb", vec3(1.0, 0.0, 0.0));

        // No indexes at all
        let results = db
            .hybrid_search(
                "Doc",
                "content",
                "emb",
                "Rust",
                Some(&[1.0, 0.0, 0.0]),
                4,
                None,
            )
            .expect("hybrid without any index should not error");

        assert!(
            results.is_empty(),
            "should return empty when no indexes exist"
        );
    }

    #[test]
    fn test_hybrid_weighted_fusion_vector_ranking() {
        let db = setup_hybrid_db();

        // Use weighted fusion: the node closest in vector space to query [1,0,0]
        // AND matching text "Rust" should rank higher than a node that is
        // far in vector space even if it matches text.
        let fusion = grafeo_core::index::text::FusionMethod::Weighted {
            weights: vec![0.3, 0.7], // heavily weight vector similarity
        };
        let results = db
            .hybrid_search(
                "Doc",
                "content",
                "emb",
                "Rust",
                Some(&[1.0, 0.0, 0.0]),
                4,
                Some(fusion),
            )
            .expect("weighted hybrid search");

        assert!(results.len() >= 2, "need at least 2 results");

        // With 0.7 vector weight and query [1,0,0], the node with emb [1,0,0]
        // (n1: "Rust graph database engine") should rank above the node with
        // emb [0.9,0.1,0] (n3: "Rust systems programming language").
        // Both match "Rust" in text, but n1 is closer in vector space.
        let top_node = results[0].0;
        let top_props = db.get_node(top_node).expect("top node exists");
        let content = top_props
            .properties
            .get(&grafeo_common::types::PropertyKey::new("content"))
            .expect("has content");
        if let Value::String(s) = content {
            assert!(
                s.contains("Rust graph database"),
                "with 70% vector weight, closest vector should rank first, got: {s}"
            );
        }
    }
}

// ============================================================================
// Concurrent index access (T3-05)
// ============================================================================

#[cfg(feature = "vector-index")]
mod concurrent_vector {
    use grafeo_common::types::Value;
    use grafeo_engine::GrafeoDB;

    fn vec3(x: f32, y: f32, z: f32) -> Value {
        Value::Vector(vec![x, y, z].into())
    }

    #[test]
    fn test_concurrent_vector_read_during_write() {
        let db = std::sync::Arc::new(GrafeoDB::new_in_memory());

        // Seed initial data
        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(n1, "emb", vec3(1.0, 0.0, 0.0));
        db.create_vector_index("Doc", "emb", Some(3), Some("cosine"), None, None, None)
            .unwrap();

        let db_read = std::sync::Arc::clone(&db);
        let db_write = std::sync::Arc::clone(&db);

        // Writer thread: add more nodes
        let writer = std::thread::spawn(move || {
            for i in 0..10 {
                let n = db_write.create_node(&["Doc"]);
                let x = (i as f32) / 10.0;
                db_write.set_node_property(n, "emb", vec3(x, 1.0 - x, 0.0));
            }
        });

        // Reader thread: search concurrently
        let reader = std::thread::spawn(move || {
            for _ in 0..10 {
                let results = db_read.vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 5, None, None);
                // Should not panic or error
                assert!(results.is_ok(), "concurrent read should not error");
            }
        });

        writer.join().expect("writer thread should not panic");
        reader.join().expect("reader thread should not panic");
    }
}

#[cfg(feature = "text-index")]
mod concurrent_text {
    use grafeo_common::types::Value;
    use grafeo_engine::GrafeoDB;

    #[test]
    fn test_concurrent_text_read_during_write() {
        let db = std::sync::Arc::new(GrafeoDB::new_in_memory());

        let n1 = db.create_node(&["Doc"]);
        db.set_node_property(
            n1,
            "content",
            Value::String("initial document about graphs".into()),
        );
        db.create_text_index("Doc", "content").unwrap();

        let db_read = std::sync::Arc::clone(&db);
        let db_write = std::sync::Arc::clone(&db);

        let writer = std::thread::spawn(move || {
            for i in 0..10 {
                let n = db_write.create_node(&["Doc"]);
                db_write.set_node_property(
                    n,
                    "content",
                    Value::String(format!("document number {i} about databases").into()),
                );
            }
        });

        let reader = std::thread::spawn(move || {
            for _ in 0..10 {
                let results = db_read.text_search("Doc", "content", "database", 5);
                assert!(results.is_ok(), "concurrent text read should not error");
            }
        });

        writer.join().expect("writer should not panic");
        reader.join().expect("reader should not panic");
    }
}

// ============================================================================
// Quantized vector index tests
// ============================================================================

#[cfg(feature = "vector-index")]
mod quantized_vector {
    use grafeo_common::types::Value;
    use grafeo_engine::GrafeoDB;

    fn vec3(x: f32, y: f32, z: f32) -> Value {
        Value::Vector(vec![x, y, z].into())
    }

    #[test]
    fn test_scalar_quantized_index_create_insert_search() {
        let db = GrafeoDB::new_in_memory();

        let alix = db.create_node(&["Doc"]);
        db.set_node_property(alix, "emb", vec3(1.0, 0.0, 0.0));
        db.set_node_property(alix, "name", Value::from("Alix"));

        let gus = db.create_node(&["Doc"]);
        db.set_node_property(gus, "emb", vec3(0.0, 1.0, 0.0));
        db.set_node_property(gus, "name", Value::from("Gus"));

        let vincent = db.create_node(&["Doc"]);
        db.set_node_property(vincent, "emb", vec3(0.9, 0.1, 0.0));
        db.set_node_property(vincent, "name", Value::from("Vincent"));

        db.create_vector_index(
            "Doc",
            "emb",
            Some(3),
            Some("cosine"),
            None,
            None,
            Some("scalar"),
        )
        .expect("create scalar-quantized index");

        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 2, None, None)
            .expect("search should succeed");

        assert_eq!(results.len(), 2, "should return 2 results");
        // The closest vector to [1,0,0] should be Alix's node
        assert_eq!(results[0].0, alix, "Alix should be the closest match");
    }

    #[test]
    fn test_binary_quantized_index_create_insert_search() {
        let db = GrafeoDB::new_in_memory();

        let alix = db.create_node(&["Doc"]);
        db.set_node_property(alix, "emb", vec3(1.0, 0.0, 0.0));

        let gus = db.create_node(&["Doc"]);
        db.set_node_property(gus, "emb", vec3(0.0, 1.0, 0.0));

        let vincent = db.create_node(&["Doc"]);
        db.set_node_property(vincent, "emb", vec3(0.0, 0.0, 1.0));

        db.create_vector_index(
            "Doc",
            "emb",
            Some(3),
            Some("euclidean"),
            None,
            None,
            Some("binary"),
        )
        .expect("create binary-quantized index");

        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 2, None, None)
            .expect("search should succeed");

        assert_eq!(results.len(), 2, "should return 2 results");
        assert_eq!(results[0].0, alix, "Alix should be the closest match");
    }

    #[test]
    fn test_no_quantization_still_works() {
        // Regression test: quantization=None (default) should behave identically
        let db = GrafeoDB::new_in_memory();

        let alix = db.create_node(&["Doc"]);
        db.set_node_property(alix, "emb", vec3(1.0, 0.0, 0.0));

        let gus = db.create_node(&["Doc"]);
        db.set_node_property(gus, "emb", vec3(0.0, 1.0, 0.0));

        // Explicit None quantization
        db.create_vector_index("Doc", "emb", Some(3), Some("cosine"), None, None, None)
            .expect("create non-quantized index");

        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 1, None, None)
            .expect("search should succeed");

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].0, alix);
    }

    #[test]
    fn test_quantization_none_string_equivalent_to_default() {
        let db = GrafeoDB::new_in_memory();

        let alix = db.create_node(&["Doc"]);
        db.set_node_property(alix, "emb", vec3(1.0, 0.0, 0.0));

        // "none" string should be equivalent to None
        db.create_vector_index(
            "Doc",
            "emb",
            Some(3),
            Some("cosine"),
            None,
            None,
            Some("none"),
        )
        .expect("create index with 'none' quantization");

        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 1, None, None)
            .expect("search should succeed");
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_invalid_quantization_type_errors() {
        let db = GrafeoDB::new_in_memory();

        let alix = db.create_node(&["Doc"]);
        db.set_node_property(alix, "emb", vec3(1.0, 0.0, 0.0));

        let result = db.create_vector_index(
            "Doc",
            "emb",
            Some(3),
            Some("cosine"),
            None,
            None,
            Some("invalid_type"),
        );
        assert!(result.is_err(), "invalid quantization type should error");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Unknown quantization type"),
            "error should mention unknown type: {err_msg}"
        );
    }

    #[test]
    fn test_scalar_quantized_empty_index_then_insert() {
        // Create quantized index with explicit dimensions but no data yet
        let db = GrafeoDB::new_in_memory();

        db.create_vector_index(
            "Doc",
            "emb",
            Some(3),
            Some("cosine"),
            None,
            None,
            Some("scalar"),
        )
        .expect("create empty scalar-quantized index");

        // Insert after index creation
        let alix = db.create_node(&["Doc"]);
        db.set_node_property(alix, "emb", vec3(1.0, 0.0, 0.0));

        let gus = db.create_node(&["Doc"]);
        db.set_node_property(gus, "emb", vec3(0.0, 1.0, 0.0));

        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 1, None, None)
            .expect("search should succeed");

        // Note: auto-insert into quantized index happens via the same mechanism
        // as non-quantized, but depends on property-change hooks being connected
        // (which they are for VectorIndexKind::Quantized through the standard path).
        // With empty index + late inserts, the index may not auto-populate.
        // This test validates the create-then-search path doesn't panic.
        let _ = results;
    }

    #[test]
    fn test_rebuild_preserves_quantization() {
        let db = GrafeoDB::new_in_memory();

        let alix = db.create_node(&["Doc"]);
        db.set_node_property(alix, "emb", vec3(1.0, 0.0, 0.0));

        let gus = db.create_node(&["Doc"]);
        db.set_node_property(gus, "emb", vec3(0.0, 1.0, 0.0));

        db.create_vector_index(
            "Doc",
            "emb",
            Some(3),
            Some("cosine"),
            None,
            None,
            Some("binary"),
        )
        .expect("create binary-quantized index");

        // Rebuild should preserve the binary quantization
        db.rebuild_vector_index("Doc", "emb")
            .expect("rebuild should succeed");

        let results = db
            .vector_search("Doc", "emb", &[1.0, 0.0, 0.0], 1, None, None)
            .expect("search after rebuild should succeed");

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].0, alix);
    }
}