Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathtest_read_index_deserialize.cpp
More file actions
4487 lines (3956 loc) · 174 KB
/
Copy pathtest_read_index_deserialize.cpp
File metadata and controls
4487 lines (3956 loc) · 174 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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gtest/gtest.h>
#include <cstdint>
#include <cstring>
#include <numeric>
#include <random>
#include <vector>
#include <faiss/Index.h>
#include <faiss/Index2Layer.h>
#include <faiss/IndexAdditiveQuantizer.h>
#include <faiss/IndexAdditiveQuantizerFastScan.h>
#include <faiss/IndexBinary.h>
#include <faiss/IndexBinaryHNSW.h>
#include <faiss/IndexBinaryIVF.h>
#include <faiss/IndexFlat.h>
#include <faiss/IndexHNSW.h>
#include <faiss/IndexIDMap.h>
#include <faiss/IndexIVFAdditiveQuantizer.h>
#include <faiss/IndexIVFAdditiveQuantizerFastScan.h>
#include <faiss/IndexIVFFlat.h>
#include <faiss/IndexIVFIndependentQuantizer.h>
#include <faiss/IndexIVFPQ.h>
#include <faiss/IndexIVFPQR.h>
#include <faiss/IndexRaBitQFastScan.h>
#include <faiss/IndexScalarQuantizer.h>
#include <faiss/VectorTransform.h>
#include <faiss/impl/FaissException.h>
#include <faiss/impl/ScalarQuantizer.h>
#include <faiss/impl/io.h>
#include <faiss/index_io.h>
#include <faiss/invlists/InvertedLists.h>
#include <faiss/utils/hamming.h>
using namespace faiss;
/// Helper: append a scalar value to the buffer in little-endian format,
/// matching WRITE1.
template <typename T>
static void push_val(std::vector<uint8_t>& buf, T val) {
const auto* p = reinterpret_cast<const uint8_t*>(&val);
buf.insert(buf.end(), p, p + sizeof(T));
}
/// Helper: append a WRITEVECTOR-formatted vector (size_t length prefix
/// followed by raw element data).
template <typename T>
static void push_vector(std::vector<uint8_t>& buf, const std::vector<T>& vec) {
push_val<size_t>(buf, vec.size());
const auto* p = reinterpret_cast<const uint8_t*>(vec.data());
buf.insert(buf.end(), p, p + vec.size() * sizeof(T));
}
/// Helper: append a fourcc string as a uint32_t.
static void push_fourcc(std::vector<uint8_t>& buf, const char s[4]) {
const auto* x = reinterpret_cast<const unsigned char*>(s);
uint32_t h = x[0] | (x[1] << 8) | (x[2] << 16) | (x[3] << 24);
push_val<uint32_t>(buf, h);
}
/// Helper: append write_index_header fields.
static void push_index_header(
std::vector<uint8_t>& buf,
int d,
int64_t ntotal,
bool is_trained = true,
int metric_type = 1 /* L2 */) {
push_val<int>(buf, d);
push_val<int64_t>(buf, ntotal);
int64_t dummy = 1 << 20;
push_val<int64_t>(buf, dummy);
push_val<int64_t>(buf, dummy);
push_val<bool>(buf, is_trained);
push_val<int>(buf, metric_type);
}
/// Helper: append write_ProductQuantizer fields (d, M, nbits, centroids vec).
static void push_pq(
std::vector<uint8_t>& buf,
size_t d,
size_t M,
size_t nbits,
const std::vector<float>& centroids = {}) {
push_val<size_t>(buf, d);
push_val<size_t>(buf, M);
push_val<size_t>(buf, nbits);
push_vector<float>(buf, centroids);
}
/// Try to read a VectorTransform from the given buffer and expect a
/// FaissException whose message contains the given substring.
static void expect_vt_read_throws_with(
const std::vector<uint8_t>& data,
const std::string& expected_substr) {
VectorIOReader reader;
reader.data = data;
try {
read_VectorTransform_up(&reader);
FAIL() << "expected FaissException";
} catch (const FaissException& e) {
EXPECT_NE(
std::string(e.what()).find(expected_substr), std::string::npos)
<< "expected '" << expected_substr << "' in: " << e.what();
}
}
/// Try to read a float index from the given buffer and expect a FaissException.
static void expect_read_throws(const std::vector<uint8_t>& data) {
VectorIOReader reader;
reader.data = data;
EXPECT_THROW(read_index_up(&reader), FaissException);
}
/// Try to read a float index and expect a FaissException whose message
/// contains the given substring.
static void expect_read_throws_with(
const std::vector<uint8_t>& data,
const std::string& expected_substr) {
VectorIOReader reader;
reader.data = data;
try {
read_index_up(&reader);
FAIL() << "expected FaissException";
} catch (const FaissException& e) {
EXPECT_NE(
std::string(e.what()).find(expected_substr), std::string::npos)
<< "expected '" << expected_substr << "' in: " << e.what();
}
}
// -----------------------------------------------------------------------
// Test: ProductQuantizer with M=0 causes divide-by-zero in
// set_derived_values(). The fix validates M > 0 in read_ProductQuantizer
// before calling set_derived_values().
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, PQWithMZeroDivideByZero) {
// Build a minimal MultiIndexQuantizer ("Imiq") payload with M=0.
// Format: fourcc("Imiq") + index_header + PQ(d=4, M=0, nbits=8, [])
std::vector<uint8_t> buf;
push_fourcc(buf, "Imiq");
push_index_header(buf, /*d=*/4, /*ntotal=*/0);
push_pq(buf, /*d=*/4, /*M=*/0, /*nbits=*/8);
expect_read_throws(buf);
}
// -----------------------------------------------------------------------
// Test: a non-{0,1} byte at a bool field position must be rejected as
// FaissException rather than silently producing an invalid bool value.
// Reading a non-canonical byte directly into a bool is UB and trips
// UBSan's invalid-bool-load check; the READ1_BOOL helper routes every
// bool READ1 through a value check and throws on anything outside {0,1}.
// is_trained, read inside read_index_header, exercises the helper from
// the most common deserialization path.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, IndexHeaderInvalidBoolEncodingIsTrained) {
// Minimal IndexFlatL2 ("IxF2") with ntotal=0 - read_index_header is
// the first thing the deserializer consumes for this fourcc.
std::vector<uint8_t> buf;
push_fourcc(buf, "IxF2");
push_index_header(buf, /*d=*/4, /*ntotal=*/0);
// is_trained sits at offset 4 (fourcc) + 4 (d) + 8 (ntotal) +
// 8 (dummy) + 8 (dummy) = 32. push_index_header writes 0x01 there;
// overwrite with a non-canonical bool byte.
constexpr size_t is_trained_offset = 32;
ASSERT_EQ(buf[is_trained_offset], uint8_t{1});
buf[is_trained_offset] = 0x02;
expect_read_throws_with(buf, "invalid bool encoding");
}
// -----------------------------------------------------------------------
// Test: AdditiveQuantizer with nbits.size() != M causes out-of-bounds
// access on the nbits vector in set_derived_values(). The fix validates
// nbits.size() == M in read_AdditiveQuantizer.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, AdditiveQuantizerNbitsSizeMismatch) {
// Build a minimal IndexProductResidualQuantizerFastScan ("IPRf") payload
// whose AdditiveQuantizer has M=10 but nbits vector has only 1 element.
//
// "IPRf" format:
// fourcc + index_header + read_AdditiveQuantizer(d, M, nbits,
// is_trained, codebooks, search_type, norm_min, norm_max)
// + set_derived_values()
//
// We must provide enough data to reach set_derived_values() so the
// OOB access on nbits[i] actually triggers (rather than an earlier
// read-error throwing first).
std::vector<uint8_t> buf;
push_fourcc(buf, "IPRf");
push_index_header(buf, /*d=*/4, /*ntotal=*/0);
// read_AdditiveQuantizer fields:
push_val<size_t>(buf, 4); // d
push_val<size_t>(buf, 10); // M = 10
// nbits vector with only 1 element (should be 10 to match M)
push_vector<size_t>(buf, {8});
// is_trained
push_val<bool>(buf, true);
// codebooks (empty vector is fine)
push_vector<float>(buf, {});
// search_type (ST_decompress = 0)
push_val<int>(buf, 0);
// norm_min, norm_max
push_val<float>(buf, 0.0f);
push_val<float>(buf, 1.0f);
// After these reads, set_derived_values() will access nbits[1..9]
// which are out of bounds.
expect_read_throws_with(buf, "nbits size");
}
// -----------------------------------------------------------------------
// Test: ResidualQuantizer (old format) with nbits.size() != M also causes
// out-of-bounds access. Uses the "IxRQ" fourcc path.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, ResidualQuantizerOldNbitsSizeMismatch) {
// "IxRQ" format: fourcc + index_header + read_ResidualQuantizer_old(...)
// read_ResidualQuantizer_old reads: d, M, nbits_vec, is_trained, ...
std::vector<uint8_t> buf;
push_fourcc(buf, "IxRQ");
push_index_header(buf, /*d=*/4, /*ntotal=*/0);
// ResidualQuantizer_old fields:
push_val<size_t>(buf, 4); // d
push_val<size_t>(buf, 5); // M = 5
// nbits vector with only 2 elements (should be 5 to match M)
push_vector<size_t>(buf, {8, 8});
expect_read_throws_with(buf, "nbits size");
}
// -----------------------------------------------------------------------
// Test: ProductQuantizer with d * ksub overflow in centroids allocation.
// The fix uses mul_no_overflow to detect the overflow.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, PQCentroidsOverflow) {
// Build a minimal "Imiq" with d very large and nbits=24 so that
// d * (1 << 24) overflows size_t.
std::vector<uint8_t> buf;
push_fourcc(buf, "Imiq");
// Use a huge d that, when multiplied by ksub=2^24, overflows
size_t huge_d = (size_t)1 << 48;
push_index_header(buf, /*d=*/(int)huge_d, /*ntotal=*/0);
// M must divide d; set M=1 so d % M == 0
push_pq(buf, /*d=*/huge_d, /*M=*/1, /*nbits=*/24);
expect_read_throws(buf);
}
// -----------------------------------------------------------------------
// Test: READVECTOR rejects a vector whose total byte size exceeds the
// configurable deserialization byte limit. Uses a LinearTransform
// ("LTra") whose A vector is read via READVECTOR.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, READVECTORByteLimit) {
// Build a "LTra" (LinearTransform) payload.
// Format: fourcc + have_bias + READVECTOR(A) + READVECTOR(b)
// + d_in + d_out + is_trained
// A contains 1024 floats = 4096 bytes.
// READVECTOR check: size < limit / sizeof(float)
const size_t old_limit = get_deserialization_vector_byte_limit();
const int d_in = 32;
const int d_out = 32;
const size_t n_elements = d_in * d_out; // 1024
std::vector<uint8_t> buf;
push_fourcc(buf, "LTra");
push_val<bool>(buf, false); // have_bias
std::vector<float> A(n_elements, 0.0f);
push_vector<float>(buf, A);
// b vector: empty (no bias)
push_vector<float>(buf, {});
// Common VectorTransform fields
push_val<int>(buf, d_in);
push_val<int>(buf, d_out);
push_val<bool>(buf, true); // is_trained
// Exactly at the boundary: limit = n_elements * sizeof(float).
// Check is strict less-than, so this should be rejected.
set_deserialization_vector_byte_limit(n_elements * sizeof(float));
{
VectorIOReader reader;
reader.data = buf;
EXPECT_THROW(read_VectorTransform_up(&reader), FaissException);
}
// One element above the boundary: limit = (n_elements + 1) * sizeof(float).
// Now n_elements < limit / sizeof(float) = n_elements + 1, so it passes.
set_deserialization_vector_byte_limit((n_elements + 1) * sizeof(float));
{
VectorIOReader reader;
reader.data = buf;
EXPECT_NO_THROW(read_VectorTransform_up(&reader));
}
set_deserialization_vector_byte_limit(old_limit);
}
// -----------------------------------------------------------------------
// Test: ProductQuantizer centroids allocation is rejected when it would
// exceed the configurable deserialization byte limit.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, PQCentroidsByteLimit) {
// d=8, M=1, nbits=8 → ksub=256, centroids = 8*256 = 2048 floats.
// PQ check: n < limit / sizeof(float), where n = d * ksub = 2048.
const size_t old_limit = get_deserialization_vector_byte_limit();
const size_t d = 8;
const size_t M = 1;
const size_t nbits = 8;
const size_t ksub = size_t{1} << nbits;
const size_t n_elements = d * ksub; // 2048
std::vector<float> centroids(n_elements, 0.0f);
std::vector<uint8_t> buf;
push_fourcc(buf, "Imiq");
push_index_header(buf, /*d=*/d, /*ntotal=*/0);
push_pq(buf, d, M, nbits, centroids);
// Exactly at the boundary: limit = n_elements * sizeof(float).
// Check is strict less-than, so this should be rejected.
set_deserialization_vector_byte_limit(n_elements * sizeof(float));
{
VectorIOReader reader;
reader.data = buf;
EXPECT_THROW(read_index_up(&reader), FaissException);
}
// One element above the boundary: limit = (n_elements + 1) * sizeof(float).
// Now n_elements < limit / sizeof(float) = n_elements + 1, so it passes.
set_deserialization_vector_byte_limit((n_elements + 1) * sizeof(float));
{
VectorIOReader reader;
reader.data = buf;
EXPECT_NO_THROW(read_index_up(&reader));
}
set_deserialization_vector_byte_limit(old_limit);
}
// -----------------------------------------------------------------------
// Test: IndexLattice with nsq=0 causes divide-by-zero in the
// constructor's member initializer list (dsq = d / nsq). The fix
// validates nsq > 0 in the deserialization path.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, IndexLatticeNsqZeroDivideByZero) {
// "IxLa" format: fourcc + d(int) + nsq(int) + scale_nbit(int)
// + r2(int) + index_header + READVECTOR(trained)
std::vector<uint8_t> buf;
push_fourcc(buf, "IxLa");
push_val<int>(buf, 16); // d
push_val<int>(buf, 0); // nsq = 0 -> divide by zero
push_val<int>(buf, 4); // scale_nbit
push_val<int>(buf, 14); // r2
expect_read_throws(buf);
}
// -----------------------------------------------------------------------
// Test: IndexLattice with d not divisible by nsq causes undefined
// behavior in the constructor. The fix validates d % nsq == 0 before
// construction.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, IndexLatticeDNotDivisibleByNsq) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IxLa");
push_val<int>(buf, 17); // d = 17 (not divisible by nsq=4)
push_val<int>(buf, 4); // nsq
push_val<int>(buf, 4); // scale_nbit
push_val<int>(buf, 14); // r2
expect_read_throws_with(buf, "divisible by nsq");
}
// -----------------------------------------------------------------------
// Test: IndexLattice with r2=0 causes heap-buffer-overflow in
// ZnSphereCodecRec constructor. The fix validates r2 > 0.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, IndexLatticeR2Zero) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IxLa");
push_val<int>(buf, 4); // d
push_val<int>(buf, 1); // nsq
push_val<int>(buf, 4); // scale_nbit
push_val<int>(buf, 0); // r2 = 0 -> heap-buffer-overflow
expect_read_throws_with(buf, "r2");
}
// -----------------------------------------------------------------------
// Test: IndexLattice with d/nsq not a power of 2 >= 2 causes
// heap-buffer-overflow in ZnSphereCodecRec constructor. The fix
// validates that d/nsq is a power of 2 and >= 2.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, IndexLatticeDsqNotPowerOf2) {
// d=3, nsq=1 -> dsq=3 (not a power of 2)
std::vector<uint8_t> buf;
push_fourcc(buf, "IxLa");
push_val<int>(buf, 3); // d
push_val<int>(buf, 1); // nsq
push_val<int>(buf, 4); // scale_nbit
push_val<int>(buf, 1); // r2
expect_read_throws_with(buf, "power of 2");
}
TEST(ReadIndexDeserialize, IndexLatticeDsqOne) {
// d=1, nsq=1 -> dsq=1 (too small, causes cache_level=-1)
std::vector<uint8_t> buf;
push_fourcc(buf, "IxLa");
push_val<int>(buf, 1); // d
push_val<int>(buf, 1); // nsq
push_val<int>(buf, 4); // scale_nbit
push_val<int>(buf, 1); // r2
expect_read_throws_with(buf, "power of 2");
}
// -----------------------------------------------------------------------
// Test: IndexLattice with r2 too large causes timeout in
// ZnSphereCodecRec constructor (exponential codeword count in the
// decode cache). ZnSphereCodecRec caps the decode cache size to
// prevent this. Use dsq=16 (log2_dim=4, cache_level=3) with r2=73
// which would take well over a minute of CPU time if not rejected.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, IndexLatticeR2TooLarge) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IxLa");
push_val<int>(buf, 16); // d
push_val<int>(buf, 1); // nsq
push_val<int>(buf, 4); // scale_nbit
push_val<int>(buf, 73); // r2 = 73 (decode cache too large for dsq=16)
expect_read_throws_with(buf, "decode cache");
}
// -----------------------------------------------------------------------
// Test: the configurable deserialization_lattice_r2_limit rejects
// IndexLattice payloads whose r2 exceeds the limit, separately from
// the in-codec decode-cache memory cap. The limit's purpose is to
// let callers that operate on untrusted index payloads cap the
// ZnSphereCodecRec decode-cache build cost (which grows polynomially
// in r2) before it dominates load time, even for parameter
// combinations that the memory cap permits.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, IndexLatticeR2ConfigurableLimit) {
const size_t old_limit = get_deserialization_lattice_r2_limit();
// d=4, nsq=1, scale_nbit=4 produces dsq=4 -- a configuration that
// passes the existing structural checks. r2 at the limit must
// deserialize cleanly (the cap is "r2 > limit", not "r2 >= limit");
// r2 above the limit must be rejected with a FaissException whose
// message names the limit, before the IndexLattice constructor
// (and the underlying ZnSphereCodecRec) is invoked.
constexpr int d = 4;
auto build = [](int r2) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IxLa");
push_val<int>(buf, d); // d
push_val<int>(buf, 1); // nsq
push_val<int>(buf, 4); // scale_nbit
push_val<int>(buf, r2); // r2
push_index_header(buf, d, /*ntotal=*/0);
// Untrained: empty trained vector.
push_vector<float>(buf, {});
return buf;
};
set_deserialization_lattice_r2_limit(2);
{
// r2 == limit: the limit check passes (since it is r2 > limit,
// not r2 >= limit) and the underlying ZnSphereCodecRec
// constructor runs to completion.
auto buf = build(2);
VectorIOReader reader;
reader.data = buf;
EXPECT_NO_THROW(read_index_up(&reader));
}
{
// r2 == limit + 1: rejected at the limit check with the
// configured limit value in the error message.
auto buf = build(3);
expect_read_throws_with(buf, "deserialization_lattice_r2_limit");
}
set_deserialization_lattice_r2_limit(old_limit);
}
// -----------------------------------------------------------------------
// Binary index helpers
// -----------------------------------------------------------------------
/// Helper: append read_index_binary_header fields.
/// Fields: int d, int code_size, idx_t ntotal, bool is_trained, int metric_type
static void push_binary_index_header(
std::vector<uint8_t>& buf,
int d,
int64_t ntotal,
bool is_trained = true,
int metric_type = 1 /* L2 */) {
int code_size = d / 8;
push_val<int>(buf, d);
push_val<int>(buf, code_size);
push_val<int64_t>(buf, ntotal);
push_val<bool>(buf, is_trained);
push_val<int>(buf, metric_type);
}
/// Try to read a binary index from the given buffer and expect a
/// FaissException.
static void expect_binary_read_throws(const std::vector<uint8_t>& data) {
VectorIOReader reader;
reader.data = data;
EXPECT_THROW(read_index_binary_up(&reader), FaissException);
}
/// Try to read a binary index and expect a FaissException whose message
/// contains the given substring.
static void expect_binary_read_throws_with(
const std::vector<uint8_t>& data,
const std::string& expected_substr) {
VectorIOReader reader;
reader.data = data;
try {
read_index_binary_up(&reader);
FAIL() << "expected FaissException";
} catch (const FaissException& e) {
EXPECT_NE(
std::string(e.what()).find(expected_substr), std::string::npos)
<< "expected '" << expected_substr << "' in: " << e.what();
}
}
/// Helper: append empty direct_map bytes (NoMap type + empty array).
static void push_empty_direct_map(std::vector<uint8_t>& buf) {
push_val<char>(buf, 0); // DirectMap::NoMap
push_val<size_t>(buf, 0); // empty array
}
/// Helper: append null inverted lists ("il00" fourcc).
static void push_null_invlists(std::vector<uint8_t>& buf) {
push_fourcc(buf, "il00");
}
/// Helper: append a minimal IndexBinaryFlat ("IBxF") with the given
/// dimensions and ntotal=0.
static void push_minimal_binary_flat(std::vector<uint8_t>& buf, int d) {
push_fourcc(buf, "IBxF");
push_binary_index_header(buf, d, /*ntotal=*/0);
push_vector<uint8_t>(buf, {}); // empty xb
}
// -----------------------------------------------------------------------
// Test: Unrecognized binary fourcc throws.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryUnrecognizedFourcc) {
std::vector<uint8_t> buf;
push_fourcc(buf, "ZZZZ");
expect_binary_read_throws(buf);
}
// -----------------------------------------------------------------------
// Test: IndexBinaryFlat with truncated input (fourcc only, no header).
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryFlatTruncatedInput) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IBxF");
expect_binary_read_throws(buf);
}
// -----------------------------------------------------------------------
// Test: IndexBinaryFlat xb size mismatch (ntotal=1 but empty xb).
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryFlatXbSizeMismatch) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IBxF");
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/1);
push_vector<uint8_t>(buf, {}); // empty xb, but ntotal=1 expects 2 bytes
expect_binary_read_throws_with(buf, "xb.size()");
}
// -----------------------------------------------------------------------
// Test: IndexBinaryFlat with negative dimension.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryFlatNegativeDimension) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IBxF");
// Manually push header with d=-1
push_val<int>(buf, -1); // d
push_val<int>(buf, 0); // code_size
push_val<int64_t>(buf, 0); // ntotal
push_val<bool>(buf, true); // is_trained
push_val<int>(buf, 1); // metric_type
expect_binary_read_throws_with(buf, "dimension");
}
// -----------------------------------------------------------------------
// Test: IndexBinaryMultiHash with storage ntotal mismatch exercises the
// Leak 5 fix (dynamic_cast + assertion with unique_ptr guard).
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryMultiHashStorageCastFailure) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IBHm");
// Outer index header: ntotal=99
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/99);
// Nested IBxF storage with ntotal=0 (mismatch with outer ntotal=99)
push_minimal_binary_flat(buf, /*d=*/16);
expect_binary_read_throws(buf);
}
// -----------------------------------------------------------------------
// Test: IndexBinaryIVF with inverted list nlist mismatch exercises the
// Leak 2 fix.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryIVFInvListNlistMismatch) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IBwF");
// Binary IVF header: binary_header + nlist + nprobe + quantizer +
// direct_map
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0);
push_val<size_t>(buf, 10); // nlist = 10
push_val<size_t>(buf, 1); // nprobe
// Nested quantizer (IBxF)
push_minimal_binary_flat(buf, /*d=*/16);
// Empty direct map
push_empty_direct_map(buf);
// ArrayInvertedLists with nlist=5 (mismatch with IVF nlist=10).
// "ilar" fourcc + nlist + code_size + sizes
push_fourcc(buf, "ilar");
push_val<size_t>(buf, 5); // nlist = 5 (mismatches IVF nlist=10)
push_val<size_t>(buf, 2); // code_size = d/8 = 2
// 5 list sizes, all zero
for (int i = 0; i < 5; i++) {
push_val<size_t>(buf, 0);
}
expect_binary_read_throws(buf);
}
// -----------------------------------------------------------------------
// Test: IndexBinaryHash with empty hash invlist buffer but non-zero entry
// count. Exercises the null-deref fix in read_binary_hash_invlists.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryHashEmptyInvlistBuffer) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IBHh");
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0);
push_val<int>(buf, 4); // b
push_val<int>(buf, 0); // nflip
push_val<size_t>(buf, size_t(1)); // sz = 1 (non-zero)
push_val<int>(buf, 8); // il_nbit
push_vector<uint8_t>(buf, {}); // empty buffer (should fail)
expect_binary_read_throws_with(buf, "binary hash invlists");
}
// -----------------------------------------------------------------------
// Test: NSG with R=0 triggers the R > 0 validation.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, NSGNegativeR) {
// "INSf" format: fourcc + index_header + GK + build_type +
// nndescent_S/R/L/iter + read_NSG(ntotal, R, ...)
std::vector<uint8_t> buf;
push_fourcc(buf, "INSf");
push_index_header(buf, /*d=*/4, /*ntotal=*/0);
push_val<int>(buf, 0); // GK
push_val<int>(buf, 0); // build_type
push_val<int>(buf, 10); // nndescent_S
push_val<int>(buf, 10); // nndescent_R
push_val<int>(buf, 10); // nndescent_L
push_val<int>(buf, 1); // nndescent_iter
// read_NSG fields:
push_val<int>(buf, 0); // ntotal
push_val<int>(buf, -1); // R = -1 (invalid)
expect_read_throws_with(buf, "invalid NSG R");
}
// -----------------------------------------------------------------------
// Test: ScalarQuantizer with out-of-range qtype throws.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, ScalarQuantizerInvalidQtype) {
// "IxSQ" format: fourcc + index_header + read_ScalarQuantizer(qtype, ...)
std::vector<uint8_t> buf;
push_fourcc(buf, "IxSQ");
push_index_header(buf, /*d=*/4, /*ntotal=*/0);
// ScalarQuantizer fields:
push_val<int>(buf, 99); // qtype = 99 (out of range)
expect_read_throws_with(buf, "qtype");
}
// -----------------------------------------------------------------------
// Test: ProductAdditiveQuantizer with nsplits=0 throws.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, ProductAdditiveQuantizerZeroNsplits) {
// "IxPR" format: fourcc + index_header +
// read_ProductResidualQuantizer(read_ProductAdditiveQuantizer(
// read_AdditiveQuantizer(...) + nsplits))
std::vector<uint8_t> buf;
push_fourcc(buf, "IxPR");
push_index_header(buf, /*d=*/4, /*ntotal=*/0);
// AdditiveQuantizer fields:
push_val<size_t>(buf, 4); // d
push_val<size_t>(buf, 1); // M
push_vector<size_t>(buf, {8}); // nbits (1 element matching M=1)
push_val<bool>(buf, true); // is_trained
// codebooks: d * total_codebook_size = 4 * 256 = 1024 floats
push_vector<float>(buf, std::vector<float>(4 * 256, 0.0f));
push_val<int>(buf, 0); // search_type = ST_decompress
push_val<float>(buf, 0.0f); // norm_min
push_val<float>(buf, 1.0f); // norm_max
// ProductAdditiveQuantizer field:
push_val<size_t>(buf, 0); // nsplits = 0 (invalid)
expect_read_throws_with(buf, "nsplits");
}
// -----------------------------------------------------------------------
// Test: PreTransform with negative chain length throws.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, PreTransformNegativeChainLength) {
// "IxPT" format: fourcc + index_header + nt + VT chain + nested index
std::vector<uint8_t> buf;
push_fourcc(buf, "IxPT");
push_index_header(buf, /*d=*/4, /*ntotal=*/0);
push_val<int>(buf, -1); // nt = -1 (invalid)
expect_read_throws_with(buf, "chain length");
}
// -----------------------------------------------------------------------
// Test: IndexBinaryMultiHash with nhash=0 throws.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryMultiHashZeroNhash) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IBHm");
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0);
// Nested IBxF storage (ntotal=0 matches outer)
push_minimal_binary_flat(buf, /*d=*/16);
push_val<int>(buf, 4); // b
push_val<int>(buf, 0); // nhash = 0 (invalid)
expect_binary_read_throws_with(buf, "nhash");
}
// -----------------------------------------------------------------------
// Test: IndexBinaryHash with b=0 triggers the b > 0 validation.
// Without this check, BitstringReader::read(0) would silently produce
// garbage hash values on every inverted-list entry.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryHashBZero) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IBHh");
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0);
push_val<int>(buf, 0); // b = 0 (invalid)
expect_binary_read_throws_with(buf, "IndexBinaryHash b=");
}
// -----------------------------------------------------------------------
// Test: read_binary_hash_invlists with negative il_nbit triggers the
// il_nbit >= 0 validation. Without this check, the negative value would
// wrap to a huge size_t in the bits-per-entry calculation, causing an
// out-of-bounds read in BitstringReader.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryHashNegativeIlNbit) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IBHh");
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0);
push_val<int>(buf, 4); // b
push_val<int>(buf, 0); // nflip
// read_binary_hash_invlists fields:
push_val<size_t>(buf, size_t(0)); // sz = 0
push_val<int>(buf, -1); // il_nbit = -1 (invalid)
expect_binary_read_throws_with(buf, "il_nbit=");
}
// -----------------------------------------------------------------------
// Test: read_binary_hash_invlists with il_nbit=0 but sz > 0 triggers
// the il_nbit > 0 validation. Without this check, every inverted-list
// size would silently read as 0, corrupting the deserialized index.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryHashIlNbitZeroWithEntries) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IBHh");
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0);
push_val<int>(buf, 4); // b
push_val<int>(buf, 0); // nflip
// read_binary_hash_invlists fields:
push_val<size_t>(buf, size_t(1)); // sz = 1 (non-zero)
push_val<int>(buf, 0); // il_nbit = 0 (invalid when sz > 0)
expect_binary_read_throws_with(buf, "il_nbit=");
}
// -----------------------------------------------------------------------
// Test: IndexBinaryHash with b exceeding code_size*8 triggers validation.
// Without this check, BitstringReader::read() would access past the
// allocated code buffer, causing a heap-buffer-overflow.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryHashBExceedsCodeSize) {
std::vector<uint8_t> buf;
push_fourcc(buf, "IBHh");
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0);
// d=16 → code_size=2 → 16 bits available
push_val<int>(buf, 17); // b = 17 (exceeds 16 bits)
expect_binary_read_throws_with(buf, "IndexBinaryHash b=");
}
// -----------------------------------------------------------------------
// Test: read_binary_multi_hash_map with crafted ilsz values that sum to
// more than ntotal. Without the check, the inner loop would read past
// the end of the BitstringReader buffer.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryMultiHashMapIlszExceedsNtotal) {
// ntotal=4 → id_bits=2 (writer: while (4 > (1<<id_bits)) id_bits++)
// b=4, sz=2 entries
// Total bits formula: (b + id_bits) * sz + ntotal * id_bits
// = (4 + 2) * 2 + 4 * 2 = 20
// buf size = (20 + 7) / 8 = 3 bytes
//
// Craft entry 0: hash=0, ilsz=3 (3 ids follow)
// Craft entry 1: hash=1, ilsz=3 (3 ids follow)
// Total ilsz = 6, but ntotal = 4 → should throw on entry 1.
const int b = 4;
const int id_bits = 2;
const size_t ntotal = 4;
const size_t sz = 2;
const size_t nbit = (b + id_bits) * sz + ntotal * id_bits;
const size_t bitbuf_size = (nbit + 7) / 8;
// Pack the bitstring with BitstringWriter.
std::vector<uint8_t> bitbuf(bitbuf_size, 0);
BitstringWriter wr(bitbuf.data(), bitbuf.size());
// Entry 0: hash=0, ilsz=3, ids={0,0,0}
wr.write(0, b);
wr.write(3, id_bits);
wr.write(0, id_bits);
wr.write(0, id_bits);
wr.write(0, id_bits);
// Entry 1: hash=1, ilsz=3
// (reader should throw before reading ids for this entry)
wr.write(1, b);
wr.write(3, id_bits);
// Build the full IBHm serialized buffer.
std::vector<uint8_t> buf;
push_fourcc(buf, "IBHm");
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/ntotal);
// Nested IBxF storage with matching ntotal.
// xb needs ntotal * code_size bytes (code_size = d/8 = 2).
push_fourcc(buf, "IBxF");
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/ntotal);
std::vector<uint8_t> xb(ntotal * 2, 0);
push_vector<uint8_t>(buf, xb);
push_val<int>(buf, b); // b
push_val<int>(buf, 1); // nhash = 1
push_val<int>(buf, 0); // nflip
// Multi hash map fields (1 map):
push_val<int>(buf, id_bits); // id_bits
push_val<size_t>(buf, sz); // sz = 2 entries
push_vector<uint8_t>(buf, bitbuf); // packed bitstring
expect_binary_read_throws_with(buf, "would exceed ntotal");
}
// -----------------------------------------------------------------------
// Test: IndexBinaryIDMap ("IBMp") with id_map size != ntotal. Without
// the check, construct_rev_map (IBM2) or subsequent search operations
// would use an inconsistent ID mapping.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BinaryIDMapIdMapSizeMismatch) {
// Outer IBMp header has ntotal=2, but the id_map vector has 5
// entries. The check on id_map.size() == ntotal must reject this.
std::vector<uint8_t> buf;
push_fourcc(buf, "IBMp");
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/2);
// Nested IBxF storage with ntotal=2 (matches outer header).
push_fourcc(buf, "IBxF");
push_binary_index_header(buf, /*d=*/16, /*ntotal=*/2);
std::vector<uint8_t> xb(2 * 2, 0); // ntotal * code_size
push_vector<uint8_t>(buf, xb);
// id_map with 5 entries (mismatches ntotal=2).
std::vector<int64_t> id_map = {10, 20, 30, 40, 50};
push_vector<int64_t>(buf, id_map);
expect_binary_read_throws_with(buf, "id_map");
}
// -----------------------------------------------------------------------
// Test: IndexIDMap2 ("IxM2") with id_map size != ntotal. Without the
// check, construct_rev_map() reads past id_map bounds causing a crash.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, IndexIDMap2IdMapSizeMismatch) {
// Outer IxM2 header has ntotal=2, but the id_map vector has 5
// entries. The check on id_map.size() == ntotal must reject this.
std::vector<uint8_t> buf;
push_fourcc(buf, "IxM2");
push_index_header(buf, /*d=*/4, /*ntotal=*/2);
// Nested IndexFlatL2 ("IxF2") with ntotal=2.
push_fourcc(buf, "IxF2");
push_index_header(buf, /*d=*/4, /*ntotal=*/2);
// WRITEXBVECTOR: ntotal * d floats
size_t num_floats = 2 * 4;
push_val<size_t>(buf, num_floats);
for (size_t i = 0; i < num_floats; ++i) {
push_val<float>(buf, 0.0f);
}
// id_map with 5 entries (mismatches ntotal=2).
std::vector<int64_t> id_map = {10, 20, 30, 40, 50};
push_vector<int64_t>(buf, id_map);
expect_read_throws_with(buf, "id_map");
}
// -----------------------------------------------------------------------
// InvertedLists helpers
// -----------------------------------------------------------------------
/// Try to read an InvertedLists from the given buffer and expect a
/// FaissException whose message contains the given substring.
static void expect_invlists_read_throws_with(
const std::vector<uint8_t>& data,
const std::string& expected_substr) {
VectorIOReader reader;
reader.data = data;
try {
read_InvertedLists_up(&reader);
FAIL() << "expected FaissException";
} catch (const FaissException& e) {
EXPECT_NE(
std::string(e.what()).find(expected_substr), std::string::npos)
<< "expected '" << expected_substr << "' in: " << e.what();
}
}
// -----------------------------------------------------------------------
// Test: BlockInvertedLists with n_per_block=0 causes divide-by-zero
// in resize() and add_entries(). The fix validates n_per_block > 0
// during deserialization.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BlockInvertedListsNPerBlockZero) {
std::vector<uint8_t> buf;
push_fourcc(buf, "ilbl");
push_val<size_t>(buf, 1); // nlist
push_val<size_t>(buf, 32); // code_size
push_val<size_t>(buf, 0); // n_per_block = 0 (invalid)
push_val<size_t>(buf, 128); // block_size
expect_invlists_read_throws_with(buf, "n_per_block");
}
// -----------------------------------------------------------------------
// Test: BlockInvertedLists with block_size=0 causes divide-by-zero
// in add_entries(). The fix validates block_size > 0 during
// deserialization.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BlockInvertedListsBlockSizeZero) {
std::vector<uint8_t> buf;
push_fourcc(buf, "ilbl");
push_val<size_t>(buf, 1); // nlist
push_val<size_t>(buf, 32); // code_size
push_val<size_t>(buf, 32); // n_per_block
push_val<size_t>(buf, 0); // block_size = 0 (invalid)
expect_invlists_read_throws_with(buf, "block_size");
}
// -----------------------------------------------------------------------
// Test: BlockInvertedLists with codes vector size inconsistent with ids
// size, n_per_block, and block_size. Without the check, a search or
// add operation would read/write past the end of the codes buffer.
// -----------------------------------------------------------------------
TEST(ReadIndexDeserialize, BlockInvertedListsCodesSizeMismatch) {
const size_t n_per_block = 32;
const size_t block_size = 128;
You can’t perform that action at this time.