From b2a5061389d1f51c0f6496c5498ccb01c183e607 Mon Sep 17 00:00:00 2001 From: Dmitry Razdoburdin Date: Wed, 25 Nov 2026 04:05:04 -0800 Subject: [PATCH 1/6] initial --- include/svs/concurrent/consolidate.h | 60 +++- include/svs/concurrent/dynamic_index.h | 374 ++++++++++++++------- include/svs/concurrent/graph.h | 36 +- include/svs/concurrent/reverse_edges.h | 1 + include/svs/concurrent/vamana_build.h | 4 +- include/svs/core/compact.h | 20 ++ include/svs/core/data/simple.h | 11 + include/svs/orchestrators/dynamic_vamana.h | 39 +++ 8 files changed, 406 insertions(+), 139 deletions(-) diff --git a/include/svs/concurrent/consolidate.h b/include/svs/concurrent/consolidate.h index 1ba9639c1..87268a986 100644 --- a/include/svs/concurrent/consolidate.h +++ b/include/svs/concurrent/consolidate.h @@ -23,6 +23,7 @@ #include "svs/index/vamana/consolidate.h" #include "svs/index/vamana/extensions.h" #include "svs/lib/array.h" +#include "svs/lib/misc.h" #include "svs/lib/threads.h" #include "svs/lib/timing.h" @@ -118,10 +119,14 @@ class GraphConsolidator { /// will contain the full set of neighbor candidate indices. /// @param neighbors The current neighbors of the vertex being processed. /// @param is_deleted Callable functor returning `true` of a vertex is deleted. + /// @param eligible Callable functor returning `true` if a vertex may get a new edge. /// - template + template void populate_candidates( - set_type& all_candidates, const Neighbors& neighbors, const Deleted& is_deleted + set_type& all_candidates, + const Neighbors& neighbors, + const Deleted& is_deleted, + const Eligible& eligible ) const { all_candidates.clear(); for (auto dst : neighbors) { @@ -135,7 +140,13 @@ class GraphConsolidator { continue; } const auto& others = graph_.get_node(dst); - all_candidates.insert(others.begin(), others.end()); + // A new neighbor must be eligible: another consolidation may + // already have collected the in-neighbors of a Deleted one. + for (auto other : others) { + if (eligible(other)) { + all_candidates.insert(other); + } + } if (graph_.seq_counters()[dst].read_validate(*maybe_seq)) { break; } @@ -171,12 +182,13 @@ class GraphConsolidator { std::sort(valid_candidates.begin(), valid_candidates.end(), Compare{}); } - template + template void generate_updates( const GlobalIds& global_ids, const threads::UnitRange& local_ids, ConsolidateThreadLocal& tls, - const Deleted& is_deleted + const Deleted& is_deleted, + const Eligible& eligible ) const { auto& [all_candidates, valid_candidates, final_candidates] = tls; @@ -200,7 +212,7 @@ class GraphConsolidator { } // Other nodes still use seqlock validation in populate_candidates(). - populate_candidates(all_candidates, neighbors, is_deleted); + populate_candidates(all_candidates, neighbors, is_deleted, eligible); filter_candidates( valid_candidates, all_candidates, @@ -224,7 +236,9 @@ class GraphConsolidator { lib::as_const_span(valid_candidates), final_candidates ); - graph_.replace_node(src, lib::as_const_span(final_candidates), node_lock); + graph_.replace_node( + src, lib::as_const_span(final_candidates), node_lock, eligible + ); } } @@ -260,8 +274,12 @@ class GraphConsolidator { /// /// Update an explicit list of source nodes `work_ids`. /// - template - void run_driver(const std::vector& work_ids, const Deleted& is_deleted) { + template + void run_driver( + const std::vector& work_ids, + const Deleted& is_deleted, + const Eligible& eligible + ) { const size_t num_work = work_ids.size(); const size_t update_batch_size = std::min(params_.update_batch_size, num_work); const size_t thread_batch_size = 500; @@ -284,7 +302,8 @@ class GraphConsolidator { global_ids, threads::UnitRange(local_ids), thread_local_scratch, - is_deleted + is_deleted, + eligible ); } ); @@ -296,12 +315,15 @@ class GraphConsolidator { /// /// Reverse-edge-driven consolidation: process only the in-neighbors of the deleted /// nodes `deleted_ids`, discovered via the graph's reverse-edge index. + /// `eligible` returns `true` if a vertex may get a new edge. /// - template - void operator()(const DeletedSet& deleted_ids, const Deleted& is_deleted) { + template + void operator()( + const DeletedSet& deleted_ids, const Deleted& is_deleted, const Eligible& eligible + ) { auto work_ids = gather_work_set(deleted_ids, is_deleted); assert(int(work_ids.size()) > -1); - run_driver(work_ids, is_deleted); + run_driver(work_ids, is_deleted, eligible); } /// @@ -331,7 +353,8 @@ class GraphConsolidator { global_ids, threads::UnitRange(local_ids), thread_local_scratch, - is_deleted + is_deleted, + lib::ReturnsTrueType{} ); } ); @@ -366,6 +389,7 @@ void consolidate( /// /// Reverse-edge-driven consolidation over an explicit deleted set `deleted_ids`. Requires /// `graph.reverse_edges() != nullptr`; only the in-neighbors of `deleted_ids` are visited. +/// `eligible` returns `true` if a vertex may get a new edge. /// template < graphs::MemoryGraph Graph, @@ -373,7 +397,8 @@ template < threads::ThreadPool Pool, typename Distance, typename DeletedSet, - typename Deleted> + typename Deleted, + typename Eligible> void consolidate( Graph& graph, const Data& data, @@ -383,11 +408,12 @@ void consolidate( float alpha, const Distance& distance, const DeletedSet& deleted_ids, - Deleted&& is_deleted + Deleted&& is_deleted, + const Eligible& eligible ) { ConsolidationParameters params{200'000, prune_to, max_candidate_pool_size, alpha}; auto consolidator = GraphConsolidator{graph, data, threadpool, distance, params}; - consolidator(deleted_ids, is_deleted); + consolidator(deleted_ids, is_deleted, eligible); } } // namespace svs::index::vamana::concurrent diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index 1fc1a8980..1dc85f3e1 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -17,14 +17,18 @@ #pragma once // stdlib +#include #include #include #include #include #include +#include +#include #include #include #include +#include #include // Include the flat index to spin-up exhaustive searches on demand. @@ -1042,6 +1046,21 @@ class MutableVamanaIndex { ///// Mutable Interface + private: + // Whether `id` may get a new edge. A Deleted or Empty slot may not: a consolidation + // may already have collected its in-neighbors. + auto linkable(Idx anchor) { + return [this, anchor](Idx id) { + if (id == anchor) { + return true; // routing anchor is retained until exclusive compact() + } + auto state = + std::atomic_ref(status_[id]).load(std::memory_order_acquire); + return state == SlotMetadata::Valid || state == SlotMetadata::Pending; + }; + } + + public: template void copy_points(const Points& points, const std::vector& slots) { assert(points.size() == slots.size()); @@ -1189,6 +1208,8 @@ class MutableVamanaIndex { } catch (...) { // Release the reserved slots back to Empty. for (auto s : slots) { + // An Empty slot has an empty list. A grown slot holds garbage. + graph_.clear_node(lib::narrow_cast(s)); std::atomic_ref(status_[s]) .store(SlotMetadata::Empty, std::memory_order_release); } @@ -1251,14 +1272,7 @@ class MutableVamanaIndex { auto sp = get_search_parameters(); auto prefetch_parameters = GreedySearchPrefetchParameters{sp.prefetch_lookahead_, sp.prefetch_step_}; - auto eligible = [this, seed](Idx id) { - if (id == seed) { - return true; // routing anchor is retained until exclusive compact() - } - auto state = std::atomic_ref(status_[id]) - .load(std::memory_order_acquire); - return state == SlotMetadata::Valid || state == SlotMetadata::Pending; - }; + auto eligible = linkable(seed); std::vector pending_candidates; if (single_insert) { // Snapshot BEFORE graph search. An insertion that already left the @@ -1314,7 +1328,13 @@ class MutableVamanaIndex { /// Delete consolidation performs the actual removal of deleted entries from the /// graph. /// - template size_t delete_entries(const T& ids) { + /// @param ids External IDs to delete. Missing or already deleted IDs are skipped. + /// @param internal_ids If not null, the internal ID of each entry deleted by this + /// call is appended. Keep them for `compact(ids)`: after `consolidate()` the + /// external ID is gone and can no longer be translated. + /// + template + size_t delete_entries(const T& ids, std::vector* internal_ids = nullptr) { auto compact_lock = lock_storage_shared(); std::shared_lock lock{*translator_mutex_}; size_t deleted = 0; @@ -1328,6 +1348,9 @@ class MutableVamanaIndex { } delete_entry(internal); ++deleted; + if (internal_ids != nullptr) { + internal_ids->push_back(lib::narrow_cast(internal)); + } } // Don't erase translator entries here — concurrent search may still // need them for translate_to_external(). Cleanup happens in @@ -1393,16 +1416,9 @@ class MutableVamanaIndex { return indices; } - /// - /// @brief Compact the data and the graph. - /// - /// @param batch_size Granularity at which points are shuffled. Setting this higher can - /// improve performance but requires more working memory. - /// - void compact(Idx batch_size = 1'000) { - std::lock_guard gatekeeper_lock{*compact_gatekeeper_}; - std::lock_guard compact_lock{*compact_mutex_}; - + private: + // The caller holds compact_mutex_ exclusive. + void retire_deleted_anchor() { // All users of the old anchor have drained. A live medoid can now be // selected without a candidate-lifetime race or a Pending-slot scan. const Idx anchor = entry_point(); @@ -1419,97 +1435,194 @@ class MutableVamanaIndex { std::atomic_ref(entry_point_[0]) .store(successor, std::memory_order_release); } + } + + public: + /// + /// @brief Move slots from the end into the listed empty slots, then shrink. + /// + /// Listed Deleted slots are consolidated first. A deleted entry point is + /// replaced by a new medoid, old entry point is consolidated. + /// Other listed slots are skipped. + /// + /// @param ids Internal IDs. An ID outside the index throws. + /// `delete_entries()` can report them. + /// + template void compact(Ids&& ids) { + std::lock_guard gatekeeper_lock{*compact_gatekeeper_}; + std::lock_guard compact_lock{*compact_mutex_}; + + const size_t num_slots = status_.size(); + auto listed = std::set{}; + auto deleted = tsl::robin_set{}; + for (auto i : ids) { + const auto id = static_cast(i); + if (id >= num_slots) { + throw ANNEXCEPTION( + "Internal ID {} is out of range: the index has {} slots!", id, num_slots + ); + } + if (status_[id] != SlotMetadata::Valid) + listed.insert(lib::narrow_cast(id)); + + if (is_deleted(id)) + deleted.insert(lib::narrow_cast(id)); + } + + if (listed.empty()) + return; + + // Process entry point + const Idx old_anchor = entry_point(); + retire_deleted_anchor(); + const Idx new_anchor = entry_point(); + if (old_anchor != new_anchor) { + // Entry point was moved. + // Consolidate the old one + deleted.insert(old_anchor); + } + + if (!deleted.empty()) + consolidate_locked(deleted); + + auto it = listed.begin(); + while (it != listed.end()) { + if ((*first_empty_ == *it) && (*first_reusable_ == *it)) { + first_empty_->store(*it + 1, std::memory_order_release); + first_reusable_->store(*it + 1, std::memory_order_release); + it++; + } else { + break; + } + } + + compact_locked(listed); + } + + /// + /// @brief Compact the data and the graph. + /// + /// @param batch_size Not used. Kept so that existing calls still compile. + /// + void compact([[maybe_unused]] Idx batch_size = 1'000) { + std::lock_guard gatekeeper_lock{*compact_gatekeeper_}; + std::lock_guard compact_lock{*compact_mutex_}; + + retire_deleted_anchor(); + + auto deleted = tsl::robin_set{}; + for (size_t i = 0, imax = status_.size(); i < imax; ++i) { + if (status_[i] == SlotMetadata::Deleted) { + deleted.insert(lib::narrow_cast(i)); + } + } // Consolidate first, under the same exclusive lock. This folds any // outstanding soft-deletes (including the old anchor) into the graph. - consolidate_locked(); - compact_locked(batch_size); + consolidate_locked(deleted); + // Deleted slots are Empty now. The walk reads them lazily, nothing is stored. + auto is_empty = [this](Idx i) { return status_[i] == SlotMetadata::Empty; }; + auto ids_empty = std::views::iota(Idx{0}, lib::narrow_cast(status_.size())) | + std::views::filter(is_empty); + compact_locked(ids_empty); + // No Empty slots are left. + first_empty_->store(status_.size(), std::memory_order_release); + first_reusable_->store(status_.size(), std::memory_order_release); } /// @brief Check if the index has been consolidated. /// @remarks compact() always call consolidate_locked(), this query always returns true. bool is_consolidated() const noexcept { return true; } - // Body of compact() with no compact_mutex_ locking. The caller MUST hold - // compact_mutex_ exclusive - void compact_locked(Idx batch_size = 1'000) { - // The graph is fully remapped below; every reverse-edge entry would be stale. - // Suppress recording during the remap and rebuild from the final graph at the end. - if (auto* re = graph_.reverse_edges()) { - re->set_recording(false); + private: + // The caller must hold compact_mutex_ exclusive and call retire_deleted_anchor() + // first. `ids_empty` holds Empty slots in increasing order. The lowest ones are + // filled with slots from the end, then the index shrinks. + template void compact_locked(Ids&& ids_empty) { + assert(std::ranges::is_sorted(ids_empty)); + // Slots below new_size keep their ID. A slot at or above it moves into a hole + // or is dropped. new_ids maps each moved slot to its hole. + auto moves = std::vector>{}; + auto new_ids = tsl::robin_map{}; + size_t new_size = status_.size(); + auto id_empty = std::ranges::begin(ids_empty); + const auto ids_end = std::ranges::end(ids_empty); + while (id_empty != ids_end && new_size > *id_empty) { + if (status_[new_size - 1] != SlotMetadata::Empty) { + const auto old_id = lib::narrow_cast(new_size - 1); + moves.emplace_back(old_id, *id_empty); + new_ids.insert({old_id, *id_empty}); + ++id_empty; + } + --new_size; } + // No list points at an Empty slot, so a dropped slot is never looked up. + auto new_id_of = [&](Idx src, Idx id) { + if (id < new_size) { + return id; + } + auto it = new_ids.find(id); + if (it == new_ids.end()) { + throw ANNEXCEPTION( + "Slot {} points at slot {} ({}), which compaction drops.", + src, + id, + svs::index::vamana::concurrent::name(status_[id]) + ); + } + return it->second; + }; - // Step 1: Compute a prefix-sum matching each valid internal index to its new - // internal index. - // - // In the returned data structure, an entry `j` at index `i` means that the - // data at index `j` is to be moved to index `i`. - auto new_to_old_id_map = nonmissing_indices(); - - // Construct an associative data structure to facilitate graph adjacency list - // remapping. - auto old_to_new_id_map = tsl::robin_map{}; - for (Idx new_id = 0, imax = new_to_old_id_map.size(); new_id < imax; ++new_id) { - Idx old_id = new_to_old_id_map.at(new_id); - old_to_new_id_map.insert({old_id, new_id}); - } + // The reverse edges are rebuilt at the end. + auto* reverse_edges = graph_.reverse_edges(); + assert(reverse_edges != nullptr); + reverse_edges->set_recording(false); // Compact the data. - data_.compact(lib::as_const_span(new_to_old_id_map), threadpool_, batch_size); - - // Manually compact the graph. - auto temp_graph = graphs::SimpleGraph(batch_size, graph_.max_degree()); - - // TODO: Write helper classes to do this partitioning. - Idx start = 0; - Idx max_index = new_to_old_id_map.size(); - while (start < max_index) { - Idx stop = std::min(start + batch_size, max_index); - // Remapping of start index to stop index. - auto batch_to_new_id_map = threads::UnitRange{start, stop}; - auto this_batch = batch_to_new_id_map.eachindex(); - - // Copy the graph into the temporary buffer and remap the IDs. - // Edges to non-Valid (Deleted) slots are dropped — those slots - // do not survive compaction, so the edge would dangle. - threads::parallel_for( - threadpool_, - threads::StaticPartition(this_batch), - [&](const auto& batch_ids, uint64_t /*tid*/) { - std::vector buffer{}; - for (auto batch_id : batch_ids) { - auto new_id = batch_to_new_id_map[batch_id]; - auto old_id = new_to_old_id_map[new_id]; - - const auto& list = graph_.get_node(old_id); - buffer.clear(); - buffer.reserve(list.size()); + data_.compact(lib::as_const_span(moves), threadpool_); - for (auto neighbor_old : list) { - auto it = old_to_new_id_map.find(neighbor_old); - if (it != old_to_new_id_map.end()) { - buffer.push_back(it->second); - } + // Remap connections. + threads::parallel_for( + threadpool_, + threads::StaticPartition{moves.size()}, + [&](const auto& is, uint64_t /*tid*/) { + std::vector buffer{}; + auto in_neighbors = tsl::robin_set{}; + for (auto i : is) { + const auto& [old_id, new_id] = moves[i]; + + buffer.clear(); + in_neighbors.clear(); + for (auto dst : graph_.get_node(old_id)) { + buffer.push_back(new_id_of(old_id, dst)); + if (graph_.has_edge(dst, old_id)) { + in_neighbors.insert(dst); } - - temp_graph.replace_node(batch_id, buffer); } - } - ); + graph_.replace_node(new_id, buffer); - // Copy the entries in the temporary graph to the original graph. - threads::parallel_for( - threadpool_, - threads::StaticPartition(this_batch), - [&](const auto& batch_ids, uint64_t /*tid*/) { - for (auto batch_id : batch_ids) { - auto new_id = batch_to_new_id_map[batch_id]; - graph_.replace_node(new_id, temp_graph.get_node(batch_id)); + reverse_edges->collect(old_id, in_neighbors, [&](size_t j) { + return !graph_.has_edge(lib::narrow_cast(j), old_id); + }); + for (auto j : in_neighbors) { + buffer.clear(); + const auto src = lib::narrow_cast(j); + + auto lock = graph_.lock_node(src); + // Map every moved neighbor at once. A later move then finds no + // edge to its old ID here, and skips this list. + bool changed = false; + for (auto dst : graph_.get_node(src)) { + changed = changed || dst >= new_size; + buffer.push_back(new_id_of(src, dst)); + } + if (changed) { + graph_.replace_node(src, lib::as_const_span(buffer), lock); + } } } - ); - start = stop; - } + } + ); ///// Finishing steps. { @@ -1517,43 +1630,37 @@ class MutableVamanaIndex { // Shrink the graph and data. compact_mutex_ is held exclusive for the // whole compact(), so all in-flight readers have drained — freeing // trailing segments here cannot dangle a concurrent search. - graph_.unsafe_resize(max_index); - data_.resize(max_index); - first_empty_->store(max_index, std::memory_order_release); - first_reusable_->store(max_index, std::memory_order_release); + graph_.unsafe_resize(new_size); + data_.resize(new_size); + // Empty slots that are not filled stay. + detail::atomic_min(*first_empty_, new_size); + detail::atomic_min(*first_reusable_, new_size); // Compact metadata and ID remapping. - for (size_t new_id = 0; new_id < max_index; ++new_id) { - auto old_id = getindex(new_to_old_id_map, new_id); - if (new_id == old_id) { - continue; - } - - auto status = getindex(status_, old_id); - status_[new_id] = status; - if (status == SlotMetadata::Valid) { + for (const auto& [old_id, new_id] : moves) { + status_[new_id] = status_[old_id]; + // A Deleted slot may have no mapping. + if (translator_.has_internal(old_id)) { translator_.remap_internal_id(old_id, new_id); } } - status_.resize(max_index); + status_.resize(new_size); - // Remap the surviving anchor, or publish the genuinely empty state. - auto ep = old_to_new_id_map.find(entry_point()); - const Idx remapped = ep != old_to_new_id_map.end() - ? ep->second - : (max_index ? Idx{0} : NO_ENTRY); - std::atomic_ref(entry_point_[0]) - .store(remapped, std::memory_order_release); + // The entry point is Valid or NO_ENTRY here, so it moves or stays. + const Idx anchor = entry_point(); + if (anchor != NO_ENTRY && anchor >= new_size) { + std::atomic_ref(entry_point_[0]) + .store(new_ids.at(anchor), std::memory_order_release); + } } // Re-derive the reverse-edge index from the fully remapped graph. - if (auto* re = graph_.reverse_edges()) { - re->set_recording(true); - } + reverse_edges->set_recording(true); graph_.rebuild_reverse_edges(threadpool_); ++compaction_epoch_; } + public: ///// Threading Interface /// @brief Return the current number of threads used for search. @@ -1654,7 +1761,8 @@ class MutableVamanaIndex { alpha_, distance_, deleted, - should_remove + should_remove, + linkable(anchor) ); // After consolidation - clean up the removed slots under lock. O(|deleted|). @@ -1677,6 +1785,9 @@ class MutableVamanaIndex { size_t min_freed = std::numeric_limits::max(); for (auto i : deleted) { if (i != anchor && status_[i] == SlotMetadata::Deleted) { + // An Empty slot has an empty list. Clear it first: once the slot + // is Empty, an add may reuse it. + graph_.clear_node(i); std::atomic_ref(status_[i]) .store(SlotMetadata::Empty, std::memory_order_release); min_freed = std::min(min_freed, static_cast(i)); @@ -1727,6 +1838,37 @@ class MutableVamanaIndex { return targets.size(); } + /// + /// @brief Consolidate only the soft-deleted slots listed in `internal_ids`. + /// + /// * Same effect as `consolidate(ids)`, addressed by internal ID, so it also reaches + /// a Deleted slot whose external ID was reassigned by a later `add_points`. + /// `delete_entries()` can report the internal IDs. + /// + /// * Listed slots that are not currently Deleted, or are outside the index, are + /// skipped. + /// + /// @returns The number of listed slots that were consolidated. + /// + template + size_t repair_incomming_connections(Ids&& internal_ids) { + auto compact_lock = lock_storage_shared(); + + tsl::robin_set targets{}; + for (auto i : internal_ids) { + const auto id = static_cast(i); + if (id < status_.size() && is_deleted(id)) { + targets.insert(lib::narrow_cast(id)); + } + } + + if (targets.empty()) { + return 0; + } + consolidate_locked(targets); + return targets.size(); + } + ///// Saving VamanaIndexParameters parameters() const { diff --git a/include/svs/concurrent/graph.h b/include/svs/concurrent/graph.h index a740da999..fdf38d8d0 100644 --- a/include/svs/concurrent/graph.h +++ b/include/svs/concurrent/graph.h @@ -25,6 +25,7 @@ #include "svs/lib/boundscheck.h" #include "svs/lib/concurrency/atomic_span.h" #include "svs/lib/concurrency/seqlock.h" +#include "svs/lib/misc.h" #include "svs/lib/saveload.h" #include "svs/lib/segmented_vector.h" #include "svs/lib/threads.h" @@ -257,13 +258,20 @@ template class SimpleGrap } /// Replace under an already-held source lock, without acquiring it twice. + /// + /// `eligible` is checked for each new neighbor after its reverse edge is recorded, + /// and a rejected neighbor is dropped. A consolidation of that neighbor then either + /// finds `i` in its reverse edges, or this check sees the deletion. The default + /// accepts all neighbors. + template void replace_node( Idx i, std::span new_neighbors, - [[maybe_unused]] const std::unique_lock& lock + [[maybe_unused]] const std::unique_lock& lock, + const Eligible& eligible = {} ) { assert(lock.owns_lock() && lock.mutex() == &node_locks_[i]); - replace_node_locked(i, new_neighbors); + replace_node_locked(i, new_neighbors, eligible); } /// @@ -499,7 +507,9 @@ template class SimpleGrap replace_node_locked(i, new_neighbors); } - template void replace_node_locked(Idx i, const Span& new_neighbors) { + template + void + replace_node_locked(Idx i, const Span& new_neighbors, const Eligible& eligible = {}) { std::span raw_data = data_.get_datum(i); // Clamp the number of elements to copy to the maximum out degree to correctly @@ -509,7 +519,9 @@ template class SimpleGrap // [Exact list] // std::vector edges_to_remove; - if (reverse_edges_) { + // These scans only feed record() and the `eligible` check, so they run only + // while recording. + if (reverse_edges_ && reverse_edges_->recording()) { Idx old_size = relaxed_load(raw_data[0]); old_size = std::min(old_size, max_degree_); @@ -530,12 +542,15 @@ template class SimpleGrap return false; }; + bool rejected = false; for (Idx k = 0; k < elements_to_copy; ++k) { Idx dst = new_neighbors[k]; if (in_old(dst)) continue; reverse_edges_->record(i, dst); + // The check must come after record(): see replace_node(). + rejected = rejected || !eligible(dst); // [Exact list] // Commented lines with [Exact list] mark // can be used to maintain exact reverse_edges list @@ -562,6 +577,19 @@ template class SimpleGrap // reverse_edges_->record(dst, i); // } } + + if (rejected) { + // Rare race: publish the list without the rejected new neighbors. + std::vector kept{}; + for (Idx k = 0; k < elements_to_copy; ++k) { + Idx dst = new_neighbors[k]; + if (in_old(dst) || eligible(dst)) { + kept.push_back(dst); + } + } + replace_node_locked(i, lib::as_const_span(kept)); + return; + } } auto seq = seq_counters_[i].begin_write(); diff --git a/include/svs/concurrent/reverse_edges.h b/include/svs/concurrent/reverse_edges.h index ca771666a..3fb7bff94 100644 --- a/include/svs/concurrent/reverse_edges.h +++ b/include/svs/concurrent/reverse_edges.h @@ -72,6 +72,7 @@ class ReverseEdges { } void set_recording(bool on) { recording_.store(on, std::memory_order_release); } + bool recording() const { return recording_.load(std::memory_order_acquire); } // lists are keeped sorted for fast binary search of elements. void record(Idx m, Idx n) { diff --git a/include/svs/concurrent/vamana_build.h b/include/svs/concurrent/vamana_build.h index 7cd707530..4267c00de 100644 --- a/include/svs/concurrent/vamana_build.h +++ b/include/svs/concurrent/vamana_build.h @@ -503,7 +503,7 @@ class VamanaBuilder { pruned_results ); graph_.replace_node( - node_id, lib::as_const_span(pruned_results), node_lock + node_id, lib::as_const_span(pruned_results), node_lock, eligible_ ); } } @@ -633,7 +633,7 @@ class VamanaBuilder { pruned_results ); graph_.replace_node( - src, lib::as_const_span(pruned_results), node_lock + src, lib::as_const_span(pruned_results), node_lock, eligible_ ); } } diff --git a/include/svs/core/compact.h b/include/svs/core/compact.h index ac2ff395b..d292d52ed 100644 --- a/include/svs/core/compact.h +++ b/include/svs/core/compact.h @@ -25,6 +25,8 @@ #include "tsl/robin_map.h" // stl +#include +#include #include namespace svs { @@ -85,4 +87,22 @@ void compact_data( } } +/// Each pair is (old, new). No new ID may also be an old ID, so the copies run in +/// parallel and need no buffer. +template +void compact_data( + Data& data, std::span> old_to_new, Pool& threadpool +) { + threads::parallel_for( + threadpool, + threads::StaticPartition{old_to_new.size()}, + [&](const auto& is, uint64_t SVS_UNUSED(tid)) { + for (auto i : is) { + const auto& [old_id, new_id] = old_to_new[i]; + data.set_datum(new_id, data.get_datum(old_id)); + } + } + ); +} + } // namespace svs diff --git a/include/svs/core/data/simple.h b/include/svs/core/data/simple.h index 28544df88..f48ca17f0 100644 --- a/include/svs/core/data/simple.h +++ b/include/svs/core/data/simple.h @@ -592,6 +592,12 @@ class SimpleData { compact(new_to_old, pool, batchsize); } + template + requires(!is_const) + void compact(std::span> old_to_new, Pool& threadpool) { + compact_data(*this, old_to_new, threadpool); + } + private: void resize_impl(size_t new_size, bool force_reallocate) { bool forced = force_reallocate && (capacity() != size()); @@ -959,6 +965,11 @@ class SimpleData { compact(new_to_old, pool, batchsize); } + template + void compact(std::span> old_to_new, Pool& threadpool) { + compact_data(*this, old_to_new, threadpool); + } + ///// Saving lib::SaveTable save(const lib::SaveContext& ctx) const { return GenericSerializer::save(*this, ctx); diff --git a/include/svs/orchestrators/dynamic_vamana.h b/include/svs/orchestrators/dynamic_vamana.h index 261278d7b..b66f4aba8 100644 --- a/include/svs/orchestrators/dynamic_vamana.h +++ b/include/svs/orchestrators/dynamic_vamana.h @@ -44,7 +44,14 @@ class DynamicVamanaInterface : public VamanaInterface { ) = 0; virtual void delete_points(std::span ids) = 0; + // The internal-ID operations below are provided by the concurrent index only. + // Like delete_points; also appends the internal ID of each deleted entry and + // returns how many were deleted. + virtual size_t + delete_points(std::span ids, std::vector& internal_ids) = 0; virtual void consolidate() = 0; + // Consolidates only the listed soft-deleted internal IDs + virtual size_t repair_incomming_connections(std::span internal_ids) = 0; virtual void compact(size_t batchsize = 1'000'000) = 0; // ID inspection. @@ -85,6 +92,30 @@ class DynamicVamanaImpl : public VamanaImpl ids) override { impl().delete_entries(ids); } void consolidate() override { impl().consolidate(); } + size_t + delete_points(std::span ids, std::vector& internal_ids) override { + using Index = std::remove_cvref_t; + if constexpr (requires(std::vector * out) { + impl().delete_entries(ids, out); + }) { + std::vector slots; + const size_t deleted = impl().delete_entries(ids, &slots); + internal_ids.insert(internal_ids.end(), slots.begin(), slots.end()); + return deleted; + } else { + throw ANNEXCEPTION("Reporting internal IDs is not supported by this index type." + ); + } + } + size_t repair_incomming_connections(std::span internal_ids) override { + if constexpr (requires { impl().repair_incomming_connections(internal_ids); }) { + return impl().repair_incomming_connections(internal_ids); + } else { + throw ANNEXCEPTION( + "Consolidating internal IDs is not supported by this index type." + ); + } + } void compact(size_t batchsize) override { impl().compact(batchsize); } // ID inspection. @@ -178,6 +209,10 @@ class DynamicVamana : public manager::IndexManager { return *this; } + size_t repair_incomming_connections(std::span internal_ids) { + return impl_->repair_incomming_connections(internal_ids); + } + DynamicVamana& compact(size_t batchsize = 1'000'000) { impl_->compact(batchsize); return *this; @@ -199,6 +234,10 @@ class DynamicVamana : public manager::IndexManager { return *this; } + size_t delete_points(std::span ids, std::vector& internal_ids) { + return impl_->delete_points(ids, internal_ids); + } + // Accessors /// @copydoc svs::index::vamana::MutableVamanaIndex::get_alpha float get_alpha() const { return impl_->get_alpha(); } From ed3d880c60b2a6d15e6b8abd38b50d84282ce174 Mon Sep 17 00:00:00 2001 From: Dmitry Razdoburdin Date: Wed, 25 Nov 2026 04:49:47 -0800 Subject: [PATCH 2/6] use plane vector for empty ids --- include/svs/concurrent/dynamic_index.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index 1dc85f3e1..e5aad8d96 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -1511,20 +1511,20 @@ class MutableVamanaIndex { retire_deleted_anchor(); auto deleted = tsl::robin_set{}; + std::vector empty; for (size_t i = 0, imax = status_.size(); i < imax; ++i) { if (status_[i] == SlotMetadata::Deleted) { deleted.insert(lib::narrow_cast(i)); + empty.push_back(i); + } else if (status_[i] == SlotMetadata::Empty) { + empty.push_back(i); } } // Consolidate first, under the same exclusive lock. This folds any // outstanding soft-deletes (including the old anchor) into the graph. consolidate_locked(deleted); - // Deleted slots are Empty now. The walk reads them lazily, nothing is stored. - auto is_empty = [this](Idx i) { return status_[i] == SlotMetadata::Empty; }; - auto ids_empty = std::views::iota(Idx{0}, lib::narrow_cast(status_.size())) | - std::views::filter(is_empty); - compact_locked(ids_empty); + compact_locked(empty); // No Empty slots are left. first_empty_->store(status_.size(), std::memory_order_release); first_reusable_->store(status_.size(), std::memory_order_release); From 83335acad5b2aca90ad52bbbebc38326b19f068b Mon Sep 17 00:00:00 2001 From: Dmitry Razdoburdin Date: Wed, 25 Nov 2026 05:03:28 -0800 Subject: [PATCH 3/6] style and fix clang build --- include/svs/concurrent/dynamic_index.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index e5aad8d96..8eed3731f 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -1510,21 +1510,21 @@ class MutableVamanaIndex { retire_deleted_anchor(); - auto deleted = tsl::robin_set{}; - std::vector empty; + auto ids_deleted = tsl::robin_set{}; + std::vector ids_empty; for (size_t i = 0, imax = status_.size(); i < imax; ++i) { if (status_[i] == SlotMetadata::Deleted) { - deleted.insert(lib::narrow_cast(i)); - empty.push_back(i); + ids_deleted.insert(lib::narrow_cast(i)); + ids_empty.push_back(lib::narrow_cast(i)); } else if (status_[i] == SlotMetadata::Empty) { - empty.push_back(i); + ids_empty.push_back(lib::narrow_cast(i)); } } // Consolidate first, under the same exclusive lock. This folds any // outstanding soft-deletes (including the old anchor) into the graph. - consolidate_locked(deleted); - compact_locked(empty); + consolidate_locked(ids_deleted); + compact_locked(ids_empty); // No Empty slots are left. first_empty_->store(status_.size(), std::memory_order_release); first_reusable_->store(status_.size(), std::memory_order_release); From b4fec25f0c37df2d41e29f056c540ffc17290518 Mon Sep 17 00:00:00 2001 From: Dmitry Razdoburdin Date: Wed, 25 Nov 2026 05:11:01 -0800 Subject: [PATCH 4/6] clang fix --- include/svs/concurrent/dynamic_index.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index 8eed3731f..f2c333441 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -1589,7 +1589,9 @@ class MutableVamanaIndex { std::vector buffer{}; auto in_neighbors = tsl::robin_set{}; for (auto i : is) { - const auto& [old_id, new_id] = moves[i]; + // Not a structured binding: clang 15 cannot capture one in a lambda. + const Idx old_id = moves[i].first; + const Idx new_id = moves[i].second; buffer.clear(); in_neighbors.clear(); From 513a5dd48f1241f619419de7ed7bb6af02589c9b Mon Sep 17 00:00:00 2001 From: Dmitry Razdoburdin Date: Wed, 25 Nov 2026 05:19:40 -0800 Subject: [PATCH 5/6] sq8 --- include/svs/quantization/scalar/scalar.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/include/svs/quantization/scalar/scalar.h b/include/svs/quantization/scalar/scalar.h index 3a808d661..b986dfa35 100644 --- a/include/svs/quantization/scalar/scalar.h +++ b/include/svs/quantization/scalar/scalar.h @@ -27,6 +27,7 @@ #include #include #include +#include #include namespace svs { @@ -484,6 +485,13 @@ class SQDataset { data_.compact(new_to_old, threadpool, batchsize); } + template + void compact(std::span> old_to_new, Pool& threadpool) + requires is_resizeable + { + data_.compact(old_to_new, threadpool); + } + /// @brief Resize the dataset void resize(size_t new_size) requires is_resizeable From da2deeac756276a7eff78179f160bc72b201f296 Mon Sep 17 00:00:00 2001 From: Dmitry Razdoburdin Date: Thu, 26 Nov 2026 08:20:30 -0800 Subject: [PATCH 6/6] c-api --- bindings/c/include/svs/c/svs_c.h | 43 ++++++++++- bindings/c/src/index.hpp | 5 ++ bindings/c/src/index_vamana.cpp | 39 ++++++++++ bindings/c/src/index_vamana.hpp | 8 ++ bindings/c/src/svs_c.cpp | 86 ++++++++++++++++++++++ include/svs/concurrent/dynamic_index.h | 36 ++++++--- include/svs/index/vamana/dynamic_index.h | 15 ++++ include/svs/orchestrators/dynamic_vamana.h | 43 +++++------ 8 files changed, 238 insertions(+), 37 deletions(-) diff --git a/bindings/c/include/svs/c/svs_c.h b/bindings/c/include/svs/c/svs_c.h index 0826c16f9..0cb84ec66 100644 --- a/bindings/c/include/svs/c/svs_c.h +++ b/bindings/c/include/svs/c/svs_c.h @@ -649,8 +649,8 @@ struct svs_dynamic_index_params { /// /// @remarks Thread-safety: unless a specific function documents otherwise, handles /// (svs_error_h, svs_index_h, svs_index_builder_h, svs_algorithm_h, svs_storage_h, -/// svs_search_params_h) are not internally synchronized. Do not operate on the same -/// handle from multiple threads concurrently without external synchronization. +/// svs_search_params_h, svs_task_h) are not internally synchronized. Do not operate on +/// the samehandle from multiple threads concurrently without external synchronization. /// Exception: dynamic indices built or loaded with a svs_sync_kind other than /// SVS_SYNC_KIND_NONE are internally synchronized, with the limits listed in /// svs_sync_kind. @@ -661,6 +661,7 @@ typedef struct svs_storage* svs_storage_h; typedef struct svs_search_params* svs_search_params_h; typedef struct svs_leanvec_training_data* svs_leanvec_training_data_h; typedef struct svs_logger* svs_logger_h; +typedef struct svs_task* svs_task_h; // Fully defined types; "_t" suffix indicates a fully defined struct typedef enum svs_error_code svs_error_code_t; @@ -1598,6 +1599,44 @@ SVS_API bool svs_index_dynamic_delete_points( svs_error_h out_err /*=NULL*/ ); +/// @brief Start deletion of points from a dynamic index, +// returns a task that finalize the deletion. +// Points aren't returnable by search after this operation. +/// @param index The dynamic index handle +/// @param ids Pointer to the vector IDs to delete (size_t array) +/// @param num_ids The number of vector IDs to delete +/// @param follow_up Receives the task on success, not written on failure. +// Free it with svs_task_free() +/// @param out_deleted_count Optional pointer to store the number of successfully deleted +/// vectors +/// @param out_err An optional error handle to capture errors +/// @return true on success, false on failure +/// @error SVS_ERROR_NOT_IMPLEMENTED if @p index doesn't use SVS_SYNC_KIND_FINE_GRAIN or +/// @p num_ids is greater than 1 +SVS_API bool svs_index_dynamic_mark_points_deleted( + svs_index_h index, + const size_t* ids, + size_t num_ids, + svs_task_h* follow_up, + size_t* out_deleted_count /*=NULL*/, + svs_error_h out_err /*=NULL*/ +); + +/// @brief Finalize a two-stage task being started by one of the following calls: +// svs_index_dynamic_mark_points_deleted() +/// @param task The task handle +/// @param out_err An optional error handle to capture errors +/// @return true on success, false on failure +SVS_API bool svs_execute_task( + svs_task_h task, svs_error_h out_err /*=NULL*/ +); + +/// @brief Free the task handle +/// @param task The task handle to free +/// @remarks A task keeps its index alive: the index is released only when the index +/// handle and all of its tasks are freed. +SVS_API void svs_task_free(svs_task_h task); + /// @brief Check if a dynamic index has a specific ID /// @param index The dynamic index handle /// @param id The vector ID to check for diff --git a/bindings/c/src/index.hpp b/bindings/c/src/index.hpp index 577520780..0eb75f531 100644 --- a/bindings/c/src/index.hpp +++ b/bindings/c/src/index.hpp @@ -23,6 +23,7 @@ #include #include +#include #include #include @@ -63,6 +64,8 @@ struct Index { virtual size_t size() const = 0; }; +using DeleteResponse = svs::index::vamana::DeleteResponse; + struct DynamicIndex : public Index { svs_sync_kind_t sync_kind; mutable std::optional mutex; @@ -92,8 +95,10 @@ struct DynamicIndex : public Index { svs::data::ConstSimpleDataView new_points, std::span ids ) = 0; virtual size_t delete_points(std::span ids) = 0; + virtual size_t delete_points(std::span ids, DeleteResponse& response) = 0; virtual bool has_id(size_t id) const = 0; virtual void consolidate() = 0; + virtual size_t repair(const DeleteResponse& response) = 0; virtual void compact(size_t batchsize) = 0; }; } // namespace svs::c_runtime diff --git a/bindings/c/src/index_vamana.cpp b/bindings/c/src/index_vamana.cpp index addc5eb34..fcba83741 100644 --- a/bindings/c/src/index_vamana.cpp +++ b/bindings/c/src/index_vamana.cpp @@ -247,6 +247,20 @@ void DynamicIndexVamana::consolidate() { index.consolidate(); } +size_t DynamicIndexVamana::delete_points( + std::span /*ids*/, DeleteResponse& /*response*/ +) { + throw not_implemented( + "Reporting internal IDs is only supported by FINE GRAIN dynamic indices." + ); +} + +size_t DynamicIndexVamana::repair(const DeleteResponse& /*response*/) { + throw not_implemented( + "Consolidating internal IDs is only supported by FINE GRAIN dynamic indices." + ); +} + void DynamicIndexVamana::compact(size_t batchsize) { auto lock = write_lock(); // Ensure the index is consolidated before compacting. @@ -320,4 +334,29 @@ size_t ConcurrentIndexVamana::delete_points(std::span ids) { return delete_points_unlocked(ids); } +size_t ConcurrentIndexVamana::delete_points( + std::span ids, DeleteResponse& response +) { + assert(sync_kind == SVS_SYNC_KIND_FINE_GRAIN); + if (ids.size() > 1) { + throw not_implemented( + "FINE GRAIN dynamic index only supports deleting one point at a time." + ); + } + auto lock = read_lock(); + return index.delete_points(ids, response); +} + +size_t ConcurrentIndexVamana::repair(const DeleteResponse& response) { + assert(sync_kind == SVS_SYNC_KIND_FINE_GRAIN); + if (response.internal_ids.size() > 1) { + throw not_implemented( + "FINE GRAIN dynamic index only supports repairment one point at a time." + ); + } + auto lock = read_lock(); + // The index skips the repair if it was compacted since the delete. + return index.repair_incoming_connections(response); +} + } // namespace svs::c_runtime diff --git a/bindings/c/src/index_vamana.hpp b/bindings/c/src/index_vamana.hpp index 2a193981e..760b87e20 100644 --- a/bindings/c/src/index_vamana.hpp +++ b/bindings/c/src/index_vamana.hpp @@ -130,6 +130,10 @@ struct DynamicIndexVamana : public DynamicIndex { void consolidate() override; + size_t delete_points(std::span ids, DeleteResponse& response) override; + + size_t repair(const DeleteResponse& response) override; + void compact(size_t batchsize) override; size_t get_num_threads() const override { @@ -184,6 +188,10 @@ struct ConcurrentIndexVamana : public DynamicIndexVamana { index.consolidate(); } + size_t delete_points(std::span ids, DeleteResponse& response) override; + + size_t repair(const DeleteResponse& response) override; + void compact(size_t batchsize) override { // exclusive lock prevents potential deadlock in case of custom threadpool takes // internal mutex in parallel_for method diff --git a/bindings/c/src/svs_c.cpp b/bindings/c/src/svs_c.cpp index 6718861bf..6a87cbe85 100644 --- a/bindings/c/src/svs_c.cpp +++ b/bindings/c/src/svs_c.cpp @@ -1588,6 +1588,92 @@ extern "C" bool svs_index_dynamic_delete_points( ); } +struct svs_task { + using IndexPtr_t = std::shared_ptr; + class AbstractTask { + protected: + IndexPtr_t index_; + + public: + AbstractTask(IndexPtr_t index) + : index_(index){}; + + virtual ~AbstractTask() = default; + + virtual void execute() const = 0; + }; + + class RepairTask : public AbstractTask { + svs::c_runtime::DeleteResponse response_; + + public: + RepairTask(IndexPtr_t index) + : AbstractTask(index){}; + + void execute() const override { index_->repair(response_); }; + + svs::c_runtime::DeleteResponse& get_response() { return response_; } + }; + + void execute() { task->execute(); } + + svs_task(std::unique_ptr _task) + : task(std::move(_task)) {} + + private: + std::unique_ptr task; +}; + +extern "C" bool svs_index_dynamic_mark_points_deleted( + svs_index_h index, + const size_t* ids, + size_t num_ids, + svs_task_h* follow_up, + size_t* out_deleted_count, + svs_error_h out_err +) { + using namespace svs::c_runtime; + return wrap_exceptions( + [&]() { + EXPECT_ARG_NOT_NULL(index); + EXPECT_ARG_NOT_NULL(ids); + EXPECT_ARG_GT_THAN(num_ids, 0); + EXPECT_ARG_NOT_NULL(follow_up); + auto dynamic_index_ptr = std::dynamic_pointer_cast(index->impl); + INVALID_ARGUMENT_IF( + dynamic_index_ptr == nullptr, "Index does not support dynamic updates" + ); + auto task = std::make_unique(dynamic_index_ptr); + auto& response = task->get_response(); + auto output = std::make_unique(svs_task{std::move(task)}); + + auto deleted_count = + dynamic_index_ptr->delete_points(std::span(ids, num_ids), response); + if (out_deleted_count) { + *out_deleted_count = deleted_count; + } + + *follow_up = output.release(); + return true; + }, + out_err + ); +} + +extern "C" bool svs_execute_task(svs_task_h task, svs_error_h out_err) { + using namespace svs::c_runtime; + return wrap_exceptions( + [&]() { + EXPECT_ARG_NOT_NULL(task); + task->execute(); + return true; + }, + out_err + ); +} + +extern "C" void svs_task_free(svs_task_h task) { delete task; } + extern "C" bool svs_index_dynamic_has_id( svs_index_h index, size_t id, bool* out_has_id, svs_error_h out_err ) { diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index f2c333441..9c41fa5ee 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -1329,14 +1329,19 @@ class MutableVamanaIndex { /// graph. /// /// @param ids External IDs to delete. Missing or already deleted IDs are skipped. - /// @param internal_ids If not null, the internal ID of each entry deleted by this - /// call is appended. Keep them for `compact(ids)`: after `consolidate()` the - /// external ID is gone and can no longer be translated. + /// @param response If not null, it is overwritten with the internal ID of each entry + /// deleted by this call and the current compaction epoch. /// template - size_t delete_entries(const T& ids, std::vector* internal_ids = nullptr) { + size_t delete_entries(const T& ids, DeleteResponse* response = nullptr) { auto compact_lock = lock_storage_shared(); std::shared_lock lock{*translator_mutex_}; + + if (response != nullptr) { + response->internal_ids.clear(); + response->epoch = compaction_epoch_; + } + size_t deleted = 0; for (auto i : ids) { if (!translator_.has_external(i)) { @@ -1348,8 +1353,8 @@ class MutableVamanaIndex { } delete_entry(internal); ++deleted; - if (internal_ids != nullptr) { - internal_ids->push_back(lib::narrow_cast(internal)); + if (response != nullptr) { + response->internal_ids.push_back(internal); } } // Don't erase translator entries here — concurrent search may still @@ -1841,23 +1846,30 @@ class MutableVamanaIndex { } /// - /// @brief Consolidate only the soft-deleted slots listed in `internal_ids`. + /// @brief Consolidate only the soft-deleted slots listed in `response`. /// /// * Same effect as `consolidate(ids)`, addressed by internal ID, so it also reaches /// a Deleted slot whose external ID was reassigned by a later `add_points`. - /// `delete_entries()` can report the internal IDs. + /// + /// * Does nothing if the index was compacted after `delete_entries()` filled + /// `response`: its internal IDs may now name other slots. /// /// * Listed slots that are not currently Deleted, or are outside the index, are /// skipped. /// - /// @returns The number of listed slots that were consolidated. + /// @param response What `delete_entries()` reported. /// - template - size_t repair_incomming_connections(Ids&& internal_ids) { + /// @returns The number of listed slots that were consolidated + /// + size_t repair_incoming_connections(const DeleteResponse& response) { auto compact_lock = lock_storage_shared(); + if (response.epoch != compaction_epoch_) { + // compaction was launched between delete and repair calls + return 0; + } tsl::robin_set targets{}; - for (auto i : internal_ids) { + for (auto i : response.internal_ids) { const auto id = static_cast(i); if (id < status_.size() && is_deleted(id)) { targets.insert(lib::narrow_cast(id)); diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index 8a9a64dd1..ea21e7ccd 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -20,6 +20,7 @@ #include #include #include +#include // Include the flat index to spin-up exhaustive searches on demand. #include "svs/index/flat/flat.h" @@ -92,6 +93,20 @@ inline constexpr std::string_view name(SlotMetadata metadata) { } // clang-format on +/// +/// @brief What the concurrent index's `delete_entries()` reports for a later +/// `repair_incoming_connections()`. +/// +/// Internal IDs change only when the index is compacted, so the IDs are valid only +/// while `epoch` matches the index. +/// +struct DeleteResponse { + /// Internal IDs of the entries the call deleted. + std::vector internal_ids; + /// Compaction epoch of the index when they were deleted. + size_t epoch = 0; +}; + class ValidBuilder { public: ValidBuilder(const std::vector& status) diff --git a/include/svs/orchestrators/dynamic_vamana.h b/include/svs/orchestrators/dynamic_vamana.h index b66f4aba8..657ffdc9d 100644 --- a/include/svs/orchestrators/dynamic_vamana.h +++ b/include/svs/orchestrators/dynamic_vamana.h @@ -44,14 +44,14 @@ class DynamicVamanaInterface : public VamanaInterface { ) = 0; virtual void delete_points(std::span ids) = 0; - // The internal-ID operations below are provided by the concurrent index only. - // Like delete_points; also appends the internal ID of each deleted entry and - // returns how many were deleted. + // The response operations below are provided by the concurrent index only. + // Like delete_points; also fills `response` and returns how many were deleted. virtual size_t - delete_points(std::span ids, std::vector& internal_ids) = 0; + delete_points(std::span ids, index::vamana::DeleteResponse& response) = 0; virtual void consolidate() = 0; - // Consolidates only the listed soft-deleted internal IDs - virtual size_t repair_incomming_connections(std::span internal_ids) = 0; + // Consolidates the slots in `response`. + virtual size_t repair_incoming_connections(const index::vamana::DeleteResponse& response + ) = 0; virtual void compact(size_t batchsize = 1'000'000) = 0; // ID inspection. @@ -92,24 +92,20 @@ class DynamicVamanaImpl : public VamanaImpl ids) override { impl().delete_entries(ids); } void consolidate() override { impl().consolidate(); } - size_t - delete_points(std::span ids, std::vector& internal_ids) override { - using Index = std::remove_cvref_t; - if constexpr (requires(std::vector * out) { - impl().delete_entries(ids, out); - }) { - std::vector slots; - const size_t deleted = impl().delete_entries(ids, &slots); - internal_ids.insert(internal_ids.end(), slots.begin(), slots.end()); - return deleted; + size_t delete_points( + std::span ids, index::vamana::DeleteResponse& response + ) override { + if constexpr (requires { impl().delete_entries(ids, &response); }) { + return impl().delete_entries(ids, &response); } else { throw ANNEXCEPTION("Reporting internal IDs is not supported by this index type." ); } } - size_t repair_incomming_connections(std::span internal_ids) override { - if constexpr (requires { impl().repair_incomming_connections(internal_ids); }) { - return impl().repair_incomming_connections(internal_ids); + size_t repair_incoming_connections(const index::vamana::DeleteResponse& response + ) override { + if constexpr (requires { impl().repair_incoming_connections(response); }) { + return impl().repair_incoming_connections(response); } else { throw ANNEXCEPTION( "Consolidating internal IDs is not supported by this index type." @@ -209,8 +205,8 @@ class DynamicVamana : public manager::IndexManager { return *this; } - size_t repair_incomming_connections(std::span internal_ids) { - return impl_->repair_incomming_connections(internal_ids); + size_t repair_incoming_connections(const index::vamana::DeleteResponse& response) { + return impl_->repair_incoming_connections(response); } DynamicVamana& compact(size_t batchsize = 1'000'000) { @@ -234,8 +230,9 @@ class DynamicVamana : public manager::IndexManager { return *this; } - size_t delete_points(std::span ids, std::vector& internal_ids) { - return impl_->delete_points(ids, internal_ids); + size_t + delete_points(std::span ids, index::vamana::DeleteResponse& response) { + return impl_->delete_points(ids, response); } // Accessors