Repository navigation
Expand file tree
/
Copy pathndd.hpp
More file actions
2283 lines (1953 loc) · 95.9 KB
/
Copy pathndd.hpp
File metadata and controls
2283 lines (1953 loc) · 95.9 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
#pragma once
#include <curl/curl.h>
#include <regex>
#include "hnsw/hnswlib.h"
#include "settings.hpp"
#include "types.hpp"
#include "id_mapper.hpp"
#include "vector_storage.hpp"
#include "../sparse/sparse_storage.hpp"
#include "rand_utils.hpp"
#include "index_meta.hpp"
#include "msgpack_ndd.hpp"
#include "quant_vector.hpp"
#include "wal.hpp"
#include "../quant/dispatch.hpp"
#include <memory>
#include <deque>
#include <unordered_map>
#include <list>
#include <algorithm>
#include <mutex>
#include <shared_mutex>
#include <chrono>
#include <filesystem>
#include <thread>
#include <atomic>
#include <optional>
#include <random>
#include <type_traits>
#include <future>
struct IndexConfig {
size_t dim;
ndd::SparseScoringModel sparse_model = ndd::SparseScoringModel::NONE;
size_t max_elements = settings::MAX_ELEMENTS;
std::string space_type_str;
size_t M = settings::DEFAULT_M;
size_t ef_construction = settings::DEFAULT_EF_CONSTRUCT;
ndd::quant::QuantizationLevel quant_level =
ndd::quant::QuantizationLevel::INT8; // Default to INT8 quantization
const int32_t checksum;
};
struct IndexInfo {
size_t total_elements;
size_t dimension;
ndd::SparseScoringModel sparse_model = ndd::SparseScoringModel::NONE;
std::string space_type_str;
ndd::quant::QuantizationLevel
quant_level; // Selected quantization level
int32_t checksum;
size_t M;
size_t ef_con;
};
struct CacheEntry {
std::string index_id;
ndd::SparseScoringModel sparse_model = ndd::SparseScoringModel::NONE;
std::unique_ptr<hnswlib::HierarchicalNSW<float>> alg;
std::shared_ptr<IDMapper> id_mapper;
std::shared_ptr<VectorStorage> vector_storage;
std::unique_ptr<ndd::SparseVectorStorage> sparse_storage;
std::unique_ptr<WriteAheadLog> wal;
std::chrono::system_clock::time_point last_access;
std::chrono::system_clock::time_point last_saved_at;
std::chrono::system_clock::time_point last_dirtied_at;
/**
* Indicates if the index has unsaved in-memory changes
* is_dirty = true -> the index has not been persisted in storage
*/
bool is_dirty{false};
/**
* cache_valid marks whether this CacheEntry is still the active entry
* for its index_id.
*
* This is needed because the per-thread cache stores weak_ptr<CacheEntry>.
* A weak_ptr only tells us whether the old CacheEntry object is still alive;
* it does not tell us whether that object is still the current entry in
* IndexManager::indices_.
*
* After delete/evict/reload, the old CacheEntry may still remain alive
* because in-flight readers still hold shared_ptr references to it. In that
* window, weak_ptr.lock() can still succeed. cache_valid prevents new lookups
* from reusing that stale entry while allowing existing users of the entry to
* finish safely.
*
* NOTE: This need not be an atomic bool because its a huge performance penalty
* and negligible correctness improvement.
*/
bool cache_valid{true};
/**
* Number of searches performed on this index. For a search with k=10
* it will be 10
*
* NOTE: Since there can be multiple readers hitting the same index,
* there is no guarantee that this number will capture the true searchCount.
* using std::atomics will levy (~10%) performance penalty.
*/
size_t searchCount{0};
/**
* Per-index reader's - writer's operation lock
*
* writers: addVectors, saveIndexInternal, saveIndex, deleteVectors,
* evictIfNeeded, recoverIndex, deleteVectorsByFilter, updateFilters,
* deleteIndex, executeBackupJob
*
* readers: searchKNN, getVector, getIndexInfo (loaded-index path only)
*
* NOTE: std::shared_mutex dont guarantee fairness between
* readers and writers. ie. currently it could be the case that either
* reads or writes can starve if other is being flooded.
*
* TODO: If that is required, we will have to implement a custom reader-writer
* locking mechanism with a ticketing system to guarantee fairness.
*
* XXX: We want readers to work even when writers are happening on an index
* If we use a reader's lock in read path, long running writes will starve
* them. So for now, we are not using readers lock. This doesnt affect
* correctness for now. Access-after-delete errors are handled by making
* CacheEntry a shared_ptr in IndexManager.
* TODO: Revisit the locking mechanism to make it finegrained for performance.
*/
std::shared_mutex operation_mutex;
// Default constructor required for map
CacheEntry() :
last_access(std::chrono::system_clock::now()) {}
CacheEntry(std::string index_id_,
ndd::SparseScoringModel sparse_model_,
std::unique_ptr<hnswlib::HierarchicalNSW<float>> alg_,
std::shared_ptr<IDMapper> mapper_,
std::shared_ptr<VectorStorage> storage_,
std::unique_ptr<ndd::SparseVectorStorage> sparse_storage_,
std::unique_ptr<WriteAheadLog> wal_,
std::chrono::system_clock::time_point access_time_) {
LOG_INFO(2001, index_id_, "Creating cache entry");
// Validate all components
if(!alg_) {
LOG_ERROR(2002, index_id_, "Algorithm is null");
throw std::runtime_error("Algorithm is null");
}
if(!mapper_) {
LOG_ERROR(2003, index_id_, "ID mapper is null");
throw std::runtime_error("ID Mapper is null");
}
if(!storage_) {
LOG_ERROR(2004, index_id_, "Vector storage is null");
throw std::runtime_error("Vector Storage is null");
}
LOG_INFO(2005, index_id_, "Assigning index id");
index_id = std::move(index_id_);
sparse_model = sparse_model_;
id_mapper = std::move(mapper_);
vector_storage = std::move(storage_);
sparse_storage = std::move(sparse_storage_);
wal = std::move(wal_);
last_access = access_time_;
LOG_INFO(2006, index_id, "Moving algorithm instance");
alg = std::move(alg_);
last_saved_at = std::chrono::system_clock::now();
LOG_INFO(2007, index_id, "Cache entry construction completed");
}
void markDirty() {
is_dirty = true;
last_dirtied_at = std::chrono::system_clock::now();
}
void resetSearchCount() { searchCount = 0; }
// Delete copy constructor and assignment
CacheEntry(const CacheEntry&) = delete;
CacheEntry& operator=(const CacheEntry&) = delete;
// Disable move operations since mutex is not movable
CacheEntry(CacheEntry&&) = delete;
CacheEntry& operator=(CacheEntry&&) = delete;
};
struct PersistenceConfig {
size_t save_every_n_updates{settings::SAVE_EVERY_N_UPDATES};
std::chrono::minutes save_interval{settings::SAVE_EVERY_N_MINUTES};
bool save_on_shutdown{true};
};
#include "../storage/backup_store.hpp"
class IndexManager {
private:
std::deque<std::string> indices_list_;
std::unordered_map<std::string, std::shared_ptr<CacheEntry>> indices_;
/**
* This is a thread local store(TLS) for the indices_. ie. hot indices
* need not look at indices_ and take a global lock repeatedly.
* look at getIndexEntry() for more.
*/
inline static thread_local std::unordered_map<std::string, std::weak_ptr<CacheEntry>>
per_thread_indices_;
std::shared_mutex indices_mutex_;
std::string data_dir_;
PersistenceConfig persistence_config_;
std::atomic<bool> shutdown_requested_{false};
std::condition_variable persistence_cv_;
std::unique_ptr<MetadataManager> metadata_manager_;
// Autosave methods
std::thread autosave_thread_;
std::atomic<bool> running_{true};
BackupStore backup_store_;
void executeBackupJob(const std::string& index_id, const std::string& backup_name,
std::stop_token st);
std::unique_ptr<WriteAheadLog> createWAL(const std::string& index_id) {
const std::string wal_dir = data_dir_ + "/" + index_id;
return std::make_unique<WriteAheadLog>(wal_dir, index_id);
}
WriteAheadLog* getOrCreateWAL(CacheEntry& entry) {
if(!entry.wal) {
entry.wal = createWAL(entry.index_id);
}
return entry.wal.get();
}
void clearWAL(CacheEntry& entry) {
getOrCreateWAL(entry)->clear();
}
// Helper method for WAL recovery
void recoverFromWAL(CacheEntry& entry) {
const std::string& index_id = entry.index_id;
WriteAheadLog* wal = getOrCreateWAL(entry);
// Check if WAL has entries needing recovery
if(wal->hasEntries()) {
LOG_INFO(2008, index_id, "WAL recovery needed");
auto wal_entries = wal->readEntries();
LOG_INFO(2009, index_id, "Read " << wal_entries.size() << " entries from WAL");
// Process all entries in the exact order they were recorded
std::vector<idInt> failed_vector_add_ids;
for(const auto& wal_entry : wal_entries) {
try {
if(wal_entry.op_type == WALOperationType::VECTOR_ADD) {
// Check if vector exists in storage before recovering
auto vector_bytes = entry.vector_storage->get_vector(wal_entry.numeric_id);
if(!vector_bytes.empty()) {
entry.alg->addPoint<true>(vector_bytes.data(), wal_entry.numeric_id);
} else {
// Vector doesn't exist - this VECTOR_ADD failed
failed_vector_add_ids.push_back(wal_entry.numeric_id);
LOG_DEBUG("VECTOR_ADD failed for ID " << wal_entry.numeric_id
<< " - adding to deleted_ids");
}
} else if(wal_entry.op_type == WALOperationType::VECTOR_UPDATE) {
// Recover vector update
auto vector_bytes = entry.vector_storage->get_vector(wal_entry.numeric_id);
if(!vector_bytes.empty()) {
entry.alg->addPoint<false>(vector_bytes.data(), wal_entry.numeric_id);
}
} else if(wal_entry.op_type == WALOperationType::VECTOR_DELETE) {
// For deletions, just mark the vector as deleted
entry.alg->markDelete(wal_entry.numeric_id);
}
} catch(const std::exception& e) {
if(wal_entry.op_type == WALOperationType::VECTOR_ADD) {
// If VECTOR_ADD recovery failed, add ID to failed list
failed_vector_add_ids.push_back(wal_entry.numeric_id);
LOG_DEBUG("VECTOR_ADD recovery failed for ID " << wal_entry.numeric_id
<< ": " << e.what());
} else {
LOG_DEBUG("Failed to recover operation for vector " << wal_entry.numeric_id
<< ": " << e.what());
}
}
}
// Add failed VECTOR_ADD IDs back to deleted_ids for reuse
if(!failed_vector_add_ids.empty()) {
entry.id_mapper->reclaim_failed_ids(failed_vector_add_ids);
LOG_INFO(2010,
index_id,
"Reclaimed " << failed_vector_add_ids.size()
<< " failed VECTOR_ADD ids for reuse");
}
// Mark as dirty to trigger a save
entry.markDirty();
// Explicitly save the index after recovery
LOG_DEBUG("Saving index after WAL recovery: " << index_id);
// Save index will also clear the WAL and save bloom filter
// FIX: Call saveIndexInternal instead of saveIndex to avoid circular lock
saveIndexInternal(entry);
}
}
// The thread will call this method
void autosaveLoop() {
LOG_INFO(2011, "Autosave thread started");
while(running_) {
// Sleep for AUTOSAVE_SLEEP_MINUTES
std::this_thread::sleep_for(std::chrono::minutes(settings::AUTOSAVE_SLEEP_MINUTES));
// Check if we're still running
if(!running_) {
break;
}
LOG_INFO(2012, "Autosave check running");
checkAndSaveIndices();
}
LOG_INFO(2013, "Autosave thread stopped");
}
// Check and save indices based on when they were last dirtied
void checkAndSaveIndices() {
std::vector<std::string> indices_to_save;
auto now = std::chrono::system_clock::now();
/**
* Identify the dirty indices without holding indices_mutex_ for too long
*/
{
std::shared_lock<std::shared_mutex> read_lock(indices_mutex_);
for(const auto& [index_id, entry] : indices_) {
if(entry && entry->is_dirty) {
auto time_since_dirtied = now - entry->last_dirtied_at;
// Save if more than SAVE_EVERY_N_MINUTES minutes since the last mutation
if(time_since_dirtied
> std::chrono::minutes(settings::SAVE_EVERY_N_MINUTES)) {
indices_to_save.push_back(index_id);
}
}
}
}
/* Write each dirty index back */
for(const auto& index_id : indices_to_save) {
bool should_save = false;
{
std::shared_lock<std::shared_mutex> read_lock(indices_mutex_);
auto it = indices_.find(index_id);
should_save = (it != indices_.end() && it->second && it->second->is_dirty);
}
if(should_save) {
LOG_DEBUG("Auto-saving index (60-minute threshold): " << index_id);
saveIndex(index_id);
}
}
}
/**
* Returns the CacheEntry if it is resident in memory.
*/
std::shared_ptr<CacheEntry> findInMemoryIndexEntry(const std::string& index_id) {
/**
* First check the entry in thread local storage (TLS)
* indices_ will be referred only if:
* 1. index_id is not found
* 2. entry is not pointing to a valid shared_ptr
* 3. entry is pointing to a valid shared_ptr but cache_valid == false
*/
auto cached_it = per_thread_indices_.find(index_id);
if(cached_it != per_thread_indices_.end()) {
auto entry = cached_it->second.lock();
if(entry && entry->cache_valid) {
return entry;
}
per_thread_indices_.erase(cached_it);
}
/**
* Second check if this index is in global indices_.
* A read lock on indices_mutex_ is enough for this.
*/
std::shared_lock<std::shared_mutex> read_lock(indices_mutex_);
auto it = indices_.find(index_id);
if(it == indices_.end() || !it->second || !it->second->cache_valid) {
return nullptr;
}
//update TLS indices_
auto entry = it->second;
per_thread_indices_[index_id] = entry;
return entry;
}
/**
* Returns the shared_ptr to CacheEntry
* 1. If Index is active (in-memory), return from there
* 2. Else, fetch from disk, make active and then return.
*/
std::shared_ptr<CacheEntry> getIndexEntry(const std::string& index_id) {
if(auto entry = findInMemoryIndexEntry(index_id)) {
return entry;
}
/**
* Index not found in memory.
* Hold a write lock on indices_mutex_ and fetch it from disk
*/
{
std::unique_lock<std::shared_mutex> write_lock(indices_mutex_);
auto it = indices_.find(index_id);
if(it == indices_.end()) {
ensureLiveIndexCapacity(index_id, "load index");
loadIndex(index_id); // modifies indices_
}
it = indices_.find(index_id);
if(it == indices_.end()) {
throw std::runtime_error("[ERROR] Index " + index_id + " doesnt exist.");
}
auto entry = it->second;
per_thread_indices_[index_id] = entry;
return entry;
}
}
void saveIndex(const std::string& index_id) {
LOG_DEBUG("saveIndex called for index=" + index_id);
// Get the index entry (thread-safe)
auto entry = getIndexEntry(index_id);
// Use per-index operation mutex to prevent concurrent operations
std::unique_lock<std::shared_mutex> operation_lock(entry->operation_mutex);
// Call internal implementation
saveIndexInternal(*entry);
}
private:
// Internal saveIndex implementation that doesn't call getIndexEntry
// Used by functions that already have the entry and mutex
void saveIndexInternal(CacheEntry& entry) {
// Double check if the index is still dirty
if(!entry.is_dirty) {
return;
}
LOG_DEBUG("Saving index " << entry.index_id);
// Auto-resize check
size_t remainingCapacity = entry.alg->getRemainingCapacity();
LOG_DEBUG("Remaining capacity for index " << entry.index_id << ": " << remainingCapacity);
size_t maxElements = entry.alg->getMaxElements();
LOG_DEBUG("Max elements for index " << entry.index_id << ": " << maxElements);
// If remaining capacity is less than 50k, resize by adding 100k
if(remainingCapacity < settings::MAX_ELEMENTS_INCREMENT_TRIGGER) {
size_t newMaxElements = maxElements + settings::MAX_ELEMENTS_INCREMENT;
LOG_DEBUG("Auto-resizing index " << entry.index_id << " from " << maxElements << " to "
<< newMaxElements << " elements");
try {
entry.alg->resizeIndex(newMaxElements);
} catch(const std::exception& e) {
LOG_DEBUG("Failed to auto-resize index: " << e.what());
// Continue with saving even if resize fails
}
}
std::string index_dir = data_dir_ + "/" + entry.index_id;
std::string vector_storage_dir = index_dir + "/vectors";
std::string index_path = vector_storage_dir + "/" + settings::DEFAULT_SUBINDEX + ".idx";
std::string temp_path = index_path + ".tmp";
entry.alg->saveIndex(temp_path);
std::filesystem::rename(temp_path, index_path);
// Clear the WAL
clearWAL(entry);
// Update element count in metadata
if(!metadata_manager_->updateElementCount(entry.index_id, entry.alg->getElementsCount())) {
LOG_WARN(
2014, entry.index_id, "Failed to update element count in metadata");
}
entry.is_dirty = false;
}
public:
/**
* TODO:
* This function is currently triggered by:
* 1.
* 2.
*
* For more look at docs/memory_management.md
*/
void evictIfNeeded() {
size_t max_attempts = std::max(indices_list_.size(), indices_.size());
while(indices_.size() >= settings::MAX_LIVE_INDICES && max_attempts > 0) {
if(indices_list_.empty()) {
LOG_ERROR(2048, "Cannot evict index: indices_list_ is empty while cache is full");
return;
}
std::string to_evict = indices_list_.back();
auto it = indices_.find(to_evict);
if(it == indices_.end()) {
LOG_WARN(2049, to_evict, "Dropping stale eviction candidate from indices_list_");
indices_list_.pop_back();
--max_attempts;
continue;
}
try {
auto entry = it->second;
std::unique_lock<std::shared_mutex> operation_lock(entry->operation_mutex);
if(entry->is_dirty) {
LOG_INFO(2050, to_evict, "Saving dirty index before eviction");
saveIndexInternal(*entry);
}
} catch(const std::exception& e) {
LOG_ERROR(2051, to_evict, "Failed to save dirty index during eviction: " << e.what());
return;
}
if(it->second->is_dirty) {
LOG_WARN(2054, to_evict, "Index remained dirty after forced save; aborting eviction");
return;
}
LOG_INFO(2016, to_evict, "Evicting clean index from cache");
it->second->cache_valid = false;
indices_.erase(it);
indices_list_.pop_back();
--max_attempts;
}
if(indices_.size() >= settings::MAX_LIVE_INDICES) {
LOG_ERROR(2052,
"Eviction attempts exhausted while live index cache remains at limit");
}
}
void ensureLiveIndexCapacity(const std::string& index_id, const char* action) {
if(indices_.size() < settings::MAX_LIVE_INDICES) {
return;
}
evictIfNeeded();
if(indices_.size() >= settings::MAX_LIVE_INDICES) {
LOG_ERROR(2047,
index_id,
"Unable to " << action << ": live index cache remains at limit "
<< settings::MAX_LIVE_INDICES);
throw std::runtime_error("Unable to " + std::string(action)
+ ": live index cache is full");
}
}
std::string getUserPath(const std::string& username) { return data_dir_ + "/" + username; }
std::string getIndexPath(const std::string& username, const std::string& index_name) {
return getUserPath(username) + "/" + index_name;
}
public:
IndexManager(const std::string& data_dir,
const PersistenceConfig& persistence_config = PersistenceConfig{}) :
data_dir_(data_dir),
persistence_config_(persistence_config),
backup_store_(data_dir) {
std::filesystem::create_directories(data_dir);
metadata_manager_ = std::make_unique<MetadataManager>(data_dir);
// Start the autosave thread
autosave_thread_ = std::thread(&IndexManager::autosaveLoop, this);
}
~IndexManager() {
// Signal all threads to stop (running_ is checked by autosave and backup threads)
running_ = false;
// Join background backup threads before destroying members
// (prevents use-after-free when detached threads outlive IndexManager)
backup_store_.joinAllThreads();
/**
* Don't wait for autosave thread to exit.
* Since the thread might be sleeping, waiting for join
* would be time consuming.
*
* TODO: This is a stop-gap solution.
* Fix it with conditional variables.
*/
if(autosave_thread_.joinable()) {
autosave_thread_.detach();
}
/**
* Persist all the dirty indices to disk.
*/
if(persistence_config_.save_on_shutdown) {
shutdown_requested_ = true;
persistence_cv_.notify_all();
LOG_INFO("Saving indices during shutdown");
std::vector<std::string> indices_to_save;
{
std::shared_lock<std::shared_mutex> read_lock(indices_mutex_);
for(const auto& pair : indices_) {
if(pair.second && pair.second->is_dirty) {
indices_to_save.push_back(pair.first);
}
}
}
for(const auto& index_id : indices_to_save) {
try {
LOG_INFO(2017, index_id, "Saving dirty index during shutdown");
saveIndex(index_id);
} catch(const std::exception& e) {
LOG_ERROR(2015,
index_id,
"Failed to save index during shutdown: " << e.what());
}
}
LOG_INFO("Shutdown complete");
}
}
// Reset the index file. It does not affect the LMDB or metadata.
// This is used when the index is corrupted or needs to be reset.
bool resetIndex(const std::string& index_id, const IndexConfig& config) {
std::string base_path = data_dir_ + "/" + index_id;
std::string vector_storage_dir = base_path + "/vectors";
std::string index_path = vector_storage_dir + "/" + settings::DEFAULT_SUBINDEX + ".idx";
LOG_DEBUG(index_path);
std::string recover_file = base_path + "/recover.txt";
LOG_DEBUG(recover_file);
// 1. Fail if directory doesn't exist
if(!std::filesystem::exists(base_path)) {
LOG_ERROR(2018, index_id, "Index directory does not exist: " << base_path);
return false;
}
// 2. Fail if index file already exists
if(std::filesystem::exists(index_path)) {
LOG_ERROR(2019, index_id, "Index file already exists: " << index_path);
return false;
}
// 3. Create and save empty HNSW index
auto space_type = hnswlib::getSpaceType(config.space_type_str);
ndd::quant::QuantizationLevel quant_level = config.quant_level;
hnswlib::HierarchicalNSW<float> hnsw(config.max_elements,
space_type,
config.dim,
config.M,
config.ef_construction,
settings::RANDOM_SEED,
quant_level,
config.checksum);
hnsw.saveIndex(index_path);
// 4. Write recover.txt with "0:0"
std::ofstream fout(recover_file);
fout << "0:0\n";
fout.close();
LOG_INFO(2020, index_id, "Index reset complete and saved");
return true;
}
bool createIndex(const std::string& index_id,
const IndexConfig& config,
UserType user_type = UserType::Admin,
size_t size_in_millions = 0) {
// Get username and index name from index_id
auto pos = index_id.find('/');
if(pos == std::string::npos) {
throw std::runtime_error("Invalid index ID");
}
std::string index_dir = data_dir_ + "/" + index_id;
std::string username = index_id.substr(0, pos);
std::string index_name = index_id.substr(pos + 1);
// Check if index already exists in metadata
auto existing_indices = metadata_manager_->listUserIndexes(username);
for(const auto& existing : existing_indices) {
if(existing.first == index_name) {
throw std::runtime_error("Index with this name already exists for this user");
}
}
// Validate max_elements against user limits (unless admin with custom size)
size_t max_vectors_allowed = getMaxVectorsPerIndex(user_type);
if(user_type != UserType::Admin || size_in_millions == 0) {
if(config.max_elements > max_vectors_allowed) {
throw std::runtime_error("Index size " + std::to_string(config.max_elements)
+ " exceeds limit of "
+ std::to_string(max_vectors_allowed) + " vectors for "
+ userTypeToString(user_type) + " users");
}
}
// Check file system without lock
std::string vector_storage_dir = index_dir + "/vectors";
std::string index_path = vector_storage_dir + "/" + settings::DEFAULT_SUBINDEX + ".idx";
if(std::filesystem::exists(index_path)) {
throw std::runtime_error("Index already exists");
}
// Evict if needed (clean indices only)
{
std::unique_lock<std::shared_mutex> temp_lock(indices_mutex_);
ensureLiveIndexCapacity(index_id, "create index");
}
hnswlib::SpaceType space_type = hnswlib::getSpaceType(config.space_type_str);
std::string lmdb_dir = index_dir + "/ids";
//create the directory and initialize sequence for IDMapper
LOG_INFO(2021,
index_id,
"Creating ID mapper with user type " << userTypeToString(user_type));
// IDMapper now uses tier-based fixed bloom filter sizing based on user_type
auto id_mapper = std::make_shared<IDMapper>(lmdb_dir, true, user_type);
// Create HNSW directly with all necessary parameters
ndd::quant::QuantizationLevel quant_level = config.quant_level;
auto vector_storage =
std::make_shared<VectorStorage>(index_dir, index_id, config.dim, config.quant_level);
// Initialize Sparse Storage if needed
std::unique_ptr<ndd::SparseVectorStorage> sparse_storage = nullptr;
if(ndd::sparseModelEnabled(config.sparse_model)) {
std::string sparse_storage_dir = index_dir + "/sparse";
sparse_storage = std::make_unique<ndd::SparseVectorStorage>(
sparse_storage_dir, index_id, config.sparse_model);
if(!sparse_storage->initialize()) {
throw std::runtime_error("Failed to initialize sparse storage");
}
}
auto alg = std::make_unique<hnswlib::HierarchicalNSW<float>>(config.max_elements,
space_type,
config.dim,
config.M,
config.ef_construction,
settings::RANDOM_SEED,
quant_level,
config.checksum);
alg->setVectorFetcher([vs = vector_storage](ndd::idInt label, uint8_t* buffer) {
return vs->get_vector(label, buffer);
});
alg->setVectorFetcherBatch([vs = vector_storage](const ndd::idInt* labels, uint8_t* buffers, bool* success, size_t count) -> size_t {
return vs->get_vectors_batch_into(labels, buffers, success, count);
});
auto wal = createWAL(index_id);
// Add to indices with minimal lock scope
{
std::unique_lock<std::shared_mutex> lock(indices_mutex_);
auto entry = std::make_shared<CacheEntry>(index_id,
config.sparse_model,
std::move(alg),
id_mapper,
vector_storage,
std::move(sparse_storage),
std::move(wal),
std::chrono::system_clock::now());
auto [it, inserted] = indices_.emplace(index_id, entry);
it->second->markDirty();
indices_list_.push_front(index_id);
}
// Create and store index metadata
IndexMetadata metadata_entry;
metadata_entry.name = index_name;
metadata_entry.dimension = config.dim;
metadata_entry.sparse_model = config.sparse_model;
metadata_entry.space_type_str = config.space_type_str;
metadata_entry.quant_level = config.quant_level;
metadata_entry.checksum = config.checksum;
metadata_entry.total_elements = 0;
metadata_entry.M = config.M;
metadata_entry.ef_con = config.ef_construction;
metadata_entry.created_at = std::chrono::system_clock::now();
if(!metadata_manager_->storeMetadata(index_id, metadata_entry)) {
throw std::runtime_error("Failed to store index metadata");
}
LOG_INFO(2022, index_id, "Saving newly created index");
// Index is marked dirty so it needs to be saved immediately for crash recovery
saveIndex(index_id);
return true;
}
std::vector<std::pair<std::string, IndexMetadata>>
listUserIndexes(const std::string& username) {
// Use the metadata manager directly to get the list of indexes
return metadata_manager_->listUserIndexes(username);
}
std::vector<std::pair<std::string, IndexMetadata>> listAllIndexes() {
// Use the metadata manager directly to get the list of indexes
return metadata_manager_->listAllIndexes();
}
void loadIndex(const std::string& index_id) {
std::string index_dir = data_dir_ + "/" + index_id;
std::string lmdb_dir = index_dir + "/ids";
std::string vector_storage_dir = index_dir + "/vectors";
std::string index_path = vector_storage_dir + "/" + settings::DEFAULT_SUBINDEX + ".idx";
if(!std::filesystem::exists(index_path) || !std::filesystem::exists(lmdb_dir)
|| !std::filesystem::exists(vector_storage_dir)) {
throw std::runtime_error("Required files missing for index: " + index_id);
}
// Load metadata to get sparse_model
auto metadata = metadata_manager_->getMetadata(index_id);
if(!metadata) {
throw std::runtime_error("Missing or incompatible index metadata for index: "
+ index_id);
}
const ndd::SparseScoringModel sparse_model = metadata->sparse_model;
// Step 1: Load HNSW index (automatically adjusts cache based on element count and cache
// percentage)
std::unique_ptr<hnswlib::HierarchicalNSW<float>> alg;
try {
alg = std::make_unique<hnswlib::HierarchicalNSW<float>>(index_path, 0);
} catch(const std::exception& e) {
throw std::runtime_error("Cannot load index '" + index_id + "': " + e.what());
}
// Step 2: Create IDMapper and VectorStorage - IDMapper handles bloom filter initialization
auto id_mapper = std::make_shared<IDMapper>(lmdb_dir, false);
auto vector_storage = std::make_shared<VectorStorage>(
index_dir, index_id, alg->getDimension(), alg->getQuantLevel());
// Initialize Sparse Storage if sparse_model is enabled
std::unique_ptr<ndd::SparseVectorStorage> sparse_storage;
if(ndd::sparseModelEnabled(sparse_model)) {
std::string sparse_storage_dir = index_dir + "/sparse";
sparse_storage = std::make_unique<ndd::SparseVectorStorage>(
sparse_storage_dir, index_id, sparse_model);
if(!sparse_storage->initialize()) {
throw std::runtime_error("Failed to initialize sparse storage for index: "
+ index_id);
}
}
// Set up vector fetcher
alg->setVectorFetcher([vs = vector_storage](ndd::idInt label, uint8_t* buffer) {
return vs->get_vector(label, buffer);
});
alg->setVectorFetcherBatch([vs = vector_storage](const ndd::idInt* labels, uint8_t* buffers, bool* success, size_t count) -> size_t {
return vs->get_vectors_batch_into(labels, buffers, success, count);
});
auto wal = createWAL(index_id);
LOG_DEBUG("Loaded index: " << index_id);
LOG_DEBUG("Created space for index: " << index_id);
// Step 3: Update cache entry so that index becomes available to other threads
auto entry = std::make_shared<CacheEntry>(index_id,
sparse_model,
std::move(alg),
id_mapper,
vector_storage,
std::move(sparse_storage),
std::move(wal),
std::chrono::system_clock::now());
auto [it, inserted] = indices_.emplace(index_id, entry);
indices_list_.push_front(index_id);
// Handle WAL recovery using the IndexManager's method
recoverFromWAL(*it->second);
}
// Reload index: save (if dirty), evict from memory, and reload
// Cache size is automatically checked and adjusted if < 5% of element count during reload
bool reload(const std::string& index_id) {
LOG_INFO(2023, index_id, "Starting reload");
try {
// Phase 1: Save index if it is dirty
{
std::shared_lock<std::shared_mutex> lock(indices_mutex_);
auto it = indices_.find(index_id);
if(it != indices_.end() && it->second && it->second->is_dirty) {
LOG_INFO(2055, index_id, "Saving dirty index before reload");
saveIndex(index_id);
}
}
// Phase 2: Evict from memory
{
std::unique_lock<std::shared_mutex> lock(indices_mutex_);
auto it = indices_.find(index_id);
if(it != indices_.end()) {
// Remove from LRU list
auto list_it = std::find(indices_list_.begin(), indices_list_.end(), index_id);
if(list_it != indices_list_.end()) {
indices_list_.erase(list_it);
}
it->second->cache_valid = false;
indices_.erase(it);
LOG_INFO(2024, index_id, "Evicted index from cache");
}
}
// Phase 3: Reload (cache adjustment happens automatically in loadIndex)
{
std::unique_lock<std::shared_mutex> lock(indices_mutex_);
loadIndex(index_id);
}
// Phase 4: Report final state
{
std::shared_lock<std::shared_mutex> lock(indices_mutex_);
auto it = indices_.find(index_id);
if(it != indices_.end()) {
// Cache removed
LOG_INFO(2025,
index_id,
"Reloaded index with "
<< it->second->alg->getElementsCount() << " elements");
}
}
return true;
} catch(const std::exception& e) {
LOG_ERROR(2026, index_id, "Failed to reload index: " << e.what());
return false;
}
}
// Add this new function to reload just the algorithm part while preserving the CacheEntry
void reloadIndex(const std::string& index_id) {
std::shared_ptr<CacheEntry> entry;
{
std::shared_lock<std::shared_mutex> read_lock(indices_mutex_);
auto it = indices_.find(index_id);
if(it == indices_.end()) {
return; // Index not in cache
}
entry = it->second;
}
std::string index_dir = data_dir_ + "/" + entry->index_id;
std::string vector_storage_dir = index_dir + "/vectors";
std::string index_path = vector_storage_dir + "/" + settings::DEFAULT_SUBINDEX + ".idx";
// Create a new HNSW algorithm object from the saved file
auto new_alg = std::make_unique<hnswlib::HierarchicalNSW<float>>(index_path, 0);
// Set the vector fetcher to use our storage
new_alg->setVectorFetcher([vs = entry->vector_storage](ndd::idInt label, uint8_t* buffer) {
return vs->get_vector(label, buffer);
});
new_alg->setVectorFetcherBatch([vs = entry->vector_storage](const ndd::idInt* labels, uint8_t* buffers, bool* success, size_t count) -> size_t {
return vs->get_vectors_batch_into(labels, buffers, success, count);
});
// Replace the algorithm in the existing entry
entry->alg = std::move(new_alg);
}
template <typename VectorType>
bool addVectors(const std::string& index_id, const std::vector<VectorType>& vectors) {
try {
// Get the index entry (loads if needed, handles all locking)
auto entry_ptr = getIndexEntry(index_id);
auto& entry = *entry_ptr;
// Use per-index operation mutex to prevent concurrent operations
std::unique_lock<std::shared_mutex> operation_lock(entry.operation_mutex);