-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathtest_svs_tiered.cpp
More file actions
2904 lines (2474 loc) · 127 KB
/
test_svs_tiered.cpp
File metadata and controls
2904 lines (2474 loc) · 127 KB
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
#include "VecSim/index_factories/tiered_factory.h"
#include "VecSim/vec_sim_debug.h"
#include <string>
#include <array>
#include "unit_test_utils.h"
#include "mock_thread_pool.h"
#if HAVE_SVS
#include <thread>
// For getAvailableCPUs():
#include <sched.h>
#include "VecSim/algorithms/svs/svs.h"
#include "VecSim/algorithms/svs/svs_tiered.h"
// There are possible cases when SVS Index cannot be created with the requested quantization mode
// due to platform and/or hardware limitations or combination of requested 'compression' modes.
// This assert handle those cases and skip a test if the mode is not supported.
// Elsewhere, test will fail if the index creation failed with no reason explained above.
#define ASSERT_INDEX(index) \
if (index == nullptr) { \
if (std::get<1>(svs_details::isSVSQuantBitsSupported(TypeParam::get_quant_bits()))) { \
GTEST_FAIL() << "Failed to create SVS index"; \
} else { \
GTEST_SKIP() << "SVS LVQ is not supported."; \
} \
}
// Get available number of CPUs
// Returns the number of logical processors on the process
// Returns std::thread::hardware_concurrency() if the number of logical processors is not available
static unsigned int getAvailableCPUs() {
#ifdef __linux__
// On Linux, use sched_getaffinity to get the number of CPUs available to the current process.
cpu_set_t cpu_set;
if (sched_getaffinity(0, sizeof(cpu_set), &cpu_set) == 0) {
return CPU_COUNT(&cpu_set);
}
#endif
// Fallback.
return std::thread::hardware_concurrency();
}
// Log callback function to print non-debug log messages
static void svsTestLogCallBackNoDebug(void *ctx, const char *level, const char *message) {
if (level == nullptr || message == nullptr) {
return; // Skip null messages
}
if (std::string_view{level} == VecSimCommonStrings::LOG_DEBUG_STRING) {
return; // Skip debug messages
}
// Print other log levels
std::cout << level << ": " << message << std::endl;
}
// Runs the test for combination of data type and quantization mode.
// TODO: Add support for label type combination(single/multi)
template <typename index_type_t>
class SVSTieredIndexTest : public ::testing::Test {
public:
using data_t = typename index_type_t::data_t;
static const size_t TestsDefaultTrainingThreshold = 1024;
static const size_t TestsDefaultUpdateThreshold = 16;
protected:
TieredSVSIndex<data_t> *CastToTieredSVS(VecSimIndex *index) {
return reinterpret_cast<TieredSVSIndex<data_t> *>(index);
}
TieredIndexParams
CreateTieredSVSParams(VecSimParams &svs_params, tieredIndexMock &mock_thread_pool,
size_t training_threshold = TestsDefaultTrainingThreshold,
size_t update_threshold = TestsDefaultUpdateThreshold,
size_t update_job_wait_time = SVS_DEFAULT_UPDATE_JOB_WAIT_TIME) {
trainingThreshold = training_threshold;
updateThreshold = update_threshold;
svs_params.algoParams.svsParams.quantBits = index_type_t::get_quant_bits();
if (svs_params.algoParams.svsParams.num_threads == 0) {
svs_params.algoParams.svsParams.num_threads = mock_thread_pool.thread_pool_size;
}
return TieredIndexParams{
.jobQueue = &mock_thread_pool.jobQ,
.jobQueueCtx = mock_thread_pool.ctx,
.submitCb = tieredIndexMock::submit_callback,
.primaryIndexParams = &svs_params,
.specificParams = {.tieredSVSParams =
TieredSVSParams{.trainingTriggerThreshold = training_threshold,
.updateTriggerThreshold = update_threshold,
.updateJobWaitTime = update_job_wait_time}}};
}
void verifyNumThreads(TieredSVSIndex<data_t> *tiered_index, size_t expected_num_threads,
size_t expected_capcity) {
ASSERT_EQ(tiered_index->GetSVSIndex()->getNumThreads(), expected_num_threads);
ASSERT_EQ(tiered_index->GetSVSIndex()->getThreadPoolCapacity(), expected_capcity);
}
TieredSVSIndex<data_t> *CreateTieredSVSIndex(const TieredIndexParams &tiered_params,
tieredIndexMock &mock_thread_pool,
size_t num_available_threads = 1) {
auto *tiered_index =
reinterpret_cast<TieredSVSIndex<data_t> *>(TieredFactory::NewIndex(&tiered_params));
// Set the created tiered index in the index external context (it will take ownership over
// the index, and we'll need to release the ctx at the end of the test.
mock_thread_pool.ctx->index_strong_ref.reset(tiered_index);
// Set numThreads to 1 by default to allow direct calls to SVS addVector() API,
// which requires exactly 1 thread. When using tiered index addVector API,
// the thread count is managed internally according to the operation and threadpool
// capacity, so testing parallelism remains intact.
tiered_index->GetSVSIndex()->setNumThreads(num_available_threads);
size_t params_threadpool_size =
tiered_params.primaryIndexParams->algoParams.svsParams.num_threads;
size_t expected_capacity =
params_threadpool_size ? params_threadpool_size : mock_thread_pool.thread_pool_size;
verifyNumThreads(tiered_index, num_available_threads, expected_capacity);
return tiered_index;
}
TieredSVSIndex<data_t> *
CreateTieredSVSIndex(VecSimParams &svs_params, tieredIndexMock &mock_thread_pool,
size_t training_threshold = TestsDefaultTrainingThreshold,
size_t update_threshold = TestsDefaultUpdateThreshold,
size_t update_job_wait_time = SVS_DEFAULT_UPDATE_JOB_WAIT_TIME,
size_t num_available_threads = 1) {
svs_params.algoParams.svsParams.quantBits = index_type_t::get_quant_bits();
TieredIndexParams tiered_params =
CreateTieredSVSParams(svs_params, mock_thread_pool, training_threshold,
update_threshold, update_job_wait_time);
return CreateTieredSVSIndex(tiered_params, mock_thread_pool, num_available_threads);
}
void SetUp() override {
// Restore the write mode to default.
VecSim_SetWriteMode(VecSim_WriteAsync);
// Limit VecSim log level to avoid printing too much information
VecSimIndexInterface::setLogCallbackFunction(svsTestLogCallBackNoDebug);
}
// Check if the test is running in fallback mode to scalar quantization.
bool isFallbackToSQ() const {
// Get the fallback quantization mode and compare it to the scalar quantization mode.
return VecSimSvsQuant_Scalar ==
std::get<0>(svs_details::isSVSQuantBitsSupported(index_type_t::get_quant_bits()));
}
size_t getTrainingThreshold() const { return trainingThreshold; }
size_t getUpdateThreshold() const { return updateThreshold; }
private:
size_t trainingThreshold = TestsDefaultTrainingThreshold;
size_t updateThreshold = TestsDefaultUpdateThreshold;
};
// TEST_DATA_T and TEST_DIST_T are defined in test_utils.h
template <VecSimType type, typename DataType, VecSimSvsQuantBits quantBits>
struct SVSIndexType {
static constexpr VecSimType get_index_type() { return type; }
static constexpr VecSimSvsQuantBits get_quant_bits() { return quantBits; }
typedef DataType data_t;
};
// clang-format off
using SVSDataTypeSet = ::testing::Types<SVSIndexType<VecSimType_FLOAT32, float, VecSimSvsQuant_NONE>
,SVSIndexType<VecSimType_FLOAT32, float, VecSimSvsQuant_8>
>;
// clang-format on
TYPED_TEST_SUITE(SVSTieredIndexTest, SVSDataTypeSet);
// Runs the test for each data type(float/double). The label type should be explicitly
// set in the test.
template <typename index_type_t>
class SVSTieredIndexTestBasic : public SVSTieredIndexTest<index_type_t> {};
using SVSBasicDataTypeSet =
::testing::Types<SVSIndexType<VecSimType_FLOAT32, float, VecSimSvsQuant_NONE>>;
TYPED_TEST_SUITE(SVSTieredIndexTestBasic, SVSBasicDataTypeSet);
TYPED_TEST(SVSTieredIndexTest, ThreadsReservation) {
// Set thread_pool_size to 4 or actual number of available CPUs
const auto num_threads = std::min(4U, getAvailableCPUs());
if (num_threads < 2) {
// If the number of threads is less than 2, we can't run the test
GTEST_SKIP() << "No threads available";
}
std::chrono::milliseconds timeout{1000}; // long enough to reserve all threads
SVSParams params = {
.type = TypeParam::get_index_type(), .dim = 4, .metric = VecSimMetric_L2, .num_threads = 1};
VecSimParams svs_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
mock_thread_pool.thread_pool_size = num_threads;
// Create TieredSVS index instance with a mock queue.
auto *tiered_index = this->CreateTieredSVSIndex(svs_params, mock_thread_pool);
ASSERT_INDEX(tiered_index);
// Get the allocator from the tiered index.
auto allocator = tiered_index->getAllocator();
// Counter of reserved threads
// This is set in the update_job_mock callback only
std::atomic<size_t> num_reserved_threads = 0;
auto update_job_mock = [&num_reserved_threads](VecSimIndex * /*unused*/, size_t num_threads) {
num_reserved_threads = num_threads;
};
SVSMultiThreadJob::JobsRegistry registry(allocator);
// Request 4 threads but just 1 thread is available
auto jobs = SVSMultiThreadJob::createJobs(allocator, SVS_BATCH_UPDATE_JOB, update_job_mock,
tiered_index, 4, timeout, ®istry);
ASSERT_EQ(jobs.size(), 4);
tiered_index->submitJobs(jobs);
ASSERT_EQ(mock_thread_pool.jobQ.size(), 4);
// emulate 1 thread availability
mock_thread_pool.thread_iteration();
ASSERT_EQ(mock_thread_pool.jobQ.size(), 3);
ASSERT_EQ(num_reserved_threads, 1);
// Complete rest of wait jobs
mock_thread_pool.init_threads();
mock_thread_pool.thread_pool_wait();
ASSERT_EQ(mock_thread_pool.jobQ.size(), 0);
// Request and run exact number of available threads
jobs = SVSMultiThreadJob::createJobs(allocator, SVS_BATCH_UPDATE_JOB, update_job_mock,
tiered_index, num_threads, timeout, ®istry);
tiered_index->submitJobs(jobs);
mock_thread_pool.thread_pool_wait();
ASSERT_EQ(num_reserved_threads, num_threads);
// Request and run 1 thread
jobs = SVSMultiThreadJob::createJobs(allocator, SVS_BATCH_UPDATE_JOB, update_job_mock,
tiered_index, 1, timeout, ®istry);
tiered_index->submitJobs(jobs);
mock_thread_pool.thread_pool_wait();
ASSERT_EQ(num_reserved_threads, 1);
// Request and run less threads than available
jobs = SVSMultiThreadJob::createJobs(allocator, SVS_BATCH_UPDATE_JOB, update_job_mock,
tiered_index, num_threads - 1, timeout, ®istry);
tiered_index->submitJobs(jobs);
mock_thread_pool.thread_pool_wait();
// The number of reserved threads should be equal to requested
ASSERT_EQ(num_reserved_threads, num_threads - 1);
// Request more threads than available
jobs = SVSMultiThreadJob::createJobs(allocator, SVS_BATCH_UPDATE_JOB, update_job_mock,
tiered_index, num_threads + 1, timeout, ®istry);
tiered_index->submitJobs(jobs);
mock_thread_pool.thread_pool_wait();
// The number of reserved threads should be equal to the number of available threads
ASSERT_EQ(num_reserved_threads, num_threads);
mock_thread_pool.thread_pool_join();
}
TYPED_TEST(SVSTieredIndexTest, TestDebugInfoThreadCount) {
// Set thread_pool_size to 4 or actual number of available CPUs
const auto num_threads = std::min(4U, getAvailableCPUs());
if (num_threads < 2) {
// If the number of threads is less than 2, we can't run the test
GTEST_SKIP() << "No threads available";
}
constexpr size_t training_threshold = 10;
constexpr size_t update_threshold = 10;
constexpr size_t update_job_wait_time = 10000;
constexpr size_t dim = 4;
SVSParams params = {.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.num_threads = num_threads};
VecSimParams svs_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
mock_thread_pool.thread_pool_size = num_threads;
// Create TieredSVS index instance with a mock queue.
auto *tiered_index =
this->CreateTieredSVSIndex(svs_params, mock_thread_pool, training_threshold,
update_threshold, update_job_wait_time, num_threads);
ASSERT_INDEX(tiered_index);
// Verify initial state: both fields should equal configured thread count
VecSimIndexDebugInfo backendIndexInfo = tiered_index->GetBackendIndex()->debugInfo();
ASSERT_EQ(backendIndexInfo.svsInfo.numThreads, num_threads);
ASSERT_EQ(backendIndexInfo.svsInfo.lastReservedThreads, num_threads);
// Get the allocator from the tiered index.
auto allocator = tiered_index->getAllocator();
// Simulate thread contention by keeping one thread busy, to force reduced thread availability
std::atomic<bool> is_reserved = false;
std::atomic<bool> thread_wait = true;
auto reserve_and_wait = [&](VecSimIndex * /*unused*/, size_t num_threads) {
is_reserved = true;
while (thread_wait) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
};
// Keep one thread occupied
mock_thread_pool.init_threads();
SVSMultiThreadJob::JobsRegistry registry(allocator);
std::chrono::milliseconds timeout{update_job_wait_time}; // long enough to reserve one thread
auto jobs = SVSMultiThreadJob::createJobs(allocator, SVS_BATCH_UPDATE_JOB, reserve_and_wait,
tiered_index, 1, timeout, ®istry);
ASSERT_EQ(jobs.size(), 1);
tiered_index->submitJobs(jobs);
// Wait for thread reservation to complete
while (!is_reserved) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
// Trigger training with reduced thread availability
for (size_t i = 0; i < training_threshold; ++i) {
GenerateAndAddVector<TEST_DATA_T>(tiered_index, dim, i);
}
while (tiered_index->GetBackendIndex()->indexSize() != training_threshold) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
// Verify: numThreads unchanged, lastReservedThreads reflects actual availability
backendIndexInfo = tiered_index->GetBackendIndex()->debugInfo();
ASSERT_EQ(backendIndexInfo.svsInfo.numThreads, num_threads);
ASSERT_LE(backendIndexInfo.svsInfo.lastReservedThreads, num_threads - 1);
// Release occupied thread and trigger another background indexing
thread_wait = false;
mock_thread_pool.thread_pool_wait();
// add more vectors to trigger background indexing
for (size_t i = 0; i < update_threshold; ++i) {
GenerateAndAddVector<TEST_DATA_T>(tiered_index, dim, training_threshold + i);
}
mock_thread_pool.thread_pool_join();
// Verify: numThreads unchanged, lastReservedThreads reflects we used all configured threads
backendIndexInfo = tiered_index->GetBackendIndex()->debugInfo();
ASSERT_EQ(backendIndexInfo.svsInfo.numThreads, num_threads);
ASSERT_LE(backendIndexInfo.svsInfo.lastReservedThreads, num_threads);
}
TYPED_TEST(SVSTieredIndexTest, TestDebugInfoThreadCountWriteInPlace) {
// Test that write-in-place mode correctly reports thread usage in debug info.
// Even when the index is configured with multiple threads, write-in-place operations
// should use only 1 thread and lastReservedThreads should reflect this.
// Set thread_pool_size to 4 or actual number of available CPUs
const auto num_threads = std::min(4U, getAvailableCPUs());
if (num_threads < 2) {
// If the number of threads is less than 2, we can't run the test
GTEST_SKIP() << "No threads available";
}
// Test svs when mode is write in place, but the index is configured with multiple threads.
constexpr size_t training_threshold = 10;
constexpr size_t update_threshold = 10;
constexpr size_t update_job_wait_time = 10000;
constexpr size_t dim = 4;
SVSParams params = {.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.num_threads = num_threads};
VecSimParams svs_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
mock_thread_pool.thread_pool_size = num_threads;
// Create TieredSVS index instance with a mock queue.
auto *tiered_index =
this->CreateTieredSVSIndex(svs_params, mock_thread_pool, training_threshold,
update_threshold, update_job_wait_time, num_threads);
ASSERT_INDEX(tiered_index);
// Set to mode to write in place even though the index is configured with multiple threads.
VecSim_SetWriteMode(VecSim_WriteInPlace);
// Verify initial state: both fields should equal configured thread count
VecSimIndexDebugInfo backendIndexInfo = tiered_index->GetBackendIndex()->debugInfo();
ASSERT_EQ(backendIndexInfo.svsInfo.numThreads, num_threads);
ASSERT_EQ(backendIndexInfo.svsInfo.lastReservedThreads, num_threads);
// Get the allocator from the tiered index.
auto allocator = tiered_index->getAllocator();
mock_thread_pool.init_threads();
// Trigger training
for (size_t i = 0; i < training_threshold; ++i) {
GenerateAndAddVector<TEST_DATA_T>(tiered_index, dim, i);
}
ASSERT_EQ(mock_thread_pool.jobQ.size(), 0);
while (tiered_index->GetBackendIndex()->indexSize() != training_threshold) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
// Verify: numThreads unchanged, lastReservedThreads reflects we only used one thread (main
// thread)
backendIndexInfo = tiered_index->GetBackendIndex()->debugInfo();
ASSERT_EQ(backendIndexInfo.svsInfo.numThreads, num_threads);
ASSERT_EQ(backendIndexInfo.svsInfo.lastReservedThreads, 1);
// add more vectors, each will be directly inserted to the backend index
size_t num_vectors = 10;
for (size_t i = 0; i < num_vectors; ++i) {
GenerateAndAddVector<TEST_DATA_T>(tiered_index, dim, training_threshold + i);
// Verify: numThreads unchanged, lastReservedThreads reflects we used only one thread
backendIndexInfo = tiered_index->GetBackendIndex()->debugInfo();
ASSERT_EQ(backendIndexInfo.svsInfo.numThreads, num_threads);
ASSERT_EQ(backendIndexInfo.svsInfo.lastReservedThreads, 1);
ASSERT_EQ(mock_thread_pool.jobQ.size(), 0);
}
}
TYPED_TEST(SVSTieredIndexTest, TestAddOneVectorAsync) {
auto mock_thread_pool = tieredIndexMock();
const auto num_threads = mock_thread_pool.thread_pool_size;
if (num_threads < 2) {
// If the number of threads is less than 2, this test has no point.
GTEST_SKIP() << "No threads available";
}
constexpr size_t training_threshold = 1;
constexpr size_t update_threshold = 1;
constexpr size_t update_job_wait_time = 10000;
constexpr size_t dim = 4;
SVSParams params = {.type = TypeParam::get_index_type(), .dim = dim, .metric = VecSimMetric_L2};
VecSimParams svs_params = CreateParams(params);
// Create TieredSVS index instance with a mock queue.
auto *tiered_index = this->CreateTieredSVSIndex(
svs_params, mock_thread_pool, training_threshold, update_threshold, update_job_wait_time);
ASSERT_INDEX(tiered_index);
mock_thread_pool.init_threads();
// Verify initial state: both fields should equal configured thread count
VecSimIndexDebugInfo backendIndexInfo = tiered_index->GetBackendIndex()->debugInfo();
ASSERT_EQ(backendIndexInfo.svsInfo.numThreads, num_threads);
// Add one vector - this should trigger background training
GenerateAndAddVector<TEST_DATA_T>(tiered_index, dim, 0);
mock_thread_pool.thread_pool_wait();
ASSERT_EQ(tiered_index->GetBackendIndex()->indexSize(), 1);
// Verify: numThreads unchanged, and we used one thread
backendIndexInfo = tiered_index->GetBackendIndex()->debugInfo();
ASSERT_EQ(backendIndexInfo.svsInfo.numThreads, num_threads);
ASSERT_EQ(backendIndexInfo.svsInfo.lastReservedThreads, 1);
// add another vectors to trigger background indexing
GenerateAndAddVector<TEST_DATA_T>(tiered_index, dim, 1);
mock_thread_pool.thread_pool_join();
ASSERT_EQ(tiered_index->GetBackendIndex()->indexSize(), 2);
// Verify: yet again, numThreads unchanged, and we used one thread
backendIndexInfo = tiered_index->GetBackendIndex()->debugInfo();
ASSERT_EQ(backendIndexInfo.svsInfo.numThreads, num_threads);
ASSERT_EQ(backendIndexInfo.svsInfo.lastReservedThreads, 1);
}
TYPED_TEST(SVSTieredIndexTest, CreateIndexInstance) {
// Create TieredSVS index instance with a mock queue.
SVSParams params = {.type = TypeParam::get_index_type(), .dim = 4, .metric = VecSimMetric_L2};
VecSimParams svs_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredSVSIndex(svs_params, mock_thread_pool);
ASSERT_INDEX(tiered_index);
// Get the allocator from the tiered index.
auto allocator = tiered_index->getAllocator();
// Add a vector to the flat index.
TEST_DATA_T vector[params.dim];
GenerateVector<TEST_DATA_T>(vector, params.dim);
labelType vector_label = 1;
VecSimIndex_AddVector(tiered_index, vector, vector_label);
ASSERT_EQ(tiered_index->GetFlatIndex()->indexSize(), 1);
ASSERT_EQ(tiered_index->GetBackendIndex()->indexSize(), 0);
// Submit the index update job.
tiered_index->scheduleSVSIndexUpdate();
ASSERT_EQ(mock_thread_pool.jobQ.size(), mock_thread_pool.thread_pool_size);
// Execute the job from the queue and validate that the index was updated properly.
mock_thread_pool.thread_iteration();
ASSERT_EQ(tiered_index->indexSize(), 1);
ASSERT_EQ(tiered_index->getDistanceFrom_Unsafe(1, vector), 0);
ASSERT_EQ(tiered_index->GetFlatIndex()->indexSize(), 0);
ASSERT_EQ(tiered_index->GetBackendIndex()->indexSize(), 1);
}
TYPED_TEST(SVSTieredIndexTest, addVector) {
// Create TieredSVS index instance with a mock queue.
size_t dim = 4;
SVSParams params = {.type = TypeParam::get_index_type(), .dim = dim, .metric = VecSimMetric_L2};
VecSimParams svs_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto tiered_params = this->CreateTieredSVSParams(svs_params, mock_thread_pool, 1, 1);
auto *tiered_index = this->CreateTieredSVSIndex(tiered_params, mock_thread_pool);
ASSERT_INDEX(tiered_index);
// Get the allocator from the tiered index.
auto allocator = tiered_index->getAllocator();
BFParams bf_params = {
.type = TypeParam::get_index_type(), .dim = dim, .metric = VecSimMetric_L2, .multi = false};
size_t expected_mem = TieredFactory::EstimateInitialSize(&tiered_params);
ASSERT_LE(expected_mem, tiered_index->getAllocationSize());
ASSERT_GE(expected_mem * 1.02, tiered_index->getAllocationSize());
ASSERT_EQ(mock_thread_pool.jobQ.size(), 0);
// Create a vector and add it to the tiered index.
labelType vec_label = 1;
TEST_DATA_T vector[dim];
GenerateVector<TEST_DATA_T>(vector, dim, vec_label);
VecSimIndex_AddVector(tiered_index, vector, vec_label);
// Validate that the vector was inserted to the flat buffer properly.
ASSERT_EQ(tiered_index->indexSize(), 1);
ASSERT_EQ(tiered_index->GetFlatIndex()->indexSize(), 1);
ASSERT_EQ(tiered_index->GetBackendIndex()->indexSize(), 0);
ASSERT_EQ(tiered_index->GetFlatIndex()->indexCapacity(), DEFAULT_BLOCK_SIZE);
ASSERT_EQ(tiered_index->indexCapacity(), DEFAULT_BLOCK_SIZE);
ASSERT_EQ(tiered_index->indexMetaDataCapacity(), tiered_index->indexCapacity());
ASSERT_EQ(tiered_index->GetFlatIndex()->getDistanceFrom_Unsafe(vec_label, vector), 0);
ASSERT_EQ(mock_thread_pool.jobQ.size(), mock_thread_pool.thread_pool_size);
// Account for the allocation of a new block due to the vector insertion.
expected_mem += (BruteForceFactory::EstimateElementSize(&bf_params)) * DEFAULT_BLOCK_SIZE;
// Account for the memory that was allocated in the labelToId map (approx.)
expected_mem += sizeof(vecsim_stl::unordered_map<labelType, idType>::value_type) +
sizeof(void *) + sizeof(size_t);
// Account for the insert job that was created.
expected_mem +=
SVSMultiThreadJob::estimateSize(mock_thread_pool.thread_pool_size) + sizeof(size_t);
auto actual_mem = tiered_index->getAllocationSize();
ASSERT_GE(expected_mem * 1.02, tiered_index->getAllocationSize());
ASSERT_LE(expected_mem, tiered_index->getAllocationSize());
}
TYPED_TEST(SVSTieredIndexTest, background_indexing_check) {
// Create TieredSVS index instance with a mock queue.
size_t dim = 2;
constexpr size_t training_th = DEFAULT_BLOCK_SIZE;
constexpr size_t update_th = DEFAULT_BLOCK_SIZE;
SVSParams params = {.type = TypeParam::get_index_type(), .dim = dim, .metric = VecSimMetric_L2};
VecSimParams svs_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto tiered_params =
this->CreateTieredSVSParams(svs_params, mock_thread_pool, training_th, update_th);
auto *tiered_index = this->CreateTieredSVSIndex(tiered_params, mock_thread_pool);
ASSERT_INDEX(tiered_index);
mock_thread_pool.init_threads();
for (size_t i = 0; i < training_th; i++) {
TEST_DATA_T vector[dim];
GenerateVector<TEST_DATA_T>(vector, dim, i);
VecSimIndex_AddVector(tiered_index, vector, i);
}
while (tiered_index->debugInfo().tieredInfo.backgroundIndexing != VecSimBool_FALSE) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
ASSERT_EQ(tiered_index->GetBackendIndex()->indexSize(), training_th);
ASSERT_EQ(tiered_index->GetFlatIndex()->indexSize(), 0);
ASSERT_EQ(tiered_index->indexSize(), training_th);
constexpr size_t second_batch = 2500;
for (size_t i = 0; i < second_batch; i++) {
TEST_DATA_T vector[dim];
GenerateVector<TEST_DATA_T>(vector, dim, i);
VecSimIndex_AddVector(tiered_index, vector, training_th + i);
}
while (tiered_index->debugInfo().tieredInfo.backgroundIndexing != VecSimBool_FALSE) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
ASSERT_GT(tiered_index->GetBackendIndex()->indexSize(), training_th + second_batch / update_th);
ASSERT_LT(tiered_index->GetFlatIndex()->indexSize(), update_th);
ASSERT_EQ(tiered_index->indexSize(), second_batch + training_th);
}
TYPED_TEST(SVSTieredIndexTest, insertJob) {
// Create TieredSVS index instance with a mock queue.
size_t dim = 4;
SVSParams params = {.type = TypeParam::get_index_type(), .dim = dim, .metric = VecSimMetric_L2};
VecSimParams svs_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
// Force thired index to submit the update job on every insert.
auto *tiered_index = this->CreateTieredSVSIndex(svs_params, mock_thread_pool, 1, 1);
ASSERT_INDEX(tiered_index);
auto allocator = tiered_index->getAllocator();
// Create a vector and add it to the tiered index.
labelType vec_label = 1;
TEST_DATA_T vector[dim];
GenerateVector<TEST_DATA_T>(vector, dim, vec_label);
VecSimIndex_AddVector(tiered_index, vector, vec_label);
ASSERT_EQ(tiered_index->indexSize(), 1);
ASSERT_EQ(tiered_index->GetFlatIndex()->indexSize(), 1);
// Execute the insert job manually (in a synchronous manner).
ASSERT_EQ(mock_thread_pool.jobQ.size(), mock_thread_pool.thread_pool_size);
auto *insertion_job = mock_thread_pool.jobQ.front().job;
ASSERT_EQ(insertion_job->jobType, SVS_BATCH_UPDATE_JOB);
mock_thread_pool.thread_iteration();
ASSERT_EQ(tiered_index->indexSize(), 1);
ASSERT_EQ(tiered_index->GetFlatIndex()->indexSize(), 0);
ASSERT_EQ(tiered_index->GetBackendIndex()->indexSize(), 1);
// SVS index should have allocated a single record, while flat index should remove the
// block.
// Compression datasets do not provide a capacity method
const size_t expected_capacity = TypeParam::get_quant_bits() == VecSimSvsQuant_NONE
? DEFAULT_BLOCK_SIZE
: tiered_index->GetBackendIndex()->indexCapacity();
ASSERT_EQ(tiered_index->indexCapacity(), expected_capacity);
ASSERT_EQ(tiered_index->indexMetaDataCapacity(), tiered_index->indexCapacity());
ASSERT_EQ(tiered_index->GetFlatIndex()->indexCapacity(), 0);
ASSERT_EQ(tiered_index->getDistanceFrom_Unsafe(vec_label, vector), 0);
}
TYPED_TEST(SVSTieredIndexTest, insertJobAsync) {
size_t dim = 4;
size_t n = 1000;
SVSParams params = {.type = TypeParam::get_index_type(), .dim = dim, .metric = VecSimMetric_L2};
VecSimParams svs_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
// Forcibly set the training threshold to a value that will trigger the update job
// after inserting a half of vectors.
auto *tiered_index = this->CreateTieredSVSIndex(svs_params, mock_thread_pool, n / 2);
ASSERT_INDEX(tiered_index);
auto allocator = tiered_index->getAllocator();
// Launch the BG threads loop that takes jobs from the queue and executes them.
mock_thread_pool.init_threads();
// Insert vectors
for (size_t i = 0; i < n; i++) {
GenerateAndAddVector<TEST_DATA_T>(tiered_index, dim, i, i / (TEST_DATA_T)n);
}
mock_thread_pool.thread_pool_join();
ASSERT_EQ(tiered_index->indexSize(), n);
ASSERT_EQ(mock_thread_pool.jobQ.size(), 0);
// Verify that vectors were moved to SVS as expected
auto sz_f = tiered_index->GetFlatIndex()->indexSize();
auto sz_b = tiered_index->GetBackendIndex()->indexSize();
EXPECT_LE(sz_f, this->getUpdateThreshold());
EXPECT_EQ(sz_f + sz_b, n);
// Quantization has limited accuaracy, so we need to check the relative error.
// If quantization is enabled, we allow a larger relative error.
double abs_err = TypeParam::get_quant_bits() != VecSimSvsQuant_NONE ? 1e-2 : 1e-6;
// Verify that the vectors were inserted to Flat/SVS as expected
for (size_t i = 0; i < n; i++) {
TEST_DATA_T expected_vector[dim];
GenerateVector<TEST_DATA_T>(expected_vector, dim, i / (TEST_DATA_T)n);
ASSERT_NEAR(tiered_index->getDistanceFrom_Unsafe(i, expected_vector), 0, abs_err)
<< "Vector label: " << i;
}
}
TYPED_TEST(SVSTieredIndexTest, KNNSearch) {
// Scalar quantization accuracy is insufficient for this test.
if (this->isFallbackToSQ()) {
GTEST_SKIP() << "SVS Scalar quantization accuracy is insufficient for this test.";
}
size_t dim = 4;
size_t k = 10;
size_t n = k * 3;
// Create TieredSVS index instance with a mock queue.
SVSParams params = {
.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
};
VecSimParams svs_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
size_t cur_memory_usage;
auto *tiered_index = this->CreateTieredSVSIndex(svs_params, mock_thread_pool, k, 1);
ASSERT_INDEX(tiered_index);
auto allocator = tiered_index->getAllocator();
EXPECT_EQ(mock_thread_pool.ctx->index_strong_ref.use_count(), 1);
auto svs_index = tiered_index->GetBackendIndex();
auto flat_index = tiered_index->GetFlatIndex();
TEST_DATA_T query_0[dim];
GenerateVector<TEST_DATA_T>(query_0, dim, 0);
TEST_DATA_T query_1mid[dim];
GenerateVector<TEST_DATA_T>(query_1mid, dim, n / 3);
TEST_DATA_T query_2mid[dim];
GenerateVector<TEST_DATA_T>(query_2mid, dim, n * 2 / 3);
TEST_DATA_T query_n[dim];
GenerateVector<TEST_DATA_T>(query_n, dim, n - 1);
// Search for vectors when the index is empty.
runTopKSearchTest(tiered_index, query_0, k, nullptr);
// Define the verification functions.
auto ver_res_0 = [&](size_t id, double score, size_t index) {
ASSERT_EQ(id, index);
ASSERT_DOUBLE_EQ(score, dim * id * id);
};
auto ver_res_1mid = [&](size_t id, double score, size_t index) {
ASSERT_EQ(std::abs(int(id - query_1mid[0])), (index + 1) / 2);
ASSERT_DOUBLE_EQ(score, dim * pow((index + 1) / 2, 2));
};
auto ver_res_2mid = [&](size_t id, double score, size_t index) {
ASSERT_EQ(std::abs(int(id - query_2mid[0])), (index + 1) / 2);
ASSERT_DOUBLE_EQ(score, dim * pow((index + 1) / 2, 2));
};
auto ver_res_n = [&](size_t id, double score, size_t index) {
ASSERT_EQ(id, n - 1 - index);
ASSERT_DOUBLE_EQ(score, dim * index * index);
};
// Insert n/2 vectors to the main index.
for (size_t i = 0; i < n / 2; i++) {
GenerateAndAddVector<TEST_DATA_T>(svs_index, dim, i, i);
}
ASSERT_EQ(tiered_index->indexSize(), n / 2);
ASSERT_EQ(tiered_index->indexSize(), svs_index->indexSize());
// Search for k vectors with the flat index empty.
cur_memory_usage = allocator->getAllocationSize();
runTopKSearchTest(tiered_index, query_0, k, ver_res_0);
runTopKSearchTest(tiered_index, query_1mid, k, ver_res_1mid);
ASSERT_EQ(allocator->getAllocationSize(), cur_memory_usage);
// Insert n/2 vectors to the flat index.
for (size_t i = n / 2; i < n; i++) {
GenerateAndAddVector<TEST_DATA_T>(flat_index, dim, i, i);
}
ASSERT_EQ(tiered_index->indexSize(), n);
ASSERT_EQ(tiered_index->indexSize(), svs_index->indexSize() + flat_index->indexSize());
cur_memory_usage = allocator->getAllocationSize();
// Search for k vectors so all the vectors will be from the flat index.
runTopKSearchTest(tiered_index, query_0, k, ver_res_0);
// Search for k vectors so all the vectors will be from the main index.
runTopKSearchTest(tiered_index, query_n, k, ver_res_n);
// Search for k so some of the results will be from the main and some from the flat index.
runTopKSearchTest(tiered_index, query_1mid, k, ver_res_1mid);
runTopKSearchTest(tiered_index, query_2mid, k, ver_res_2mid);
// Memory usage should not change.
ASSERT_EQ(allocator->getAllocationSize(), cur_memory_usage);
// Add some overlapping vectors to the main and flat index.
// adding directly to the underlying indexes to avoid jobs logic.
// The main index will have vectors 0 - 2n/3 and the flat index will have vectors n/3 - n
for (size_t i = n / 3; i < n / 2; i++) {
GenerateAndAddVector<TEST_DATA_T>(flat_index, dim, i, i);
}
for (size_t i = n / 2; i < n * 2 / 3; i++) {
GenerateAndAddVector<TEST_DATA_T>(svs_index, dim, i, i);
}
cur_memory_usage = allocator->getAllocationSize();
// Search for k vectors so all the vectors will be from the main index.
runTopKSearchTest(tiered_index, query_0, k, ver_res_0);
// Search for k vectors so all the vectors will be from the flat index.
runTopKSearchTest(tiered_index, query_n, k, ver_res_n);
// Search for k so some of the results will be from the main and some from the flat index.
runTopKSearchTest(tiered_index, query_1mid, k, ver_res_1mid);
runTopKSearchTest(tiered_index, query_2mid, k, ver_res_2mid);
// Memory usage should not change.
ASSERT_EQ(allocator->getAllocationSize(), cur_memory_usage);
// More edge cases:
// Search for more vectors than the index size.
k = n + 1;
runTopKSearchTest(tiered_index, query_0, k, ver_res_0);
runTopKSearchTest(tiered_index, query_n, k, ver_res_n);
// Search for less vectors than the index size, but more than the flat and main index sizes.
k = n * 5 / 6;
runTopKSearchTest(tiered_index, query_0, k, ver_res_0);
runTopKSearchTest(tiered_index, query_n, k, ver_res_n);
// Memory usage should not change.
ASSERT_EQ(allocator->getAllocationSize(), cur_memory_usage);
// Search for more vectors than the main index size, but less than the flat index size.
for (size_t i = n / 2; i < n * 2 / 3; i++) {
VecSimIndex_DeleteVector(svs_index, i);
}
ASSERT_EQ(flat_index->indexSize(), n * 2 / 3);
ASSERT_EQ(svs_index->indexSize(), n / 2);
k = n * 2 / 3;
cur_memory_usage = allocator->getAllocationSize();
runTopKSearchTest(tiered_index, query_0, k, ver_res_0);
runTopKSearchTest(tiered_index, query_n, k, ver_res_n);
runTopKSearchTest(tiered_index, query_1mid, k, ver_res_1mid);
runTopKSearchTest(tiered_index, query_2mid, k, ver_res_2mid);
// Memory usage should not change.
ASSERT_EQ(allocator->getAllocationSize(), cur_memory_usage);
// Search for more vectors than the flat index size, but less than the main index size.
for (size_t i = n / 2; i < n; i++) {
VecSimIndex_DeleteVector(flat_index, i);
}
ASSERT_EQ(flat_index->indexSize(), n / 6);
ASSERT_EQ(svs_index->indexSize(), n / 2);
k = n / 4;
cur_memory_usage = allocator->getAllocationSize();
runTopKSearchTest(tiered_index, query_0, k, ver_res_0);
runTopKSearchTest(tiered_index, query_1mid, k, ver_res_1mid);
// Memory usage should not change.
ASSERT_EQ(allocator->getAllocationSize(), cur_memory_usage);
// Search for vectors when the flat index is not empty but the main index is empty.
for (size_t i = 0; i < n * 2 / 3; i++) {
VecSimIndex_DeleteVector(svs_index, i);
GenerateAndAddVector<TEST_DATA_T>(flat_index, dim, i, i);
}
ASSERT_EQ(flat_index->indexSize(), n * 2 / 3);
ASSERT_EQ(svs_index->indexSize(), 0);
k = n / 3;
cur_memory_usage = allocator->getAllocationSize();
runTopKSearchTest(tiered_index, query_0, k, ver_res_0);
runTopKSearchTest(tiered_index, query_1mid, k, ver_res_1mid);
// Memory usage should not change.
ASSERT_EQ(allocator->getAllocationSize(), cur_memory_usage);
// // // // // // // // // // // //
// Check behavior upon timeout. //
// // // // // // // // // // // //
VecSimQueryReply *res;
// Add a vector to the SVS index so there will be a reason to query it.
GenerateAndAddVector<TEST_DATA_T>(svs_index, dim, n, n);
// Set timeout callback to always return 1 (will fail while querying the flat buffer).
VecSim_SetTimeoutCallbackFunction([](void *ctx) { return 1; }); // Always times out
res = VecSimIndex_TopKQuery(tiered_index, query_0, k, nullptr, BY_SCORE);
ASSERT_TRUE(res->results.empty());
ASSERT_EQ(VecSimQueryReply_GetCode(res), VecSim_QueryReply_TimedOut);
VecSimQueryReply_Free(res);
// Set timeout callback to return 1 after n checks (will fail while querying the SVS index).
// Brute-force index checks for timeout after each vector.
size_t checks_in_flat = flat_index->indexSize();
VecSimQueryParams qparams = {.timeoutCtx = &checks_in_flat};
VecSim_SetTimeoutCallbackFunction([](void *ctx) {
auto count = static_cast<size_t *>(ctx);
if (*count == 0) {
return 1;
}
(*count)--;
return 0;
});
res = VecSimIndex_TopKQuery(tiered_index, query_0, k, &qparams, BY_SCORE);
ASSERT_TRUE(res->results.empty());
ASSERT_EQ(VecSimQueryReply_GetCode(res), VecSim_QueryReply_TimedOut);
VecSimQueryReply_Free(res);
// Make sure we didn't get the timeout in the flat index.
checks_in_flat = flat_index->indexSize(); // Reset the counter.
res = VecSimIndex_TopKQuery(flat_index, query_0, k, &qparams, BY_SCORE);
ASSERT_EQ(VecSimQueryReply_GetCode(res), VecSim_QueryReply_OK);
VecSimQueryReply_Free(res);
// Clean up.
VecSim_SetTimeoutCallbackFunction([](void *ctx) { return 0; });
}
TYPED_TEST(SVSTieredIndexTest, KNNSearchCosine) {
// Scalar quantization accuracy is insufficient for this test.
if (this->isFallbackToSQ()) {
GTEST_SKIP() << "SVS Scalar quantization accuracy is insufficient for this test.";
}
const size_t dim = 128;
const size_t n = 100;
SVSParams params = {
.type = TypeParam::get_index_type(), .dim = dim, .metric = VecSimMetric_Cosine};
VecSimParams svs_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredSVSIndex(svs_params, mock_thread_pool, n);
ASSERT_INDEX(tiered_index);
auto allocator = tiered_index->getAllocator();
// Launch the BG threads loop that takes jobs from the queue and executes them.
mock_thread_pool.init_threads();
for (size_t i = 1; i <= n; i++) {
TEST_DATA_T f[dim];
f[0] = (TEST_DATA_T)i / n;
for (size_t j = 1; j < dim; j++) {
f[j] = 1.0;
}
VecSimIndex_AddVector(tiered_index, f, i);
}
mock_thread_pool.thread_pool_join();
ASSERT_EQ(VecSimIndex_IndexSize(tiered_index), n);
// Verify that vectors were moved to SVS as expected
auto sz_f = tiered_index->GetFlatIndex()->indexSize();
auto sz_b = tiered_index->GetBackendIndex()->indexSize();
EXPECT_LE(sz_f, this->getUpdateThreshold());
EXPECT_EQ(sz_f + sz_b, n);
TEST_DATA_T query[dim];
GenerateVector<TEST_DATA_T>(query, dim, 1.0);
// topK search will normalize the query so we keep the original data to
// avoid normalizing twice.
TEST_DATA_T normalized_query[dim];
memcpy(normalized_query, query, dim * sizeof(TEST_DATA_T));
VecSim_Normalize(normalized_query, dim, params.type);
auto verify_res = [&](size_t id, double score, size_t result_rank) {
ASSERT_EQ(id, (n - result_rank));
TEST_DATA_T expected_score = tiered_index->getDistanceFrom_Unsafe(id, normalized_query);
// Verify that abs difference between the actual and expected score is at most 1/10^5.
ASSERT_NEAR((TEST_DATA_T)score, expected_score, 1e-5f);
};
runTopKSearchTest(tiered_index, query, 10, verify_res);
}
TYPED_TEST(SVSTieredIndexTest, deleteVector) {
// Create TieredSVS index instance with a mock queue.
size_t dim = 4;
SVSParams params = {.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.num_threads = 1};
VecSimParams svs_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredSVSIndex(svs_params, mock_thread_pool, 1, 1);
ASSERT_INDEX(tiered_index);
auto allocator = tiered_index->getAllocator();
labelType vec_label = 0;
// Delete from an empty index.
ASSERT_EQ(tiered_index->deleteVector(vec_label), 0);
// Create a vector and add it to the tiered index (expect it to go into the flat buffer).
TEST_DATA_T vector[dim];
GenerateVector<TEST_DATA_T>(vector, dim, vec_label);
VecSimIndex_AddVector(tiered_index, vector, vec_label);
ASSERT_EQ(tiered_index->indexSize(), 1);
ASSERT_EQ(tiered_index->GetFlatIndex()->indexSize(), 1);
// Remove vector from flat buffer.
ASSERT_EQ(tiered_index->deleteVector(vec_label), 1);
ASSERT_EQ(tiered_index->indexSize(), 0);
ASSERT_EQ(tiered_index->GetFlatIndex()->indexSize(), 0);
mock_thread_pool.thread_iteration();
ASSERT_EQ(tiered_index->GetBackendIndex()->indexSize(), 0);
// Create a vector and add it to SVS in the tiered index.
VecSimIndex_AddVector(tiered_index->GetBackendIndex(), vector, vec_label);
ASSERT_EQ(tiered_index->indexSize(), 1);
ASSERT_EQ(tiered_index->GetBackendIndex()->indexSize(), 1);
// Remove from main index.
ASSERT_EQ(tiered_index->deleteVector(vec_label), 1);
ASSERT_EQ(tiered_index->indexLabelCount(), 0);
ASSERT_EQ(tiered_index->indexSize(), 0);
// Re-insert a deleted label with a different vector.
TEST_DATA_T new_vec_val = 2.0;
GenerateVector<TEST_DATA_T>(vector, dim, new_vec_val);
VecSimIndex_AddVector(tiered_index, vector, vec_label);
ASSERT_EQ(tiered_index->indexSize(), 1);
ASSERT_EQ(tiered_index->GetFlatIndex()->indexSize(), 1);
// Move the vector to SVS by executing the insert job.
mock_thread_pool.thread_iteration();
ASSERT_EQ(tiered_index->indexLabelCount(), 1);
ASSERT_EQ(tiered_index->GetBackendIndex()->indexSize(), 1);
// Scalar quantization accuracy is insufficient for this check.
if (!this->isFallbackToSQ()) {