-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathtest_hnsw_tiered.cpp
More file actions
3873 lines (3354 loc) · 181 KB
/
test_hnsw_tiered.cpp
File metadata and controls
3873 lines (3354 loc) · 181 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/algorithms/hnsw/hnsw_tiered.h"
#include "VecSim/algorithms/hnsw/hnsw_single.h"
#include "VecSim/algorithms/hnsw/hnsw_multi.h"
#include <string>
#include <array>
#include "test_utils.h"
#include "mock_thread_pool.h"
#include <thread>
// Runs the test for all combination of data type(float/double) - label type (single/multi)
template <typename index_type_t>
class HNSWTieredIndexTest : public ::testing::Test {
public:
using data_t = typename index_type_t::data_t;
using dist_t = typename index_type_t::dist_t;
protected:
HNSWIndex<data_t, dist_t> *CastToHNSW(VecSimIndex *index) {
auto tiered_index = reinterpret_cast<TieredHNSWIndex<data_t, dist_t> *>(index);
return tiered_index->getHNSWIndex();
}
TieredHNSWIndex<data_t, dist_t> *CreateTieredHNSWIndex(VecSimParams &hnsw_params,
tieredIndexMock &mock_thread_pool,
size_t swap_job_threshold = 0,
size_t flat_buffer_limit = SIZE_MAX) {
TieredIndexParams tiered_params = {
.jobQueue = &mock_thread_pool.jobQ,
.jobQueueCtx = mock_thread_pool.ctx,
.submitCb = tieredIndexMock::submit_callback,
.flatBufferLimit = flat_buffer_limit,
.primaryIndexParams = &hnsw_params,
.specificParams = {TieredHNSWParams{.swapJobThreshold = swap_job_threshold}}};
auto *tiered_index = reinterpret_cast<TieredHNSWIndex<data_t, dist_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);
return tiered_index;
}
};
TYPED_TEST_SUITE(HNSWTieredIndexTest, DataTypeSetExtended);
// 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 HNSWTieredIndexTestBasic : public HNSWTieredIndexTest<index_type_t> {};
TYPED_TEST_SUITE(HNSWTieredIndexTestBasic, DataTypeSet);
TYPED_TEST(HNSWTieredIndexTest, CreateIndexInstance) {
// Create TieredHNSW index instance with a mock queue.
HNSWParams params = {.type = TypeParam::get_index_type(),
.dim = 4,
.metric = VecSimMetric_L2,
.multi = TypeParam::isMulti()};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
// Get the allocator from the tiered index.
auto allocator = tiered_index->getAllocator();
// Add a vector to the flat index.
TEST_DATA_T vector[tiered_index->backendIndex->getDim()];
GenerateVector<TEST_DATA_T>(vector, tiered_index->backendIndex->getDim());
labelType vector_label = 1;
VecSimIndex_AddVector(tiered_index->frontendIndex, vector, vector_label);
// Create a mock job that inserts some vector into the HNSW index.
auto insert_to_index = [](AsyncJob *job) {
auto *my_insert_job = reinterpret_cast<HNSWInsertJob *>(job);
auto my_index =
reinterpret_cast<TieredHNSWIndex<TEST_DATA_T, TEST_DIST_T> *>(my_insert_job->index);
// Move the vector from the temp flat index into the HNSW index.
// Note that we access the vector via its internal id since in index of type MULTI,
// this is the only way to do so (knowing the label is not enough...)
VecSimIndex_AddVector(my_index->backendIndex,
my_index->frontendIndex->getDataByInternalId(my_insert_job->id),
my_insert_job->label);
// TODO: enable deleting vectors by internal id for the case of moving a single vector
// from the flat buffer in MULTI.
VecSimIndex_DeleteVector(my_index->frontendIndex, my_insert_job->label);
auto it = my_index->labelToInsertJobs.at(my_insert_job->label).begin();
ASSERT_EQ(job, *it); // Assert pointers equation
// Here we update labelToInsertJobs mapping, as we except that for every insert job
// there will be a corresponding item in the map.
my_index->labelToInsertJobs.at(my_insert_job->label).erase(it);
delete job;
};
auto job = new (allocator)
HNSWInsertJob(tiered_index->allocator, vector_label, 0, insert_to_index, tiered_index);
auto jobs_vec = vecsim_stl::vector<HNSWInsertJob *>(1, job, allocator);
tiered_index->labelToInsertJobs.insert({vector_label, jobs_vec});
// Wrap this job with an array and submit the jobs to the queue.
// TODO: in the future this should be part of the tiered index "add_vector" flow, and
// we can replace this to avoid the breaking of the abstraction.
tiered_index->submitSingleJob((AsyncJob *)job);
ASSERT_EQ(mock_thread_pool.jobQ.size(), 1);
// 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->frontendIndex->indexSize(), 0);
ASSERT_EQ(tiered_index->labelToInsertJobs.at(vector_label).size(), 0);
}
TYPED_TEST(HNSWTieredIndexTest, testSizeEstimation) {
size_t dim = 128;
size_t n = DEFAULT_BLOCK_SIZE;
size_t M = 32;
size_t bs = DEFAULT_BLOCK_SIZE;
bool isMulti = TypeParam::isMulti();
HNSWParams hnsw_params = {.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.multi = isMulti,
.initialCapacity = n,
.M = M};
VecSimParams vecsim_hnsw_params = CreateParams(hnsw_params);
auto mock_thread_pool = tieredIndexMock();
TieredIndexParams tiered_params = {.jobQueue = &mock_thread_pool.jobQ,
.jobQueueCtx = mock_thread_pool.ctx,
.submitCb = tieredIndexMock::submit_callback,
.flatBufferLimit = SIZE_MAX,
.primaryIndexParams = &vecsim_hnsw_params};
VecSimParams params = CreateParams(tiered_params);
auto *index = VecSimIndex_New(¶ms);
mock_thread_pool.ctx->index_strong_ref.reset(index);
auto allocator = index->getAllocator();
size_t initial_size_estimation = VecSimIndex_EstimateInitialSize(¶ms);
// labels_lookup hash table has additional memory, since STL implementation chooses "an
// appropriate prime number" higher than n as the number of allocated buckets (for n=1000, 1031
// buckets are created)
auto hnsw_index = this->CastToHNSW(index);
if (isMulti == false) {
auto hnsw = reinterpret_cast<HNSWIndex_Single<TEST_DATA_T, TEST_DIST_T> *>(hnsw_index);
initial_size_estimation += (hnsw->labelLookup.bucket_count() - n) * sizeof(size_t);
} else { // if its a multi value index cast to HNSW_Multi
auto hnsw = reinterpret_cast<HNSWIndex_Multi<TEST_DATA_T, TEST_DIST_T> *>(hnsw_index);
initial_size_estimation += (hnsw->labelLookup.bucket_count() - n) * sizeof(size_t);
}
ASSERT_EQ(initial_size_estimation, index->getAllocationSize());
// Add vectors up to initial capacity (initial capacity == block size).
for (size_t i = 0; i < n; i++) {
GenerateAndAddVector<TEST_DATA_T>(index, dim, i, i);
mock_thread_pool.thread_iteration();
}
// Estimate memory delta for filling up the first block and adding another block.
size_t estimation = VecSimIndex_EstimateElementSize(¶ms) * bs;
size_t before = index->getAllocationSize();
GenerateAndAddVector<TEST_DATA_T>(index, dim, bs + n, bs + n);
mock_thread_pool.thread_iteration();
size_t actual = index->getAllocationSize() - before;
// Flat index should be empty, hence the index size includes only hnsw size.
ASSERT_EQ(index->indexSize(), hnsw_index->indexSize());
ASSERT_EQ(index->indexCapacity(), hnsw_index->indexCapacity());
// We added n + 1 vectors
ASSERT_EQ(index->indexSize(), n + 1);
// We should have 2 blocks now
ASSERT_EQ(index->indexCapacity(), 2 * bs);
// We check that the actual size is within 1% of the estimation.
ASSERT_GE(estimation, actual * 0.99);
ASSERT_LE(estimation, actual * 1.01);
}
TYPED_TEST(HNSWTieredIndexTest, addVector) {
// Create TieredHNSW index instance with a mock queue.
size_t dim = 4;
bool isMulti = TypeParam::isMulti();
HNSWParams params = {.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.multi = isMulti};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
TieredIndexParams tiered_params = {.jobQueue = &mock_thread_pool.jobQ,
.jobQueueCtx = mock_thread_pool.ctx,
.submitCb = tieredIndexMock::submit_callback,
.flatBufferLimit = SIZE_MAX,
.primaryIndexParams = &hnsw_params};
auto *tiered_index = reinterpret_cast<TieredHNSWIndex<TEST_DATA_T, TEST_DIST_T> *>(
TieredFactory::NewIndex(&tiered_params));
// Get the allocator from the tiered index.
auto allocator = tiered_index->getAllocator();
// Set the created tiered index in the index external context.
mock_thread_pool.ctx->index_strong_ref.reset(tiered_index);
BFParams bf_params = {.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.multi = isMulti};
// Validate that memory upon creating the tiered index is as expected (no more than 2%
// above te expected, since in different platforms there are some minor additional
// allocations).
size_t expected_mem = TieredFactory::EstimateInitialSize(&tiered_params);
ASSERT_LE(expected_mem, tiered_index->getAllocationSize());
ASSERT_GE(expected_mem * 1.02, tiered_index->getAllocationSize());
// 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->backendIndex->indexSize(), 0);
ASSERT_EQ(tiered_index->frontendIndex->indexSize(), 1);
ASSERT_EQ(tiered_index->frontendIndex->indexCapacity(), DEFAULT_BLOCK_SIZE);
ASSERT_EQ(tiered_index->indexCapacity(), DEFAULT_BLOCK_SIZE);
ASSERT_EQ(tiered_index->frontendIndex->getDistanceFrom_Unsafe(vec_label, vector), 0);
// Validate that the job was created properly
ASSERT_EQ(tiered_index->labelToInsertJobs.at(vec_label).size(), 1);
ASSERT_EQ(tiered_index->labelToInsertJobs.at(vec_label)[0]->label, vec_label);
ASSERT_EQ(tiered_index->labelToInsertJobs.at(vec_label)[0]->id, 0);
// 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 memory that was allocated in the labelToInsertJobs map (approx.)
expected_mem +=
sizeof(
vecsim_stl::unordered_map<labelType, vecsim_stl::vector<HNSWInsertJob *>>::value_type) +
sizeof(void *) + sizeof(size_t);
// Account for the inner buffer of the std::vector<HNSWInsertJob *> in the map.
expected_mem += sizeof(void *) + sizeof(size_t);
// Account for the insert job that was created.
expected_mem += sizeof(HNSWInsertJob) + sizeof(size_t);
ASSERT_GE(expected_mem * 1.02, tiered_index->getAllocationSize());
ASSERT_LE(expected_mem, tiered_index->getAllocationSize());
if (isMulti) {
// Add another vector under the same label (create another insert job)
VecSimIndex_AddVector(tiered_index, vector, vec_label);
ASSERT_EQ(tiered_index->indexSize(), 2);
ASSERT_EQ(tiered_index->indexLabelCount(), 1);
ASSERT_EQ(tiered_index->backendIndex->indexSize(), 0);
ASSERT_EQ(tiered_index->frontendIndex->indexSize(), 2);
// Validate that the second job was created properly
ASSERT_EQ(tiered_index->labelToInsertJobs.at(vec_label).size(), 2);
ASSERT_EQ(tiered_index->labelToInsertJobs.at(vec_label)[1]->label, vec_label);
ASSERT_EQ(tiered_index->labelToInsertJobs.at(vec_label)[1]->id, 1);
}
}
TYPED_TEST(HNSWTieredIndexTest, manageIndexOwnership) {
// Create TieredHNSW index instance with a mock queue.
size_t dim = 4;
HNSWParams params = {.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.multi = TypeParam::isMulti()};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
// Get the allocator from the tiered index.
auto allocator = tiered_index->getAllocator();
EXPECT_EQ(mock_thread_pool.ctx->index_strong_ref.use_count(), 1);
size_t initial_mem = allocator->getAllocationSize();
// Create a dummy job callback that insert one vector to the underline HNSW index.
auto dummy_job = [](AsyncJob *job) {
auto *my_index = reinterpret_cast<TieredHNSWIndex<TEST_DATA_T, TEST_DIST_T> *>(job->index);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
size_t dim = 4;
TEST_DATA_T vector[dim];
GenerateVector<TEST_DATA_T>(vector, dim);
my_index->backendIndex->addVector(vector, my_index->backendIndex->indexSize());
};
std::atomic_int successful_executions(0);
auto job1 =
new (allocator) AsyncJob(allocator, HNSW_INSERT_VECTOR_JOB, dummy_job, tiered_index);
auto job2 =
new (allocator) AsyncJob(allocator, HNSW_INSERT_VECTOR_JOB, dummy_job, tiered_index);
// Wrap this job with an array and submit the jobs to the queue.
tiered_index->submitSingleJob(job1);
tiered_index->submitSingleJob(job2);
ASSERT_EQ(mock_thread_pool.jobQ.size(), 2);
// Execute the job from the queue asynchronously, delete the index in the meantime.
auto run_fn = [&successful_executions, &mock_thread_pool]() {
// Create a temporary strong reference of the index from the weak reference that the
// job holds, to ensure that the index is not deleted while the job is running.
if (auto temp_ref = mock_thread_pool.jobQ.front().index_weak_ref.lock()) {
// At this point we wish to validate that we have both the index strong ref (stored
// in index_ctx) and the weak ref owned by the job (that we currently promoted).
EXPECT_EQ(mock_thread_pool.jobQ.front().index_weak_ref.use_count(), 2);
mock_thread_pool.jobQ.front().job->Execute(mock_thread_pool.jobQ.front().job);
successful_executions++;
}
mock_thread_pool.jobQ.kick();
};
std::thread t1(run_fn);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// Delete the index while the job is still running, to ensure that the weak ref protects
// the index.
mock_thread_pool.reset_ctx();
EXPECT_EQ(mock_thread_pool.jobQ.front().index_weak_ref.use_count(), 1);
t1.join();
// Expect that the first job will succeed.
ASSERT_EQ(successful_executions, 1);
// The second job should not run, since the weak reference is not supposed to become a
// strong references now.
ASSERT_EQ(mock_thread_pool.jobQ.size(), 1);
ASSERT_EQ(mock_thread_pool.jobQ.front().index_weak_ref.use_count(), 0);
std::thread t2(run_fn);
t2.join();
// Expect that the second job is ot successful.
ASSERT_EQ(successful_executions, 1);
}
TYPED_TEST(HNSWTieredIndexTest, insertJob) {
// Create TieredHNSW index instance with a mock queue.
size_t dim = 4;
HNSWParams params = {.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.multi = TypeParam::isMulti()};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
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->frontendIndex->indexSize(), 1);
// Execute the insert job manually (in a synchronous manner).
ASSERT_EQ(mock_thread_pool.jobQ.size(), 1);
auto *insertion_job = reinterpret_cast<HNSWInsertJob *>(mock_thread_pool.jobQ.front().job);
ASSERT_EQ(insertion_job->label, vec_label);
ASSERT_EQ(insertion_job->id, 0);
ASSERT_EQ(insertion_job->jobType, HNSW_INSERT_VECTOR_JOB);
mock_thread_pool.thread_iteration();
ASSERT_EQ(tiered_index->indexSize(), 1);
ASSERT_EQ(tiered_index->frontendIndex->indexSize(), 0);
ASSERT_EQ(tiered_index->backendIndex->indexSize(), 1);
// HNSW index should have allocated a single block, while flat index should remove the
// block.
ASSERT_EQ(tiered_index->backendIndex->indexCapacity(), DEFAULT_BLOCK_SIZE);
ASSERT_EQ(tiered_index->indexCapacity(), DEFAULT_BLOCK_SIZE);
ASSERT_EQ(tiered_index->frontendIndex->indexCapacity(), 0);
ASSERT_EQ(tiered_index->backendIndex->getDistanceFrom_Unsafe(vec_label, vector), 0);
// After the execution, the job should be removed from the labelToInsertJobs mapping.
ASSERT_EQ(tiered_index->labelToInsertJobs.size(), 0);
}
TYPED_TEST(HNSWTieredIndexTestBasic, insertJobAsync) {
// Create TieredHNSW index instance with a mock queue.
size_t dim = 4;
size_t n = 5000;
HNSWParams params = {
.type = TypeParam::get_index_type(), .dim = dim, .metric = VecSimMetric_L2, .multi = false};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
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);
}
mock_thread_pool.thread_pool_join();
ASSERT_EQ(tiered_index->indexSize(), n);
ASSERT_EQ(tiered_index->backendIndex->indexSize(), n);
ASSERT_EQ(tiered_index->frontendIndex->indexSize(), 0);
ASSERT_EQ(tiered_index->labelToInsertJobs.size(), 0);
ASSERT_EQ(mock_thread_pool.jobQ.size(), 0);
// Verify that the vectors were inserted to HNSW as expected
for (size_t i = 0; i < n; i++) {
TEST_DATA_T expected_vector[dim];
GenerateVector<TEST_DATA_T>(expected_vector, dim, i);
ASSERT_EQ(tiered_index->backendIndex->getDistanceFrom_Unsafe(i, expected_vector), 0);
}
}
TYPED_TEST(HNSWTieredIndexTestBasic, insertJobAsyncMulti) {
// Create TieredHNSW index instance with a mock queue.
size_t dim = 4;
size_t n = 5000;
HNSWParams params = {
.type = TypeParam::get_index_type(), .dim = dim, .metric = VecSimMetric_L2, .multi = true};
VecSimParams hnsw_params = CreateParams(params);
size_t per_label = 5;
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
auto allocator = tiered_index->getAllocator();
// Launch the BG threads loop that takes jobs from the queue and executes them.
mock_thread_pool.init_threads();
// Create and insert vectors, store them in this continuous array.
TEST_DATA_T vectors[n * dim];
for (size_t i = 0; i < n / per_label; i++) {
for (size_t j = 0; j < per_label; j++) {
GenerateVector<TEST_DATA_T>(vectors + i * dim * per_label + j * dim, dim,
i * per_label + j);
tiered_index->addVector(vectors + i * dim * per_label + j * dim, i);
}
}
mock_thread_pool.thread_pool_join();
EXPECT_EQ(tiered_index->backendIndex->indexSize(), n);
EXPECT_EQ(tiered_index->indexLabelCount(), n / per_label);
EXPECT_EQ(tiered_index->frontendIndex->indexSize(), 0);
EXPECT_EQ(tiered_index->labelToInsertJobs.size(), 0);
EXPECT_EQ(mock_thread_pool.jobQ.size(), 0);
// Verify that the vectors were inserted to HNSW as expected
for (size_t i = 0; i < n / per_label; i++) {
for (size_t j = 0; j < per_label; j++) {
// The distance from every vector that is stored under the label i should be zero
EXPECT_EQ(tiered_index->backendIndex->getDistanceFrom_Unsafe(
i, vectors + i * per_label * dim + j * dim),
0);
}
}
}
TYPED_TEST(HNSWTieredIndexTestBasic, KNNSearch) {
size_t dim = 4;
size_t k = 10;
size_t n = k * 3;
// Create TieredHNSW index instance with a mock queue.
HNSWParams params = {
.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
size_t cur_memory_usage;
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
auto allocator = tiered_index->getAllocator();
EXPECT_EQ(mock_thread_pool.ctx->index_strong_ref.use_count(), 1);
auto hnsw_index = tiered_index->backendIndex;
auto flat_index = tiered_index->frontendIndex;
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>(hnsw_index, dim, i, i);
}
ASSERT_EQ(tiered_index->indexSize(), n / 2);
ASSERT_EQ(tiered_index->indexSize(), hnsw_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(), hnsw_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>(hnsw_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, n, ver_res_0);
runTopKSearchTest(tiered_index, query_n, k, n, 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(hnsw_index, i);
}
ASSERT_EQ(flat_index->indexSize(), n * 2 / 3);
ASSERT_EQ(hnsw_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(hnsw_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(hnsw_index, i);
GenerateAndAddVector<TEST_DATA_T>(flat_index, dim, i, i);
}
ASSERT_EQ(flat_index->indexSize(), n * 2 / 3);
ASSERT_EQ(hnsw_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 HNSW index so there will be a reason to query it.
GenerateAndAddVector<TEST_DATA_T>(hnsw_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 HNSW 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(HNSWTieredIndexTest, parallelSearch) {
size_t dim = 4;
size_t k = 10;
size_t n = 2000;
bool isMulti = TypeParam::isMulti();
// Create TieredHNSW index instance with a mock queue.
HNSWParams params = {
.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.multi = isMulti,
.efRuntime = n,
};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
auto allocator = tiered_index->getAllocator();
EXPECT_EQ(mock_thread_pool.ctx->index_strong_ref.use_count(), 1);
std::atomic_int successful_searches(0);
auto parallel_knn_search = [](AsyncJob *job) {
auto *search_job = reinterpret_cast<tieredIndexMock::SearchJobMock *>(job);
size_t k = search_job->k;
size_t dim = search_job->dim;
auto query = search_job->query;
auto verify_res = [&](size_t id, double score, size_t res_index) {
TEST_DATA_T element = *(TEST_DATA_T *)query;
ASSERT_EQ(std::abs(id - element), (res_index + 1) / 2);
ASSERT_EQ(score, dim * (id - element) * (id - element));
};
runTopKSearchTest(job->index, query, k, verify_res);
(*search_job->successful_searches)++;
delete job;
};
size_t per_label = isMulti ? 10 : 1;
size_t n_labels = n / per_label;
// Fill the job queue with insert and search jobs, while filling the flat index, before
// initializing the thread pool.
for (size_t i = 0; i < n; i++) {
// Insert a vector to the flat index and add a job to insert it to the main index.
GenerateAndAddVector<TEST_DATA_T>(tiered_index, dim, i % n_labels, i);
// Add a search job. Make sure the query element is between k and n - k.
auto query = (TEST_DATA_T *)allocator->allocate(dim * sizeof(TEST_DATA_T));
GenerateVector<TEST_DATA_T>(query, dim, (i % (n_labels - (2 * k))) + k);
auto search_job = new (allocator) tieredIndexMock::SearchJobMock(
allocator, parallel_knn_search, tiered_index, k, query, n, dim, &successful_searches);
tiered_index->submitSingleJob(search_job);
}
EXPECT_EQ(tiered_index->indexSize(), n);
EXPECT_EQ(tiered_index->indexLabelCount(), n_labels);
EXPECT_EQ(tiered_index->labelToInsertJobs.size(), n_labels);
for (auto &it : tiered_index->labelToInsertJobs) {
EXPECT_EQ(it.second.size(), per_label);
}
EXPECT_EQ(tiered_index->frontendIndex->indexSize(), n);
EXPECT_EQ(tiered_index->backendIndex->indexSize(), 0);
// Launch the BG threads loop that takes jobs from the queue and executes them.
// All the vectors are already in the tiered index, so we expect to find the expected
// results from the get-go.
mock_thread_pool.init_threads();
mock_thread_pool.thread_pool_join();
EXPECT_EQ(tiered_index->backendIndex->indexSize(), n);
EXPECT_EQ(tiered_index->backendIndex->indexLabelCount(), n_labels);
EXPECT_EQ(tiered_index->frontendIndex->indexSize(), 0);
EXPECT_EQ(tiered_index->labelToInsertJobs.size(), 0);
EXPECT_EQ(successful_searches, n);
EXPECT_EQ(mock_thread_pool.jobQ.size(), 0);
}
TYPED_TEST(HNSWTieredIndexTest, parallelInsertSearch) {
size_t dim = 4;
size_t k = 10;
size_t n = 3000;
size_t block_size = n / 100;
bool isMulti = TypeParam::isMulti();
// Create TieredHNSW index instance with a mock queue.
size_t n_labels = isMulti ? n / 25 : n;
HNSWParams params = {
.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.multi = isMulti,
.blockSize = block_size,
};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
auto allocator = tiered_index->getAllocator();
EXPECT_EQ(mock_thread_pool.ctx->index_strong_ref.use_count(), 1);
// Launch the BG threads loop that takes jobs from the queue and executes them.
// Save the number fo tasks done by thread i in the i-th entry.
std::vector<size_t> completed_tasks(mock_thread_pool.thread_pool_size, 0);
mock_thread_pool.init_threads();
std::atomic_int successful_searches(0);
auto parallel_knn_search = [](AsyncJob *job) {
auto *search_job = reinterpret_cast<tieredIndexMock::SearchJobMock *>(job);
size_t k = search_job->k;
auto query = search_job->query;
// In this test we don't care about the results, just that the search doesn't crash
// and returns the correct number of valid results.
auto verify_res = [&](size_t id, double score, size_t res_index) {};
runTopKSearchTest(job->index, query, k, verify_res);
(*search_job->successful_searches)++;
delete job;
};
// Insert vectors in parallel to search.
for (size_t i = 0; i < n; i++) {
GenerateAndAddVector<TEST_DATA_T>(tiered_index, dim, i % n_labels, i);
auto query = (TEST_DATA_T *)allocator->allocate(dim * sizeof(TEST_DATA_T));
GenerateVector<TEST_DATA_T>(query, dim, (TEST_DATA_T)n / 4 + (i % 1000) * M_PI);
auto search_job = new (allocator) tieredIndexMock::SearchJobMock(
allocator, parallel_knn_search, tiered_index, k, query, n, dim, &successful_searches);
tiered_index->submitSingleJob(search_job);
}
mock_thread_pool.thread_pool_join();
EXPECT_EQ(successful_searches, n);
EXPECT_EQ(tiered_index->backendIndex->indexSize(), n);
EXPECT_EQ(tiered_index->backendIndex->indexLabelCount(), n_labels);
EXPECT_EQ(tiered_index->frontendIndex->indexSize(), 0);
EXPECT_EQ(tiered_index->labelToInsertJobs.size(), 0);
EXPECT_EQ(mock_thread_pool.jobQ.size(), 0);
}
TYPED_TEST(HNSWTieredIndexTestBasic, MergeMulti) {
size_t dim = 4;
// Create TieredHNSW index instance with a mock queue.
HNSWParams params = {
.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.multi = true,
};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
auto allocator = tiered_index->getAllocator();
auto hnsw_index = tiered_index->backendIndex;
auto flat_index = tiered_index->frontendIndex;
// Insert vectors with label 0 to HNSW only.
GenerateAndAddVector<TEST_DATA_T>(hnsw_index, dim, 0, 0);
GenerateAndAddVector<TEST_DATA_T>(hnsw_index, dim, 0, 1);
GenerateAndAddVector<TEST_DATA_T>(hnsw_index, dim, 0, 2);
// Insert vectors with label 1 to flat buffer only.
GenerateAndAddVector<TEST_DATA_T>(flat_index, dim, 1, 0);
GenerateAndAddVector<TEST_DATA_T>(flat_index, dim, 1, 1);
GenerateAndAddVector<TEST_DATA_T>(flat_index, dim, 1, 2);
// Insert DIFFERENT vectors with label 2 to both HNSW and flat buffer.
GenerateAndAddVector<TEST_DATA_T>(hnsw_index, dim, 2, 0);
GenerateAndAddVector<TEST_DATA_T>(flat_index, dim, 2, 1);
TEST_DATA_T query[dim];
GenerateVector<TEST_DATA_T>(query, dim, 0);
// Search in the tiered index for more vectors than it has. Merging the results from the two
// indexes should result in a list of unique vectors, even if the scores of the duplicates are
// different.
runTopKSearchTest(tiered_index, query, 5, 3, [](size_t _, double __, size_t ___) {});
}
TYPED_TEST(HNSWTieredIndexTest, deleteFromHNSWBasic) {
// Create TieredHNSW index instance with a mock queue.
size_t dim = 4;
bool isMulti = TypeParam::isMulti();
HNSWParams params = {.type = TypeParam::get_index_type(),
.dim = dim,
.metric = VecSimMetric_L2,
.multi = isMulti};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
auto allocator = tiered_index->getAllocator();
// Delete a non existing label.
ASSERT_EQ(tiered_index->deleteLabelFromHNSW(0), 0);
ASSERT_EQ(mock_thread_pool.jobQ.size(), 0);
// Insert one vector to HNSW and then delete it (it should have no neighbors to repair).
GenerateAndAddVector<TEST_DATA_T>(tiered_index->backendIndex, dim, 0);
ASSERT_EQ(tiered_index->deleteLabelFromHNSW(0), 1);
ASSERT_EQ(mock_thread_pool.jobQ.size(), 0);
// Add another vector and remove it. Since the other vector in the index has marked deleted,
// this vector should have no neighbors, and again, no neighbors to repair.
GenerateAndAddVector<TEST_DATA_T>(tiered_index->backendIndex, dim, 1, 1);
ASSERT_EQ(tiered_index->deleteLabelFromHNSW(1), 1);
ASSERT_EQ(mock_thread_pool.jobQ.size(), 0);
// Add two vectors and delete one, expect that at backendIndex one repair job will be created.
GenerateAndAddVector<TEST_DATA_T>(tiered_index->backendIndex, dim, 2, 2);
GenerateAndAddVector<TEST_DATA_T>(tiered_index->backendIndex, dim, 3, 3);
ASSERT_EQ(tiered_index->deleteLabelFromHNSW(3), 1);
// The first job should be a repair job of the first inserted non-deleted node id (2)
// in level 0.
ASSERT_EQ(mock_thread_pool.jobQ.size(), 1);
ASSERT_EQ(mock_thread_pool.jobQ.front().job->jobType, HNSW_REPAIR_NODE_CONNECTIONS_JOB);
ASSERT_EQ(((HNSWRepairJob *)(mock_thread_pool.jobQ.front().job))->node_id, 2);
ASSERT_EQ(((HNSWRepairJob *)(mock_thread_pool.jobQ.front().job))->level, 0);
ASSERT_EQ(tiered_index->idToRepairJobs.size(), 1);
ASSERT_GE(tiered_index->idToRepairJobs.at(2).size(), 1);
ASSERT_EQ(tiered_index->idToRepairJobs.at(2)[0]->associatedSwapJobs.size(), 1);
ASSERT_EQ(tiered_index->idToRepairJobs.at(2)[0]->associatedSwapJobs[0]->deleted_id, 3);
ASSERT_EQ(tiered_index->indexSize(), 4);
ASSERT_EQ(tiered_index->getHNSWIndex()->getNumMarkedDeleted(), 3);
ASSERT_EQ(tiered_index->statisticInfo().numberOfMarkedDeleted, 3);
ASSERT_EQ(tiered_index->idToSwapJob.size(), 3);
}
TYPED_TEST(HNSWTieredIndexTestBasic, deleteFromHNSWMulti) {
// Create TieredHNSW index instance with a mock queue.
size_t dim = 4;
HNSWParams params = {
.type = TypeParam::get_index_type(), .dim = dim, .metric = VecSimMetric_L2, .multi = true};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
auto allocator = tiered_index->getAllocator();
// Add two vectors and delete one, expect that at least one repair job will be created.
GenerateAndAddVector<TEST_DATA_T>(tiered_index->backendIndex, dim, 0, 0);
GenerateAndAddVector<TEST_DATA_T>(tiered_index->backendIndex, dim, 1, 1);
ASSERT_EQ(tiered_index->deleteLabelFromHNSW(0), 1);
ASSERT_EQ(tiered_index->idToRepairJobs.size(), 1);
ASSERT_EQ(tiered_index->idToRepairJobs.at(1).size(), 1);
ASSERT_EQ(tiered_index->idToRepairJobs.at(1)[0]->associatedSwapJobs.size(), 1);
ASSERT_EQ(tiered_index->idToRepairJobs.at(1)[0]->associatedSwapJobs[0]->deleted_id, 0);
ASSERT_EQ(((HNSWRepairJob *)(mock_thread_pool.jobQ.front().job))->node_id, 1);
ASSERT_EQ(((HNSWRepairJob *)(mock_thread_pool.jobQ.front().job))->level, 0);
mock_thread_pool.jobQ.pop();
// Insert another vector under the label (1) that has not been deleted.
GenerateAndAddVector<TEST_DATA_T>(tiered_index->backendIndex, dim, 1, 2);
// Expect to see both ids stored under this label being deleted (1 and 2), and have both
// ids need repair (as the connection between the two vectors is mutual). However, 1 has
// also an outgoing edge to his other (deleted) neighbor (0), so there will be no new
// repair job created for 1, since the previous repair job is expected to have both 0 and 2 in
// its associated swap jobs. Also, there is an edge 0->1 whose going to be repaired as well.
ASSERT_EQ(tiered_index->deleteLabelFromHNSW(1), 2);
ASSERT_EQ(mock_thread_pool.jobQ.size(), 2);
ASSERT_EQ(((HNSWRepairJob *)(mock_thread_pool.jobQ.front().job))->node_id, 0);
ASSERT_EQ(((HNSWRepairJob *)(mock_thread_pool.jobQ.front().job))->level, 0);
mock_thread_pool.jobQ.pop();
ASSERT_EQ(((HNSWRepairJob *)(mock_thread_pool.jobQ.front().job))->node_id, 2);
ASSERT_EQ(((HNSWRepairJob *)(mock_thread_pool.jobQ.front().job))->level, 0);
mock_thread_pool.jobQ.pop();
// No new job for deleting 1->2 edge, just another associated swap job for the existing repair
// job of 1 (in addition to 0, we have 2).
ASSERT_EQ(tiered_index->idToRepairJobs.size(), 3);
ASSERT_EQ(tiered_index->idToRepairJobs.at(1).size(), 1);
ASSERT_EQ(tiered_index->idToRepairJobs.at(1)[0]->associatedSwapJobs.size(), 2);
ASSERT_EQ(tiered_index->idToRepairJobs.at(1)[0]->associatedSwapJobs[1]->deleted_id, 2);
ASSERT_EQ(tiered_index->idToRepairJobs.at(0).size(), 1);
ASSERT_EQ(tiered_index->idToRepairJobs.at(0)[0]->associatedSwapJobs.size(), 1);
ASSERT_EQ(tiered_index->idToRepairJobs.at(0)[0]->associatedSwapJobs[0]->deleted_id, 1);
ASSERT_EQ(tiered_index->idToRepairJobs.at(2).size(), 1);
ASSERT_EQ(tiered_index->idToRepairJobs.at(2)[0]->associatedSwapJobs.size(), 1);
ASSERT_EQ(tiered_index->idToRepairJobs.at(2)[0]->associatedSwapJobs[0]->deleted_id, 1);
ASSERT_EQ(tiered_index->idToSwapJob.size(), 3);
}
TYPED_TEST(HNSWTieredIndexTestBasic, deleteFromHNSWMultiLevels) {
// Create TieredHNSW index instance with a mock queue.
size_t dim = 4;
HNSWParams params = {
.type = TypeParam::get_index_type(), .dim = dim, .metric = VecSimMetric_L2, .multi = false};
VecSimParams hnsw_params = CreateParams(params);
auto mock_thread_pool = tieredIndexMock();
auto *tiered_index = this->CreateTieredHNSWIndex(hnsw_params, mock_thread_pool);
auto allocator = tiered_index->getAllocator();
// Test that repair jobs are created for multiple levels.
size_t num_elements_with_multiple_levels = 0;
int vec_id = -1;
do {
vec_id++;
GenerateAndAddVector<TEST_DATA_T>(tiered_index->backendIndex, dim, vec_id, vec_id);
if (tiered_index->getHNSWIndex()->getGraphDataByInternalId(vec_id)->toplevel > 0) {
num_elements_with_multiple_levels++;
}
} while (num_elements_with_multiple_levels < 2);
// Delete the last inserted vector, which is in level 1.
ASSERT_EQ(tiered_index->deleteLabelFromHNSW(vec_id), 1);
ASSERT_EQ(tiered_index->getHNSWIndex()->getGraphDataByInternalId(vec_id)->toplevel, 1);
// This should be an array of length 1.
auto &level_one = tiered_index->getHNSWIndex()->getElementLevelData(vec_id, 1);
ASSERT_EQ(level_one.numLinks, 1);
size_t num_repair_jobs = mock_thread_pool.jobQ.size();
// There should be at least two nodes to repair, the neighbors of next_id in levels 0 and 1
ASSERT_GE(num_repair_jobs, 2);
while (mock_thread_pool.jobQ.size() > 1) {
// First we should have jobs for repairing nodes in level 0.
ASSERT_EQ(((HNSWRepairJob *)(mock_thread_pool.jobQ.front().job))->level, 0);
mock_thread_pool.jobQ.pop();
}