-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathinverted_index.cpp
More file actions
2124 lines (1824 loc) · 82.7 KB
/
inverted_index.cpp
File metadata and controls
2124 lines (1824 loc) · 82.7 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
/**
* Inverted index for sparse vector similarity search.
*
* Blocked on-disk layout in MDBX:
* key = pack(term_id, block_nr) as uint64_t integer-key
* value = BlockHeader | doc_offsets[n] (uint16) | values[n] (uint8 or float)
*
* Metadata rows in the same DBI:
* pack(term_id, UINT32_MAX) -> PostingListHeader
*
* The key packing keeps all rows for a term contiguous, so scans can seek once
* to pack(term_id, 0) and walk until term_id changes.
*/
#include "inverted_index.hpp"
#include <atomic>
#include <chrono>
#include <cmath>
namespace ndd {
namespace {
template <bool StoreFloats>
struct PostingValueAccessor;
template <>
struct PostingValueAccessor<true> {
using ValueType = float;
static inline bool isLive(ValueType value) {
return value > 0.0f;
}
};
template <>
struct PostingValueAccessor<false> {
using ValueType = uint8_t;
static inline bool isLive(ValueType value) {
return value > 0;
}
};
#ifdef ND_SPARSE_INSTRUMENT
using SteadyClock = std::chrono::steady_clock;
inline uint64_t elapsedNsSince(const SteadyClock::time_point& start) {
return static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(SteadyClock::now() - start)
.count());
}
struct SparseSearchDebugStats {
std::atomic<uint64_t> phase2_iterators_visited{0};
std::atomic<uint64_t> phase2_iterators_contributed{0};
std::atomic<uint64_t> parse_current_kv_calls{0};
std::atomic<uint64_t> parse_current_kv_total_ns{0};
};
struct SparseUpdateDebugStats {
std::atomic<uint64_t> add_batch_calls{0};
std::atomic<uint64_t> add_batch_docs{0};
std::atomic<uint64_t> add_batch_terms{0};
std::atomic<uint64_t> add_batch_raw_updates{0};
std::atomic<uint64_t> add_batch_deduped_updates{0};
std::atomic<uint64_t> add_batch_blocks{0};
std::atomic<uint64_t> build_term_updates_total_ns{0};
std::atomic<uint64_t> sort_dedup_total_ns{0};
std::atomic<uint64_t> load_block_calls{0};
std::atomic<uint64_t> load_block_total_ns{0};
std::atomic<uint64_t> load_block_entries_total{0};
std::atomic<uint64_t> merge_block_calls{0};
std::atomic<uint64_t> merge_block_total_ns{0};
std::atomic<uint64_t> merge_existing_entries_total{0};
std::atomic<uint64_t> merge_update_entries_total{0};
std::atomic<uint64_t> merge_output_entries_total{0};
std::atomic<uint64_t> save_block_calls{0};
std::atomic<uint64_t> save_block_total_ns{0};
std::atomic<uint64_t> save_block_entries_total{0};
std::atomic<uint64_t> recompute_max_calls{0};
std::atomic<uint64_t> recompute_max_total_ns{0};
};
SparseSearchDebugStats& sparseSearchDebugStats() {
static SparseSearchDebugStats stats;
return stats;
}
SparseUpdateDebugStats& sparseUpdateDebugStats() {
static SparseUpdateDebugStats stats;
return stats;
}
class ParseCurrentKVTimer {
public:
ParseCurrentKVTimer() :
start_(SteadyClock::now()) {}
~ParseCurrentKVTimer() {
SparseSearchDebugStats& stats = sparseSearchDebugStats();
stats.parse_current_kv_calls.fetch_add(1, std::memory_order_relaxed);
stats.parse_current_kv_total_ns.fetch_add(elapsedNsSince(start_),
std::memory_order_relaxed);
}
private:
SteadyClock::time_point start_;
};
#endif // ND_SPARSE_INSTRUMENT
} // namespace
#ifdef ND_SPARSE_INSTRUMENT
void printSparseSearchDebugStats() {
SparseSearchDebugStats& stats = sparseSearchDebugStats();
const uint64_t visited = stats.phase2_iterators_visited.exchange(0, std::memory_order_relaxed);
const uint64_t contributed =
stats.phase2_iterators_contributed.exchange(0, std::memory_order_relaxed);
const uint64_t parse_calls = stats.parse_current_kv_calls.exchange(0, std::memory_order_relaxed);
const uint64_t parse_total_ns =
stats.parse_current_kv_total_ns.exchange(0, std::memory_order_relaxed);
LOG_INFO("Sparse search debug stats");
LOG_INFO("phase3 iterators visited: " << visited);
LOG_INFO("phase3 iterators contributed: " << contributed);
LOG_INFO("phase3 contribution rate(%): "
<< std::fixed << std::setprecision(3)
<< (visited ? (100.0 * static_cast<double>(contributed) / static_cast<double>(visited))
: 0.0));
LOG_INFO("parseCurrentKV count: " << parse_calls);
LOG_INFO("parseCurrentKV total(ms): "
<< std::fixed << std::setprecision(3)
<< (static_cast<double>(parse_total_ns) / 1'000'000.0));
LOG_INFO("parseCurrentKV avg(us): "
<< std::fixed << std::setprecision(3)
<< (parse_calls ? (static_cast<double>(parse_total_ns) / 1000.0)
/ static_cast<double>(parse_calls)
: 0.0));
std::cout << "=================================\n";
}
void printSparseUpdateDebugStats() {
SparseUpdateDebugStats& stats = sparseUpdateDebugStats();
const uint64_t add_batch_calls = stats.add_batch_calls.exchange(0, std::memory_order_relaxed);
const uint64_t add_batch_docs = stats.add_batch_docs.exchange(0, std::memory_order_relaxed);
const uint64_t add_batch_terms = stats.add_batch_terms.exchange(0, std::memory_order_relaxed);
const uint64_t add_batch_raw_updates =
stats.add_batch_raw_updates.exchange(0, std::memory_order_relaxed);
const uint64_t add_batch_deduped_updates =
stats.add_batch_deduped_updates.exchange(0, std::memory_order_relaxed);
const uint64_t add_batch_blocks = stats.add_batch_blocks.exchange(0, std::memory_order_relaxed);
const uint64_t build_term_updates_total_ns =
stats.build_term_updates_total_ns.exchange(0, std::memory_order_relaxed);
const uint64_t sort_dedup_total_ns =
stats.sort_dedup_total_ns.exchange(0, std::memory_order_relaxed);
const uint64_t load_block_calls = stats.load_block_calls.exchange(0, std::memory_order_relaxed);
const uint64_t load_block_total_ns =
stats.load_block_total_ns.exchange(0, std::memory_order_relaxed);
const uint64_t load_block_entries_total =
stats.load_block_entries_total.exchange(0, std::memory_order_relaxed);
const uint64_t merge_block_calls = stats.merge_block_calls.exchange(0, std::memory_order_relaxed);
const uint64_t merge_block_total_ns =
stats.merge_block_total_ns.exchange(0, std::memory_order_relaxed);
const uint64_t merge_existing_entries_total =
stats.merge_existing_entries_total.exchange(0, std::memory_order_relaxed);
const uint64_t merge_update_entries_total =
stats.merge_update_entries_total.exchange(0, std::memory_order_relaxed);
const uint64_t merge_output_entries_total =
stats.merge_output_entries_total.exchange(0, std::memory_order_relaxed);
const uint64_t save_block_calls = stats.save_block_calls.exchange(0, std::memory_order_relaxed);
const uint64_t save_block_total_ns =
stats.save_block_total_ns.exchange(0, std::memory_order_relaxed);
const uint64_t save_block_entries_total =
stats.save_block_entries_total.exchange(0, std::memory_order_relaxed);
const uint64_t recompute_max_calls =
stats.recompute_max_calls.exchange(0, std::memory_order_relaxed);
const uint64_t recompute_max_total_ns =
stats.recompute_max_total_ns.exchange(0, std::memory_order_relaxed);
LOG_INFO("Sparse update debug stats");
LOG_INFO("addDocumentsBatchInternal count: " << add_batch_calls);
LOG_INFO("addDocumentsBatchInternal docs: " << add_batch_docs);
LOG_INFO("addDocumentsBatchInternal terms: " << add_batch_terms);
LOG_INFO("addDocumentsBatchInternal raw updates: " << add_batch_raw_updates);
LOG_INFO("addDocumentsBatchInternal deduped updates: " << add_batch_deduped_updates);
LOG_INFO("addDocumentsBatchInternal touched blocks: " << add_batch_blocks);
LOG_INFO("term_updates build total(ms): "
<< std::fixed << std::setprecision(3)
<< (static_cast<double>(build_term_updates_total_ns) / 1'000'000.0));
LOG_INFO("sort+dedup total(ms): "
<< std::fixed << std::setprecision(3)
<< (static_cast<double>(sort_dedup_total_ns) / 1'000'000.0));
LOG_INFO("loadBlockEntries count: " << load_block_calls);
LOG_INFO("loadBlockEntries total(ms): "
<< std::fixed << std::setprecision(3)
<< (static_cast<double>(load_block_total_ns) / 1'000'000.0));
LOG_INFO("loadBlockEntries avg(us): "
<< std::fixed << std::setprecision(3)
<< (load_block_calls
? (static_cast<double>(load_block_total_ns) / 1000.0)
/ static_cast<double>(load_block_calls)
: 0.0));
LOG_INFO("loadBlockEntries avg existing entries: "
<< std::fixed << std::setprecision(3)
<< (load_block_calls
? static_cast<double>(load_block_entries_total)
/ static_cast<double>(load_block_calls)
: 0.0));
LOG_INFO("merge blocks count: " << merge_block_calls);
LOG_INFO("merge blocks total(ms): "
<< std::fixed << std::setprecision(3)
<< (static_cast<double>(merge_block_total_ns) / 1'000'000.0));
LOG_INFO("merge blocks avg(us): "
<< std::fixed << std::setprecision(3)
<< (merge_block_calls
? (static_cast<double>(merge_block_total_ns) / 1000.0)
/ static_cast<double>(merge_block_calls)
: 0.0));
LOG_INFO("merge avg existing entries: "
<< std::fixed << std::setprecision(3)
<< (merge_block_calls
? static_cast<double>(merge_existing_entries_total)
/ static_cast<double>(merge_block_calls)
: 0.0));
LOG_INFO("merge avg update entries: "
<< std::fixed << std::setprecision(3)
<< (merge_block_calls
? static_cast<double>(merge_update_entries_total)
/ static_cast<double>(merge_block_calls)
: 0.0));
LOG_INFO("merge avg output entries: "
<< std::fixed << std::setprecision(3)
<< (merge_block_calls
? static_cast<double>(merge_output_entries_total)
/ static_cast<double>(merge_block_calls)
: 0.0));
LOG_INFO("saveBlockEntries count: " << save_block_calls);
LOG_INFO("saveBlockEntries total(ms): "
<< std::fixed << std::setprecision(3)
<< (static_cast<double>(save_block_total_ns) / 1'000'000.0));
LOG_INFO("saveBlockEntries avg(us): "
<< std::fixed << std::setprecision(3)
<< (save_block_calls
? (static_cast<double>(save_block_total_ns) / 1000.0)
/ static_cast<double>(save_block_calls)
: 0.0));
LOG_INFO("saveBlockEntries avg entries: "
<< std::fixed << std::setprecision(3)
<< (save_block_calls
? static_cast<double>(save_block_entries_total)
/ static_cast<double>(save_block_calls)
: 0.0));
LOG_INFO("recomputeGlobalMax count: " << recompute_max_calls);
LOG_INFO("recomputeGlobalMax total(ms): "
<< std::fixed << std::setprecision(3)
<< (static_cast<double>(recompute_max_total_ns) / 1'000'000.0));
LOG_INFO("recomputeGlobalMax avg(us): "
<< std::fixed << std::setprecision(3)
<< (recompute_max_calls
? (static_cast<double>(recompute_max_total_ns) / 1000.0)
/ static_cast<double>(recompute_max_calls)
: 0.0));
std::cout << "=================================\n";
}
#else
void printSparseSearchDebugStats() {}
void printSparseUpdateDebugStats() {}
#endif // ND_SPARSE_INSTRUMENT
InvertedIndex::InvertedIndex(MDBX_env* env,
size_t vocab_size,
const std::string& index_id,
ndd::SparseScoringModel sparse_model)
: env_(env),
blocked_term_postings_dbi_(0),
vocab_size_(vocab_size),
index_id_(index_id),
sparse_model_(sparse_model) {}
void InvertedIndex::applyHeaderDelta(PostingListHeader& header,
int64_t total_delta,
int64_t live_delta) {
int64_t new_total = static_cast<int64_t>(header.nr_entries) + total_delta;
int64_t new_live = static_cast<int64_t>(header.nr_live_entries) + live_delta;
if (new_total < 0) new_total = 0;
if (new_live < 0) new_live = 0;
if (new_live > new_total) new_live = new_total;
header.nr_entries = static_cast<uint32_t>(new_total);
header.nr_live_entries = static_cast<uint32_t>(new_live);
}
bool InvertedIndex::validateSuperBlock(MDBX_txn* txn) {
SuperBlock sb;
bool sb_found = false;
if (!readSuperBlock(txn, &sb, &sb_found)) {
return false;
}
if (!sb_found) {
// Check whether the DBI already has data (legacy DB without superblock).
MDBX_stat stat;
int rc = mdbx_dbi_stat(txn, blocked_term_postings_dbi_, &stat, sizeof(stat));
if (rc == MDBX_SUCCESS && stat.ms_entries > 0) {
LOG_ERROR(2201,
index_id_,
"Sparse index database exists without a superblock; it was created by an older incompatible version");
throw std::runtime_error(
"Incompatible sparse index: database has no superblock (legacy format)");
}
// Fresh database — write the superblock.
sb.format_version = settings::SPARSE_ONDISK_VERSION;
LOG_INFO(2202,
index_id_,
"Writing fresh sparse superblock (version="
<< static_cast<int>(settings::SPARSE_ONDISK_VERSION) << ")");
if (!writeSuperBlock(txn, sb)) {
return false;
}
return true;
}
if (sb.format_version != settings::SPARSE_ONDISK_VERSION) {
LOG_ERROR(2203,
index_id_,
"Sparse index format version mismatch: on-disk="
<< static_cast<int>(sb.format_version)
<< " compiled=" << static_cast<int>(settings::SPARSE_ONDISK_VERSION));
throw std::runtime_error(
"Incompatible sparse index: format version "
+ std::to_string(sb.format_version)
+ " does not match compiled version "
+ std::to_string(settings::SPARSE_ONDISK_VERSION));
}
return true;
}
bool InvertedIndex::initialize() {
std::unique_lock<std::shared_mutex> lock(mutex_);
MDBX_txn* txn = nullptr;
int rc = mdbx_txn_begin(env_, nullptr, MDBX_TXN_READWRITE, &txn);
if (rc != MDBX_SUCCESS) {
LOG_ERROR(2204, index_id_, "Failed to begin sparse index init transaction: " << mdbx_strerror(rc));
return false;
}
rc = mdbx_dbi_open(txn,
"blocked_term_postings",
MDBX_CREATE | MDBX_INTEGERKEY,
&blocked_term_postings_dbi_);
if (rc != MDBX_SUCCESS) {
LOG_ERROR(2205, index_id_, "Failed to open blocked_term_postings DBI: " << mdbx_strerror(rc));
mdbx_txn_abort(txn);
return false;
}
if (!validateSuperBlock(txn)) {
mdbx_txn_abort(txn);
return false;
}
rc = mdbx_txn_commit(txn);
if (rc != MDBX_SUCCESS) {
LOG_ERROR(2206, index_id_, "Failed to commit sparse index init transaction: " << mdbx_strerror(rc));
return false;
}
if (!loadTermInfo()) {
return false;
}
LOG_INFO(2207, index_id_, "Sparse index initialized with " << term_info_.size() << " loaded terms");
return true;
}
bool InvertedIndex::addDocumentsBatch(
MDBX_txn* txn,
const std::vector<std::pair<ndd::idInt, SparseVector>>& docs)
{
std::unique_lock<std::shared_mutex> lock(mutex_);
return addDocumentsBatchInternal(txn, docs);
}
bool InvertedIndex::removeDocument(MDBX_txn* txn,
ndd::idInt doc_id,
const SparseVector& vec)
{
std::unique_lock<std::shared_mutex> lock(mutex_);
return removeDocumentInternal(txn, doc_id, vec);
}
size_t InvertedIndex::getTermCount() const {
return term_info_.size();
}
size_t InvertedIndex::getVocabSize() const {
return vocab_size_;
}
std::vector<std::pair<ndd::idInt, float>>
InvertedIndex::search(const SparseVector& query,
size_t k,
const ndd::RoaringBitmap* filter)
{
return search(query, k, 0, filter);
}
//log(1 + (N - df + 0.5)/(df + 0.5))
float InvertedIndex::get_IDF(size_t total_nr_docs, size_t nr_live_docs_with_term) {
if (total_nr_docs == 0) {
return 0.0f;
}
const size_t clamped_df = std::min(total_nr_docs, nr_live_docs_with_term);
const double total_docs = static_cast<double>(total_nr_docs);
const double doc_freq = static_cast<double>(clamped_df);
const double ratio = (total_docs - doc_freq + 0.5) / (doc_freq + 0.5);
return static_cast<float>(std::log(1.0 + ratio));
}
#if 0
/**
* There are many implementations of IDF.
* We can make a library of implementations later.
*/
float InvertedIndex::get_IDF(size_t total_nr_docs, size_t nr_live_docs_with_term) {
return 1;
if (total_nr_docs == 0) {
return 0.0f;
}
const size_t clamped_df = std::min(total_nr_docs, nr_live_docs_with_term);
const double total_docs = static_cast<double>(total_nr_docs);
return std::log(total_docs + 1) - std::log(clamped_df + 0.5);
}
#endif //if 0
template <bool StoreFloats>
bool InvertedIndex::accumulateBatchScores(PostingListIterator* it,
ndd::idInt batch_start,
uint32_t batch_end_block_nr,
BlockOffset batch_end_block_offset,
float* scores_buf,
float term_weight)
{
using Accessor = PostingValueAccessor<StoreFloats>;
using ValueType = typename Accessor::ValueType;
const BlockOffset* offsets = it->doc_offsets;
const ValueType* vals = static_cast<const ValueType*>(it->values_ptr);
uint32_t idx = it->current_entry_idx;
uint32_t sz = it->data_size;
float block_max_value = it->max_value;
bool contributed = false;
while (true) {
if (it->current_block_nr > batch_end_block_nr) {
break;
}
const bool consume_full_block = it->current_block_nr < batch_end_block_nr;
const int64_t local_base =
static_cast<int64_t>(it->currentBlockBaseDocId()) - static_cast<int64_t>(batch_start);
const uint32_t before = idx;
while (idx < sz && (consume_full_block || offsets[idx] <= batch_end_block_offset)) {
const ValueType value = vals[idx];
if (Accessor::isLive(value)) {
const size_t local = static_cast<size_t>(local_base + offsets[idx]);
if constexpr (StoreFloats) {
scores_buf[local] += value * term_weight;
} else {
scores_buf[local] += InvertedIndex::dequantize(value, block_max_value) * term_weight;
}
contributed = true;
}
idx++;
}
it->consumeEntries(idx - before);
if (idx < sz) {
break;
}
it->current_entry_idx = idx;
if (!it->loadNextBlock()) {
break;
}
offsets = it->doc_offsets;
vals = static_cast<const ValueType*>(it->values_ptr);
block_max_value = it->max_value;
idx = 0;
sz = it->data_size;
if (it->current_block_nr > batch_end_block_nr
|| (it->current_block_nr == batch_end_block_nr
&& sz > 0
&& offsets[0] > batch_end_block_offset))
{
break;
}
}
it->current_entry_idx = idx;
it->advanceToNextLive();
return contributed;
}
std::vector<std::pair<ndd::idInt, float>>
InvertedIndex::search(const SparseVector& query,
size_t k,
size_t total_nr_docs,
const ndd::RoaringBitmap* filter)
{
std::shared_lock<std::shared_mutex> lock(mutex_);
MDBX_txn* txn = nullptr;
int rc = mdbx_txn_begin(env_, nullptr, MDBX_TXN_RDONLY, &txn);
if (rc != MDBX_SUCCESS) {
LOG_ERROR(2208, index_id_, "Failed to begin sparse search transaction: " << mdbx_strerror(rc));
return {};
}
if (query.empty() || k == 0) {
mdbx_txn_abort(txn);
return {};
}
std::vector<PostingListIterator> iters_storage;
std::vector<PostingListIterator*> iters;
std::vector<MDBX_cursor*> cursors;
iters_storage.reserve(query.indices.size());
iters.reserve(query.indices.size());
cursors.reserve(query.indices.size());
{
LOG_TIME("search phase 1");
// Build one iterator per live query term. Each iterator owns a cursor and lazily
// streams the term's block rows instead of pulling the whole posting list in memory.
for (size_t qi = 0; qi < query.indices.size(); qi++) {
uint32_t term_id = query.indices[qi];
if (term_id == kMetadataTermId) continue;
float qw = query.values[qi];
if (qw <= 0.0f) continue;
auto info_it = term_info_.find(term_id);
if (info_it == term_info_.end()) {
LOG_WARN(2209, index_id_, "Search skipped unknown query term_id=" << term_id);
continue;
}
bool header_found = false;
PostingListHeader header = readPostingListHeader(txn, term_id, &header_found);
if (!header_found || header.nr_entries == 0 || header.nr_live_entries == 0) {
continue;
}
float term_weight = qw;
if (sparse_model_ == ndd::SparseScoringModel::ENDEE_BM25) {
term_weight *= get_IDF(total_nr_docs, header.nr_live_entries);
}
MDBX_cursor* cursor = nullptr;
rc = mdbx_cursor_open(txn, blocked_term_postings_dbi_, &cursor);
if (rc != MDBX_SUCCESS) {
LOG_ERROR(2210,
index_id_,
"Failed to open sparse search cursor for term "
<< term_id << ": " << mdbx_strerror(rc));
continue;
}
PostingListIterator it;
it.init(cursor,
term_id,
term_weight,
info_it->second,
header.nr_entries,
this);
if (it.current_doc_id != EXHAUSTED_DOC_ID) {
iters_storage.push_back(it);
cursors.push_back(cursor);
} else {
mdbx_cursor_close(cursor);
}
}
for (size_t i = 0; i < iters_storage.size(); i++) {
iters.push_back(&iters_storage[i]);
}
if (iters.empty()) {
mdbx_txn_abort(txn);
return {};
}
//END OF PHASE 1
}
bool use_pruning = (iters.size() > 1);
float best_min_score = 0.0f;
std::vector<float> scores_buf(settings::INV_IDX_SEARCH_BATCH_SZ, 0.0f);
std::priority_queue<ScoredDoc> top_results;
float threshold = 0.0f;
auto minIterDocId = [&iters]() -> ndd::idInt {
ndd::idInt min_id = EXHAUSTED_DOC_ID;
for (size_t i = 0; i < iters.size(); i++) {
if (iters[i]->current_doc_id < min_id) {
min_id = iters[i]->current_doc_id;
}
}
return min_id;
};
ndd::idInt min_id = minIterDocId();
// Process the index in doc-id windows. The accumulator is dense within the current
// window even though the posting lists themselves stay sparse and block-based.
while (min_id != EXHAUSTED_DOC_ID) {
ndd::idInt batch_start = min_id;
ndd::idInt batch_end = batch_start
+ (ndd::idInt)settings::INV_IDX_SEARCH_BATCH_SZ - 1;
if (batch_end < batch_start) {
batch_end = EXHAUSTED_DOC_ID - 1;
}
const uint32_t batch_end_block_nr = docToBlockNr(batch_end);
const BlockOffset batch_end_block_offset = docToBlockOffset(batch_end);
size_t batch_len = (size_t)(batch_end - batch_start) + 1;
if (batch_len > scores_buf.size()) {
scores_buf.resize(batch_len);
}
std::memset(scores_buf.data(), 0, batch_len * sizeof(float));
{
LOG_TIME("search phase 2");
// Consume all postings that fall into this batch. The iterator keeps absolute doc_ids
// implicit as (current_block_nr, doc_offsets[idx]) to avoid rebuilding them eagerly.
for (size_t i = 0; i < iters.size(); i++) {
PostingListIterator* it = iters[i];
#ifdef ND_SPARSE_INSTRUMENT
sparseSearchDebugStats().phase2_iterators_visited.fetch_add(1, std::memory_order_relaxed);
#endif // ND_SPARSE_INSTRUMENT
if (it->current_doc_id > batch_end) {
continue;
}
[[maybe_unused]] const bool phase3_contributed =
#if defined(NDD_INV_IDX_STORE_FLOATS)
accumulateBatchScores<true>(
it,
batch_start,
batch_end_block_nr,
batch_end_block_offset,
scores_buf.data(),
it->term_weight);
#else
accumulateBatchScores<false>(
it,
batch_start,
batch_end_block_nr,
batch_end_block_offset,
scores_buf.data(),
it->term_weight);
#endif // NDD_INV_IDX_STORE_FLOATS
#ifdef ND_SPARSE_INSTRUMENT
if (phase3_contributed) {
sparseSearchDebugStats().phase2_iterators_contributed.fetch_add(
1, std::memory_order_relaxed);
}
#endif // ND_SPARSE_INSTRUMENT
}
//END OF SEARCH PHASE 2
}
{
LOG_TIME("search phase 3");
// Only scores inside the current batch can be non-zero, so convert that temporary
// dense buffer into top-k candidates before moving to the next window.
for (size_t local = 0; local < batch_len; local++) {
float s = scores_buf[local];
if (s == 0.0f || s <= threshold) continue;
ndd::idInt doc_id = batch_start + (ndd::idInt)local;
if (filter && !filter->contains(doc_id)) continue;
if (top_results.size() < k) {
top_results.emplace(doc_id, s);
if (top_results.size() == k) {
threshold = top_results.top().score;
}
} else if (s > threshold) {
top_results.pop();
top_results.emplace(doc_id, s);
threshold = top_results.top().score;
}
}
//END OF SEARCH PHASE 3
}
{
LOG_TIME("search phase 4");
// Compact away exhausted iterators, then optionally prune the longest remaining list
// when its best possible future contribution cannot beat the current threshold.
size_t write_idx = 0;
for (size_t i = 0; i < iters.size(); i++) {
if (iters[i]->current_doc_id != EXHAUSTED_DOC_ID) {
iters[write_idx++] = iters[i];
}
}
iters.resize(write_idx);
if (iters.empty()) break;
min_id = minIterDocId();
if (use_pruning && top_results.size() >= k) {
float new_min_score = threshold;
if (!nearEqual(new_min_score, best_min_score)) {
best_min_score = new_min_score;
pruneLongest(iters, new_min_score);
min_id = minIterDocId();
}
}
//END OF SEARCH PHASE 4
}
}
#ifdef NDD_INV_IDX_PRUNE_DEBUG
for (const PostingListIterator& it : iters_storage) {
LOG_INFO(2229,
index_id_,
"Sparse prune stats: term_id=" << it.term_id
<< " posting_list_len=" << it.initial_entries
<< " pruned_len=" << it.pruned_entries);
}
#endif // NDD_INV_IDX_PRUNE_DEBUG
for (MDBX_cursor* cursor : cursors) {
mdbx_cursor_close(cursor);
}
mdbx_txn_abort(txn);
std::vector<std::pair<ndd::idInt, float>> results;
results.reserve(top_results.size());
while (!top_results.empty()) {
results.push_back(
std::make_pair(top_results.top().doc_id, top_results.top().score));
top_results.pop();
}
std::reverse(results.begin(), results.end());
return results;
}
inline uint8_t InvertedIndex::quantize(float val, float max_val) {
if (max_val <= settings::NEAR_ZERO)
return 0;
float scaled = (val / max_val) * UINT8_MAX;
if (scaled >= UINT8_MAX)
return UINT8_MAX;
if (scaled <= 0.0f)
return 0;
uint8_t result = (uint8_t)(scaled + 0.5f);
/**
* Since a 0 weight is considered deleted,
* we change it to 1
*/
return result == 0 ? 1 : result;
}
inline float InvertedIndex::dequantize(uint8_t val, float max_val) {
if (max_val <= settings::NEAR_ZERO)
return 0.0f;
return (float)val * (max_val / UINT8_MAX);
}
// =========================================================================
// SIMD helpers
// =========================================================================
size_t InvertedIndex::findDocIdSIMD(const uint32_t* doc_ids,
size_t size,
size_t start_idx,
uint32_t target) const
{
size_t idx = start_idx;
#if defined(USE_AVX512)
const size_t simd_width = 16;
__m512i target_vec = _mm512_set1_epi32((int)target);
while (idx + simd_width <= size) {
__m512i data_vec = _mm512_loadu_si512(doc_ids + idx);
__mmask16 mask = _mm512_cmpge_epu32_mask(data_vec, target_vec);
if (mask != 0) {
return idx + __builtin_ctz(mask);
}
idx += simd_width;
}
#elif defined(USE_AVX2)
const size_t simd_width = 8;
__m256i target_vec = _mm256_set1_epi32((int)target);
while (idx + simd_width <= size) {
__builtin_prefetch(doc_ids + idx + 32);
if (doc_ids[idx + simd_width - 1] < target) {
idx += simd_width;
continue;
}
__m256i data_vec =
_mm256_loadu_si256((const __m256i*)(doc_ids + idx));
__m256i max_vec = _mm256_max_epu32(data_vec, target_vec);
__m256i cmp = _mm256_cmpeq_epi32(max_vec, data_vec);
int mask = _mm256_movemask_ps(_mm256_castsi256_ps(cmp));
if (mask != 0) {
return idx + __builtin_ctz(mask);
}
idx += simd_width;
}
#elif defined(USE_SVE2)
svbool_t pg = svwhilelt_b32(idx, size);
svuint32_t target_vec = svdup_u32(target);
while (svptest_any(svptrue_b32(), pg)) {
svuint32_t data_vec = svld1_u32(pg, doc_ids + idx);
svbool_t cmp = svcmpge_u32(pg, data_vec, target_vec);
if (svptest_any(pg, cmp)) {
svbool_t before_match = svbrkb_z(pg, cmp);
uint64_t count = svcntp_b32(pg, before_match);
return idx + count;
}
idx += svcntw();
pg = svwhilelt_b32(idx, size);
}
return idx;
#elif defined(USE_NEON)
const size_t simd_width = 4;
uint32x4_t target_vec = vdupq_n_u32(target);
while (idx + simd_width <= size) {
uint32x4_t data_vec = vld1q_u32(doc_ids + idx);
uint32x4_t cmp = vcgeq_u32(data_vec, target_vec);
if (vmaxvq_u32(cmp) != 0) {
for (size_t i = 0; i < simd_width; i++) {
if (doc_ids[idx + i] >= target) {
return idx + i;
}
}
}
idx += simd_width;
}
#endif // USE_AVX512
while (idx < size && doc_ids[idx] < target) {
idx++;
}
return idx;
}
size_t InvertedIndex::findNextLiveSIMD(const uint8_t* values,
size_t size,
size_t start_idx) const
{
size_t idx = start_idx;
#if defined(USE_AVX512)
const size_t simd_width = 64;
__m512i zero_vec = _mm512_setzero_si512();
while (idx + simd_width <= size) {
__m512i data_vec = _mm512_loadu_si512(values + idx);
__mmask64 mask = _mm512_cmpneq_epu8_mask(data_vec, zero_vec);
if (mask != 0) {
return idx + __builtin_ctzll(mask);
}
idx += simd_width;
}
#elif defined(USE_AVX2)
const size_t simd_width = 32;
__m256i zero_vec = _mm256_setzero_si256();
while (idx + simd_width <= size) {
__m256i data_vec =
_mm256_loadu_si256((const __m256i*)(values + idx));
__m256i cmp = _mm256_cmpeq_epi8(data_vec, zero_vec);
int mask = _mm256_movemask_epi8(cmp);
if ((uint32_t)mask != 0xFFFFFFFF) {
return idx + __builtin_ctz(~mask);
}
idx += simd_width;
}
#elif defined(USE_NEON)
const size_t simd_width = 16;
uint8x16_t zero_vec = vdupq_n_u8(0);
while (idx + simd_width <= size) {
uint8x16_t data_vec = vld1q_u8(values + idx);
uint8x16_t cmp = vceqq_u8(data_vec, zero_vec);
if (vminvq_u8(cmp) == 0) {
for (size_t i = 0; i < simd_width; i++) {
if (values[idx + i] != 0) {
return idx + i;
}
}
}
idx += simd_width;
}
#elif defined(USE_SVE2)
svbool_t pg = svwhilelt_b8(idx, size);
while (svptest_any(svptrue_b8(), pg)) {
svuint8_t data_vec = svld1_u8(pg, values + idx);
svbool_t cmp = svcmpne_n_u8(pg, data_vec, 0);
if (svptest_any(pg, cmp)) {
svbool_t before_match = svbrkb_z(pg, cmp);
return idx + svcntp_b8(pg, before_match);
}
idx += svcntb();
pg = svwhilelt_b8(idx, size);
}
return idx;
#endif // USE_AVX512
while (idx < size) {
if (values[idx] != 0) return idx;
idx++;
}
return idx;
}
// =========================================================================
// Superblock helpers
// =========================================================================
bool InvertedIndex::readSuperBlock(MDBX_txn* txn,
SuperBlock* out,
bool* out_found) const {
if (out_found) *out_found = false;
uint64_t packed = packPostingKey(kMetadataTermId, kSuperBlockBlockNr);
MDBX_val key{&packed, sizeof(packed)};
MDBX_val data;
int rc = mdbx_get(txn, blocked_term_postings_dbi_, &key, &data);
if (rc == MDBX_NOTFOUND) {
return true;
}
if (rc != MDBX_SUCCESS) {
LOG_ERROR(2211, index_id_, "readSuperBlock MDBX lookup failed: " << mdbx_strerror(rc));
return false;
}
if (data.iov_len < sizeof(SuperBlock)) {
LOG_ERROR(2212, index_id_, "Corrupt sparse superblock: payload too small");
return false;
}
std::memcpy(out, data.iov_base, sizeof(SuperBlock));
if (out_found) *out_found = true;
return true;
}
bool InvertedIndex::writeSuperBlock(MDBX_txn* txn, const SuperBlock& sb) {
uint64_t packed = packPostingKey(kMetadataTermId, kSuperBlockBlockNr);
MDBX_val key{&packed, sizeof(packed)};
MDBX_val data{const_cast<SuperBlock*>(&sb), sizeof(SuperBlock)};
int rc = mdbx_put(txn, blocked_term_postings_dbi_, &key, &data, MDBX_UPSERT);
if (rc != MDBX_SUCCESS) {
LOG_ERROR(2213, index_id_, "writeSuperBlock MDBX put failed: " << mdbx_strerror(rc));
return false;
}
return true;
}
// =========================================================================
// Metadata and block helpers
// =========================================================================