From 6b3882e86cdad39880dbe2bb65b88920d717c0f6 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Wed, 21 Oct 2026 12:38:46 -0700 Subject: [PATCH 01/16] Add filtered search on the dynamic Vamana search buffer Reuse the MutableBuffer valid/invalid mechanism: a FilteredValidBuilder marks an entry invalid if it is deleted or the predicate rejects its external id. New MutableVamanaIndex::search overload taking a predicate, padding rows with id -1 / +inf and returning per-query found counts. Supplement path checks the predicate before computing the distance. Orchestrator virtual appended last. Make filtered search an optional argument of the existing search Replace the separate filtered search overload with two optional trailing arguments on MutableVamanaIndex::search (an id predicate and a per-query result count). Without a predicate the existing code path runs unchanged. check_and_supplement_search_buffer gets an optional predicate that is checked before the distance is computed. The filter predicate type is now a type-erased std::function, so FilteredValidBuilder is no longer a template. The orchestrator keeps one appended virtual that forwards to the index search. Run filtered search through the existing batch search path The optional filter on MutableVamanaIndex::search now only chooses which builder the existing greedy search closure uses; both cases call the same per_thread_batch_search. FilteredValidBuilder derives from ValidBuilder. The buffer top-up in single_search applies the filter when the search closure carries one. The per-query result count out-parameter is removed (callers count non-padding ids). per_thread_batch_search now pads result rows with fewer than k entries (id size_t(-1), distance +inf) instead of reading past the end of the search buffer, and the post-search id translation skips the padding. Filter through ValidBuilder in the existing dynamic search Give ValidBuilder an optional predicate and pass it down through internal_search_builder, greedy_search_closure and search() as optional arguments, instead of a separate builder and search path. Filtered-only checks: the supplement fallback skips failing ids, copy-out pads short rows with id -1 and the worst score, translation skips padded ids. Fix filtered test and orchestrator for the concurrent index The orchestrator reports filtered search as unsupported for indexes whose search has no filter argument (the concurrent index), instead of failing to compile. In the filtered test, drop the unfiltered-padding section (padding is filtered-only) and add an inner-product case checking padding uses -inf. Allow filtered search for data types that opt in Apply clang-format Enable filtered search for all data types Apply clang-format Name the filter argument `filter` everywhere Apply clang-format Choose the filtering builder at compile time Remove the added filtered-search test Share the search body between filtered and regular search Return to the ValidBuilder design before the compile-time changes Choose filtered or regular search at compile time Filtered search on the concurrent index Skip the filter for entries the buffer would drop --- include/svs/concurrent/dynamic_index.h | 157 +++++++++++---- include/svs/index/vamana/dynamic_index.h | 137 +++++++++---- include/svs/index/vamana/extensions.h | 36 +++- include/svs/orchestrators/dynamic_vamana.h | 60 ++++++ tests/svs/index/vamana/dynamic_index.cpp | 222 +++++++++++++++++++++ 5 files changed, 536 insertions(+), 76 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index 1fc1a8980..eb3caeab5 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -148,13 +148,35 @@ enum class ReplaceExternalIdResult : uint8_t { inline constexpr size_t no_external_id = type_traits::sentinel_v, std::less<>>.id(); -class ValidBuilder { +template class ValidBuilder { public: - ValidBuilder(const lib::SegmentedVector& status) - : status_{status} {} + // Optional `filter` (with `index`): an entry is also invalid if + // `filter(external_id)` is false. Invalid entries are navigated through but never + // returned. + ValidBuilder( + const lib::SegmentedVector& status, + const Index* index = nullptr, + const std::function* filter = nullptr + ) + : status_{status} + , index_{index} + , filter_{filter} {} + + /// Filtered only: skip the filter for entries `buffer` would drop anyway. + template void skip_if_dropped_by(const Buffer& buffer) { + skip_buffer_ = &buffer; + skip_ = [](const void* b, float d) { + return static_cast(b)->can_skip(d); + }; + } template constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { + if constexpr (Filtered) { + if (skip_ != nullptr && skip_(skip_buffer_, distance)) { + return PredicatedSearchNeighbor(i, distance, false); + } + } // A neighbor is returnable only if its slot is Valid. Deleted slots // must be skipped; Pending slots are reserved by an in-flight add and // their vectors/edges are not yet fully published. Empty slots should @@ -164,11 +186,23 @@ class ValidBuilder { .load(std::memory_order_acquire) != SlotMetadata::Valid; // This neighbor should be skipped if the metadata corresponding to the given index // marks this slot as deleted. + if constexpr (Filtered) { + if (!invalid) { + // Locks the translation per lookup so writers keep running. An id erased + // concurrently has no external id and fails the filter. + size_t external = index_->translate_internal_id(i); + invalid = external == no_external_id || !(*filter_)(external); + } + } return PredicatedSearchNeighbor(i, distance, !invalid); } private: const lib::SegmentedVector& status_; + const Index* index_; + const std::function* filter_; + const void* skip_buffer_ = nullptr; + bool (*skip_)(const void*, float) = nullptr; }; template @@ -810,6 +844,9 @@ class MutableVamanaIndex { [&](const auto is, uint64_t /*tid*/) { for (auto i : is) { for (size_t j = 0, jmax = getsize<1>(ids); j < jmax; ++j) { + if (ids.at(i, j) == static_cast(-1)) { + continue; // Padding from a filtered search. + } auto internal = lib::narrow_cast(ids.at(i, j)); ids.at(i, j) = unsafe_translate_internal_id(internal); } @@ -880,7 +917,11 @@ class MutableVamanaIndex { // Return a `greedy_search` compatible builder for this index. // This is an internal method, mostly used to help implement the batch iterator. - ValidBuilder internal_search_builder() const { return ValidBuilder{status_}; } + template + ValidBuilder + internal_search_builder(const std::function* filter = nullptr) const { + return ValidBuilder{status_, this, filter}; + } /// @brief RAII shared lock guarding data_/graph_ against compact()'s shrink /// (which frees segments). Used by searches, iterators and mutations that @@ -900,18 +941,24 @@ class MutableVamanaIndex { return std::shared_lock(*translator_mutex_); } + template auto greedy_search_closure( GreedySearchPrefetchParameters prefetch_parameters, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const std::function* filter = nullptr ) const { - return [&, prefetch_parameters]( - const auto& query, auto& accessor, auto& distance, auto& buffer - ) { + return [&, + prefetch_parameters, + filter](const auto& query, auto& accessor, auto& distance, auto& buffer) { const Idx seed = entry_point(); if (seed == NO_ENTRY) { buffer.clear(); return; } + auto builder = internal_search_builder(filter); + if constexpr (Filtered) { + builder.skip_if_dropped_by(buffer); + } // Perform the greedy search using the provided resources. concurrent::greedy_search( graph_, @@ -921,7 +968,7 @@ class MutableVamanaIndex { distance, buffer, vamana::EntryPointInitializer{std::span{&seed, 1}}, - internal_search_builder(), + builder, prefetch_parameters, cancel ); @@ -947,7 +994,7 @@ class MutableVamanaIndex { scratch.buffer, scratch.scratch, query, - greedy_search_closure(scratch.prefetch_parameters, cancel), + greedy_search_closure(scratch.prefetch_parameters, cancel), *this ); } @@ -957,7 +1004,8 @@ class MutableVamanaIndex { QueryResultView results, const Queries& queries, const search_parameters_type& sp, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const std::function* filter = nullptr ) { // Internal IDs must retain their meaning until translation has completed. auto compact_lock = lock_storage_shared(); @@ -966,33 +1014,52 @@ class MutableVamanaIndex { threadpool_, threads::StaticPartition{queries.size()}, [&](const auto is, uint64_t SVS_UNUSED(tid)) { - size_t num_neighbors = results.n_neighbors(); - auto buffer = search_buffer_type{ - sp.buffer_config_, - distance::comparator(distance_), - sp.search_buffer_visited_set_}; - - auto prefetch_parameters = GreedySearchPrefetchParameters{ - sp.prefetch_lookahead_, sp.prefetch_step_}; - - // Legalize search buffer for this search. - if (buffer.target_capacity() < num_neighbors) { - buffer.change_maxsize(num_neighbors); + auto body = [&](std::bool_constant) { + size_t num_neighbors = results.n_neighbors(); + auto buffer = search_buffer_type{ + sp.buffer_config_, + distance::comparator(distance_), + sp.search_buffer_visited_set_}; + + auto prefetch_parameters = GreedySearchPrefetchParameters{ + sp.prefetch_lookahead_, sp.prefetch_step_}; + + // Legalize search buffer for this search. + if (buffer.target_capacity() < num_neighbors) { + buffer.change_maxsize(num_neighbors); + } + auto scratch = + extensions::per_thread_batch_search_setup(data_, distance_); + + auto run = [&](const auto& search) { + extensions::per_thread_batch_search( + data_, + buffer, + scratch, + queries, + results, + threads::UnitRange{is}, + search, + *this, + cancel + ); + }; + auto search = greedy_search_closure( + prefetch_parameters, cancel, filter + ); + if constexpr (Filtered) { + run(extensions::FilteredSearch{search, filter} + ); + } else { + run(search); + } + }; + if (filter != nullptr) { + [&]() __attribute__((noinline)) { body(std::true_type{}); } + (); + } else { + body(std::false_type{}); } - auto scratch = - extensions::per_thread_batch_search_setup(data_, distance_); - - extensions::per_thread_batch_search( - data_, - buffer, - scratch, - queries, - results, - threads::UnitRange{is}, - greedy_search_closure(prefetch_parameters, cancel), - *this, - cancel - ); } ); } @@ -2030,7 +2097,11 @@ class MutableVamanaIndex { /// Called from the ``extensions::single_search`` override below. /// template - void supplement_search_buffer(SearchBuffer& search_buffer, const Query& query) const { + void supplement_search_buffer( + SearchBuffer& search_buffer, + const Query& query, + const std::function* filter = nullptr + ) const { if (search_buffer.valid() >= search_buffer.target_window() || search_buffer.valid() >= size()) { return; @@ -2043,6 +2114,10 @@ class MutableVamanaIndex { auto builder = internal_search_builder(); for (auto pair : translator_) { auto internal_id = pair.second; + // `pair.first` is the external id, read under the lock held above. + if (filter != nullptr && !(*filter)(pair.first)) { + continue; + } // Skip slots pending deferred translator cleanup, reserved by an in-flight // add_points, or otherwise not live. if (std::atomic_ref(const_cast(status_[internal_id] @@ -2133,7 +2208,11 @@ SVS_FORCE_INLINE void svs_invoke( if (cancel()) { return; } - index.supplement_search_buffer(search_buffer, query); + const std::function* filter = nullptr; + if constexpr (requires { search.filter; }) { + filter = search.filter; // Filtered search: keep filtered-out ids out of the top-up. + } + index.supplement_search_buffer(search_buffer, query, filter); } ///// Deduction Guides. diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index 8a9a64dd1..b06043083 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -92,21 +92,52 @@ inline constexpr std::string_view name(SlotMetadata metadata) { } // clang-format on -class ValidBuilder { +template class ValidBuilder { public: - ValidBuilder(const std::vector& status) - : status_{status} {} + // Optional `filter` (with `translator`): an entry is also invalid if + // `filter(external_id)` is false. Invalid entries are navigated through but never + // returned. + ValidBuilder( + const std::vector& status, + const IDTranslator* translator = nullptr, + const std::function* filter = nullptr + ) + : status_{status} + , translator_{translator} + , filter_{filter} {} + + /// Filtered only: skip the filter for entries `buffer` would drop anyway. + template void skip_if_dropped_by(const Buffer& buffer) { + skip_buffer_ = &buffer; + skip_ = [](const void* b, float d) { + return static_cast(b)->can_skip(d); + }; + } template constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { + if constexpr (Filtered) { + if (skip_ != nullptr && skip_(skip_buffer_, distance)) { + return PredicatedSearchNeighbor(i, distance, false); + } + } bool invalid = getindex(status_, i) == SlotMetadata::Deleted; // This neighbor should be skipped if the metadata corresponding to the given index // marks this slot as deleted. + if constexpr (Filtered) { + if (!invalid) { + invalid = !(*filter_)(translator_->get_external(i)); + } + } return PredicatedSearchNeighbor(i, distance, !invalid); } private: const std::vector& status_; + const IDTranslator* translator_; + const std::function* filter_; + const void* skip_buffer_ = nullptr; + bool (*skip_)(const void*, float) = nullptr; }; namespace detail { @@ -636,6 +667,9 @@ class MutableVamanaIndex { [&](const auto is, uint64_t /*tid*/) { for (auto i : is) { for (size_t j = 0, jmax = getsize<1>(ids); j < jmax; ++j) { + if (ids.at(i, j) == static_cast(-1)) { + continue; // Padding from a filtered search. + } auto internal = lib::narrow_cast(ids.at(i, j)); ids.at(i, j) = translate_internal_id(internal); } @@ -677,15 +711,25 @@ class MutableVamanaIndex { // Return a `greedy_search` compatible builder for this index. // This is an internal method, mostly used to help implement the batch iterator. - ValidBuilder internal_search_builder() const { return ValidBuilder{status_}; } + template + ValidBuilder + internal_search_builder(const std::function* filter = nullptr) const { + return ValidBuilder{status_, &translator_, filter}; + } + template auto greedy_search_closure( GreedySearchPrefetchParameters prefetch_parameters, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const std::function* filter = nullptr ) const { - return [&, prefetch_parameters]( - const auto& query, auto& accessor, auto& distance, auto& buffer - ) { + return [&, + prefetch_parameters, + filter](const auto& query, auto& accessor, auto& distance, auto& buffer) { + auto builder = internal_search_builder(filter); + if constexpr (Filtered) { + builder.skip_if_dropped_by(buffer); + } // Perform the greedy search using the provided resources. greedy_search( graph_, @@ -695,7 +739,7 @@ class MutableVamanaIndex { distance, buffer, vamana::EntryPointInitializer{lib::as_const_span(entry_point_)}, - internal_search_builder(), + builder, prefetch_parameters, cancel ); @@ -727,37 +771,60 @@ class MutableVamanaIndex { QueryResultView results, const Queries& queries, const search_parameters_type& sp, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const std::function* filter = nullptr ) { + // Optional `filter`: only entries whose external id passes are returned. It is + // called from all search threads. Rows with fewer passing entries than requested + // are padded with id `size_t(-1)` and the worst score. threads::parallel_for( threadpool_, threads::StaticPartition{queries.size()}, [&](const auto is, uint64_t SVS_UNUSED(tid)) { - size_t num_neighbors = results.n_neighbors(); - auto buffer = search_buffer_type{ - // Legalize search buffer for this search. - sp.buffer_config_.get_total_capacity() < num_neighbors - ? SearchBufferConfig{num_neighbors} - : sp.buffer_config_, - distance::comparator(distance_), - sp.search_buffer_visited_set_}; - - auto prefetch_parameters = GreedySearchPrefetchParameters{ - sp.prefetch_lookahead_, sp.prefetch_step_}; - - auto scratch = extensions::per_thread_batch_search_setup(data_, distance_); - - extensions::per_thread_batch_search( - data_, - buffer, - scratch, - queries, - results, - threads::UnitRange{is}, - greedy_search_closure(prefetch_parameters, cancel), - *this, - cancel - ); + auto body = [&](std::bool_constant) { + size_t num_neighbors = results.n_neighbors(); + auto buffer = search_buffer_type{ + // Legalize search buffer for this search. + sp.buffer_config_.get_total_capacity() < num_neighbors + ? SearchBufferConfig{num_neighbors} + : sp.buffer_config_, + distance::comparator(distance_), + sp.search_buffer_visited_set_}; + + auto prefetch_parameters = GreedySearchPrefetchParameters{ + sp.prefetch_lookahead_, sp.prefetch_step_}; + + auto scratch = + extensions::per_thread_batch_search_setup(data_, distance_); + + auto run = [&](const auto& search) { + extensions::per_thread_batch_search( + data_, + buffer, + scratch, + queries, + results, + threads::UnitRange{is}, + search, + *this, + cancel + ); + }; + auto search = greedy_search_closure( + prefetch_parameters, cancel, filter + ); + if constexpr (Filtered) { + run(extensions::FilteredSearch{search, filter}); + } else { + run(search); + } + }; + if (filter != nullptr) { + [&]() __attribute__((noinline)) { body(std::true_type{}); } + (); + } else { + body(std::false_type{}); + } } ); diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index 96ffeaa06..9ec594486 100644 --- a/include/svs/index/vamana/extensions.h +++ b/include/svs/index/vamana/extensions.h @@ -27,6 +27,9 @@ #include "svs/lib/preprocessor.h" #include "svs/lib/threads.h" +#include +#include + namespace svs::index::vamana::extensions { ///// @@ -432,12 +435,18 @@ struct VamanaSingleSearchType { /// with additional results. template void check_and_supplement_search_buffer( - const Index& index, SearchBuffer& search_buffer, const Query& query + const Index& index, + SearchBuffer& search_buffer, + const Query& query, + const std::function* filter = nullptr ) { if (search_buffer.valid() < search_buffer.target_window() && search_buffer.valid() < index.size()) { search_buffer.sort(); for (auto external_id : index.external_ids()) { + if (filter != nullptr && !(*filter)(external_id)) { + continue; + } auto internal_id = index.translate_external_id(external_id); auto dist = index.get_distance(external_id, query); auto builder = index.internal_search_builder(); @@ -449,6 +458,15 @@ void check_and_supplement_search_buffer( } } +/// A search closure that also carries the filter of a filtered search. +template struct FilteredSearch { + Search search; + const std::function* filter; + template void operator()(Args&&... args) const { + search(std::forward(args)...); + } +}; + /// Customization point object for processing single queries. inline constexpr VamanaSingleSearchType single_search{}; @@ -481,7 +499,12 @@ SVS_FORCE_INLINE void svs_invoke( search(query, accessor, distance, search_buffer); if constexpr (Index::needs_id_translation) { - check_and_supplement_search_buffer(index, search_buffer, query); + const std::function* filter = nullptr; + if constexpr (requires { search.filter; }) { + filter = + search.filter; // Filtered search: keep filtered-out ids out of the top-up. + } + check_and_supplement_search_buffer(index, search_buffer, query, filter); } } @@ -586,6 +609,15 @@ void svs_invoke( // Copy back results. for (size_t j = 0; j < num_neighbors; ++j) { + if constexpr (requires { search.filter; }) { + if (j >= search_buffer.size()) { // Filtered: fewer than k passed. + result.index(i, j) = static_cast(-1); + result.distance(i, j) = distance::comparator(distance)(0.0f, 1.0f) + ? std::numeric_limits::infinity() + : -std::numeric_limits::infinity(); + continue; + } + } result.set(search_buffer[j], i, j); } } diff --git a/include/svs/orchestrators/dynamic_vamana.h b/include/svs/orchestrators/dynamic_vamana.h index 261278d7b..92d8d1e60 100644 --- a/include/svs/orchestrators/dynamic_vamana.h +++ b/include/svs/orchestrators/dynamic_vamana.h @@ -56,6 +56,14 @@ class DynamicVamanaInterface : public VamanaInterface { // Check if the index has been consolidated - no `Deleted` entries remain. virtual bool is_consolidated() const = 0; + + // Filtered search; false if the data type does not support it. Keep last (ABI). + virtual bool filtered_search( + svs::QueryResultView results, + AnonymousArray<2> queries, + const index::vamana::VamanaSearchParameters& search_parameters, + const std::function& filter + ) = 0; }; template @@ -109,6 +117,44 @@ class DynamicVamanaImpl : public VamanaImpl results, + AnonymousArray<2> queries, + const index::vamana::VamanaSearchParameters& search_parameters, + const std::function& filter + ) override { + // Filtered search is available for every data type. Indexes whose `search` has no + // filter argument (e.g. the concurrent index) report "unsupported". + constexpr bool supported = requires( + Impl & idx, + svs::QueryResultView r, + data::ConstSimpleDataView q, + const index::vamana::VamanaSearchParameters& sp, + const std::function* filter + ) { idx.search(r, q, sp, lib::Returns(lib::Const()), filter); }; + if constexpr (supported) { + lib::match( + QueryTypes{}, + queries.type(), + [&](lib::Type SVS_UNUSED(type)) { + impl().search( + results, + data::ConstSimpleDataView(queries), + search_parameters, + lib::Returns(lib::Const()), + &filter + ); + }, + [&](svs::DataType data_type) { + throw ANNEXCEPTION("Unsupported query datatype! Got: {}.", data_type); + } + ); + return true; + } else { + return false; + } + } }; // Forward Declaractions. @@ -609,6 +655,20 @@ class DynamicVamana : public manager::IndexManager { /// @brief Check if the index has been consolidated - no `Deleted` entries remain. bool is_consolidated() const { return impl_->is_consolidated(); } + + /// @brief Filtered search: only ids for which ``filter(id)`` is true are returned. + /// Returns false if the data type does not support it. + template + bool filtered_search( + QueryResultView results, + data::ConstSimpleDataView queries, + const VamanaSearchParameters& search_parameters, + const std::function& filter + ) { + return impl_->filtered_search( + results, AnonymousArray<2>(queries), search_parameters, filter + ); + } }; /// diff --git a/tests/svs/index/vamana/dynamic_index.cpp b/tests/svs/index/vamana/dynamic_index.cpp index 94daddcf1..6bedb8ea8 100644 --- a/tests/svs/index/vamana/dynamic_index.cpp +++ b/tests/svs/index/vamana/dynamic_index.cpp @@ -23,11 +23,14 @@ #include #include #include +#include #include #include +#include #include #include #include +#include // svs #include "svs/core/recall.h" @@ -464,3 +467,222 @@ CATCH_TEST_CASE("MutableVamana Index Memory Usage", "[graph_index][dynamic_index const size_t usage = index.get_memory_breakdown().total(); CATCH_REQUIRE(usage == expected_total_bytes); } + +CATCH_TEST_CASE( + "MutableVamana Index Filtered Search", "[graph_index][dynamic_index][filtered]" +) { + const size_t num_threads = 2; + const size_t n = 3000; + const size_t dim = 32; + const size_t num_queries = 50; + const size_t k = 10; + using Distance = svs::distance::DistanceL2; + + std::mt19937 rng(42); + std::normal_distribution normal; + auto data = svs::data::BlockedData(n, dim); + std::vector> raw(n, std::vector(dim)); + for (size_t i = 0; i < n; ++i) { + for (auto& x : raw[i]) { + x = normal(rng); + } + data.set_datum(i, raw[i]); + } + auto queries = svs::data::SimpleData(num_queries, dim); + for (size_t i = 0; i < num_queries; ++i) { + std::vector q(dim); + for (auto& x : q) { + x = normal(rng); + } + queries.set_datum(i, q); + } + + // External ids differ from internal ids. + std::vector ids(n); + std::iota(ids.begin(), ids.end(), 7); + svs::index::vamana::VamanaBuildParameters parameters{1.2, 32, 64, 64, 32, true}; + auto index = svs::index::vamana::MutableVamanaIndex( + parameters, std::move(data), ids, Distance(), num_threads + ); + + auto sp = svs::index::vamana::VamanaSearchParameters{}; + sp.buffer_config_ = svs::index::vamana::SearchBufferConfig{50}; + + // Runs the filtered search; `found` = number of non-padding ids per query. + auto search_filtered = [&](auto& results, + const std::function& filter, + std::vector& found) { + index.search( + results.view(), + queries.cview(), + sp, + svs::lib::Returns(svs::lib::Const()), + &filter + ); + found.assign(num_queries, 0); + for (size_t q = 0; q < num_queries; ++q) { + for (size_t j = 0; j < k; ++j) { + found[q] += results.index(q, j) != static_cast(-1); + } + } + }; + + // Brute force over live ids passing `filter`. + std::unordered_set deleted; + auto brute_force = [&](size_t q, auto&& filter) { + std::vector> all; + for (size_t i = 0; i < n; ++i) { + size_t e = ids[i]; + if (deleted.contains(e) || !filter(e)) { + continue; + } + float d = 0; + for (size_t j = 0; j < dim; ++j) { + float diff = queries.get_datum(q)[j] - raw[i][j]; + d += diff * diff; + } + all.emplace_back(d, e); + } + std::sort(all.begin(), all.end()); + std::vector out; + for (size_t i = 0; i < std::min(k, all.size()); ++i) { + out.push_back(all[i].second); + } + return out; + }; + + auto check = [&](auto&& filter, bool expect_full) { + auto results = svs::QueryResult(num_queries, k); + std::vector found; + search_filtered(results, filter, found); + CATCH_REQUIRE(found.size() == num_queries); + size_t hits = 0, total = 0; + for (size_t q = 0; q < num_queries; ++q) { + auto gt = brute_force(q, filter); + CATCH_REQUIRE(found[q] <= k); + if (expect_full) { + CATCH_REQUIRE(found[q] == k); + } + for (size_t j = 0; j < found[q]; ++j) { + size_t id = results.index(q, j); + CATCH_REQUIRE(filter(id)); + CATCH_REQUIRE(!deleted.contains(id)); + hits += std::count(gt.begin(), gt.end(), id); + } + for (size_t j = found[q]; j < k; ++j) { + CATCH_REQUIRE(results.index(q, j) == static_cast(-1)); + CATCH_REQUIRE( + results.distance(q, j) == std::numeric_limits::infinity() + ); + } + total += gt.size(); + } + return double(hits) / double(total); + }; + + auto mod10 = [](size_t e) { return e % 10 == 0; }; + + CATCH_SECTION("recall against brute force") { + CATCH_REQUIRE(check(mod10, true) >= 0.95); + } + + CATCH_SECTION("deleted ids are never returned") { + std::vector to_delete; + for (size_t i = 0; i < n; i += 3) { + to_delete.push_back(ids[i]); + } + index.delete_entries(to_delete); + deleted.insert(to_delete.begin(), to_delete.end()); + CATCH_REQUIRE(check(mod10, true) >= 0.9); + CATCH_REQUIRE(check([](size_t) { return true; }, true) >= 0.9); + } + + CATCH_SECTION("fewer than k passing ids are padded") { + auto few = [](size_t e) { return e == 100 || e == 200 || e == 300; }; + check(few, false); + auto results = svs::QueryResult(num_queries, k); + std::vector found; + search_filtered(results, few, found); + for (size_t q = 0; q < num_queries; ++q) { + CATCH_REQUIRE(found[q] == 3); + } + auto none = [](size_t) { return false; }; + search_filtered(results, none, found); + for (size_t q = 0; q < num_queries; ++q) { + CATCH_REQUIRE(found[q] == 0); + } + } + + CATCH_SECTION("unfiltered search is unchanged by the optional argument") { + index.delete_entries(std::vector{ids[0], ids[1], ids[2]}); + auto plain = svs::QueryResult(num_queries, k); + auto with_null = svs::QueryResult(num_queries, k); + index.search(plain.view(), queries.cview(), sp); + index.search( + with_null.view(), + queries.cview(), + sp, + svs::lib::Returns(svs::lib::Const()), + nullptr + ); + for (size_t q = 0; q < num_queries; ++q) { + for (size_t j = 0; j < k; ++j) { + CATCH_REQUIRE(plain.index(q, j) == with_null.index(q, j)); + CATCH_REQUIRE(plain.distance(q, j) == with_null.distance(q, j)); + } + } + } + + CATCH_SECTION("inner product pads with the worst score (-inf)") { + auto data_ip = svs::data::BlockedData(n, dim); + for (size_t i = 0; i < n; ++i) { + data_ip.set_datum(i, raw[i]); + } + svs::index::vamana::VamanaBuildParameters parameters_ip{0.95, 32, 64, 64, 32, true}; + auto index_ip = svs::index::vamana::MutableVamanaIndex( + parameters_ip, std::move(data_ip), ids, svs::distance::DistanceIP(), num_threads + ); + std::function few = [](size_t e) { return e == 100 || e == 200; }; + auto results = svs::QueryResult(num_queries, k); + index_ip.search( + results.view(), + queries.cview(), + sp, + svs::lib::Returns(svs::lib::Const()), + &few + ); + for (size_t q = 0; q < num_queries; ++q) { + for (size_t j = 2; j < k; ++j) { + CATCH_REQUIRE(results.index(q, j) == static_cast(-1)); + CATCH_REQUIRE( + results.distance(q, j) == -std::numeric_limits::infinity() + ); + } + } + } + + CATCH_SECTION("orchestrator entry point") { + auto dyn = svs::DynamicVamana::build( + parameters, + [&] { + auto d = svs::data::SimpleData(n, dim); + for (size_t i = 0; i < n; ++i) { + d.set_datum(i, raw[i]); + } + return d; + }(), + ids, + Distance(), + num_threads + ); + auto results = svs::QueryResult(num_queries, k); + CATCH_REQUIRE(dyn.filtered_search( + results.view(), queries.cview(), sp, std::function(mod10) + )); + for (size_t q = 0; q < num_queries; ++q) { + for (size_t j = 0; j < k; ++j) { + CATCH_REQUIRE(mod10(results.index(q, j))); + } + } + } +} From 6861c4b0eced3a5cfe5b0a93fd43ee66ba960cd9 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Tue, 3 Nov 2026 18:08:17 -0800 Subject: [PATCH 02/16] Read external ids without a lock in filtered search --- include/svs/concurrent/dynamic_index.h | 56 +++++++++++++++++++++----- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index eb3caeab5..f8ffd17b6 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -148,18 +148,18 @@ enum class ReplaceExternalIdResult : uint8_t { inline constexpr size_t no_external_id = type_traits::sentinel_v, std::less<>>.id(); -template class ValidBuilder { +template class ValidBuilder { public: // Optional `filter` (with `index`): an entry is also invalid if // `filter(external_id)` is false. Invalid entries are navigated through but never // returned. ValidBuilder( const lib::SegmentedVector& status, - const Index* index = nullptr, + const lib::SegmentedVector* external_ids = nullptr, const std::function* filter = nullptr ) : status_{status} - , index_{index} + , external_ids_{external_ids} , filter_{filter} {} /// Filtered only: skip the filter for entries `buffer` would drop anyway. @@ -188,9 +188,11 @@ template class ValidBuilder { // marks this slot as deleted. if constexpr (Filtered) { if (!invalid) { - // Locks the translation per lookup so writers keep running. An id erased - // concurrently has no external id and fails the filter. - size_t external = index_->translate_internal_id(i); + // Lock-free: the id was stored before the slot's Valid release above. + size_t external = + std::atomic_ref(const_cast(getindex(*external_ids_, i)) + ) + .load(std::memory_order_acquire); invalid = external == no_external_id || !(*filter_)(external); } } @@ -199,7 +201,7 @@ template class ValidBuilder { private: const lib::SegmentedVector& status_; - const Index* index_; + const lib::SegmentedVector* external_ids_; const std::function* filter_; const void* skip_buffer_ = nullptr; bool (*skip_)(const void*, float) = nullptr; @@ -255,6 +257,9 @@ class MutableVamanaIndex { // Grow-stable per-slot metadata: search reads status_[i] lock-free via ValidBuilder // while a concurrent add_points grows it. See svs/lib/segmented_vector.h. lib::SegmentedVector status_; + // External id of each slot (or no_external_id); mirrors translator_ for lock-free + // reads. + lib::SegmentedVector external_ids_; // a lower bound such that the append path // (reuse_empty == false) scans for Empty slots starting here. std::unique_ptr> first_empty_{ @@ -338,6 +343,7 @@ class MutableVamanaIndex { , data_{std::move(data)} , entry_point_{data_.size() == 0 ? NO_ENTRY : entry_point} , status_(data_.size(), SlotMetadata::Valid) + , external_ids_(data_.size(), no_external_id) , first_empty_{std::make_unique>(data_.size())} , first_reusable_{std::make_unique>(data_.size())} , translator_() @@ -355,6 +361,9 @@ class MutableVamanaIndex { throw ANNEXCEPTION("Graph node count does not match external IDs size"); } translator_.insert(external_ids, threads::UnitRange(0, external_ids.size())); + for (auto pair : translator_) { + external_ids_[pair.second] = pair.first; + } } public: @@ -497,6 +506,7 @@ class MutableVamanaIndex { , data_{std::move(data)} , entry_point_{data_.size() == 0 ? NO_ENTRY : lib::narrow(config.entry_point)} , status_{data_.size(), SlotMetadata::Empty} // filled later in the body + , external_ids_{data_.size(), no_external_id} , first_empty_{std::make_unique>(data_.size())} , first_reusable_{std::make_unique>(data_.size())} , translator_{std::move(translator)} @@ -562,6 +572,7 @@ class MutableVamanaIndex { pair.second ); } + external_ids_[pair.second] = pair.first; } num_valid_->store(num_valid); @@ -872,7 +883,10 @@ class MutableVamanaIndex { return ReplaceExternalIdResult::OldIdMissing; } try { + auto slot = translator_.get_internal(old_id); translator_.remap_external_id(old_id, new_id); + std::atomic_ref(external_ids_[slot]) + .store(new_id, std::memory_order_relaxed); } catch (const ANNException&) { return ReplaceExternalIdResult::NewIdExists; } return ReplaceExternalIdResult::Ok; } @@ -918,9 +932,9 @@ class MutableVamanaIndex { // Return a `greedy_search` compatible builder for this index. // This is an internal method, mostly used to help implement the batch iterator. template - ValidBuilder + ValidBuilder internal_search_builder(const std::function* filter = nullptr) const { - return ValidBuilder{status_, this, filter}; + return ValidBuilder{status_, &external_ids_, filter}; } /// @brief RAII shared lock guarding data_/graph_ against compact()'s shrink @@ -1226,6 +1240,7 @@ class MutableVamanaIndex { data_.resize(new_size); graph_.unsafe_resize(new_size); status_.resize(new_size, SlotMetadata::Empty); + external_ids_.resize(new_size, no_external_id); for (size_t i = current_size; i < new_size; ++i) { std::atomic_ref(status_[i]) .store(SlotMetadata::Pending, std::memory_order_release); @@ -1246,6 +1261,12 @@ class MutableVamanaIndex { // maps to a live slot. try { std::lock_guard lock{*translator_mutex_}; + std::vector stale{}; + for (auto e : external_ids) { + if (translator_.has_external(e)) { + stale.push_back(translator_.get_internal(e)); + } + } translator_ .replace_stale_and_insert(external_ids, slots, [this](auto internal) { return std::atomic_ref( @@ -1253,6 +1274,17 @@ class MutableVamanaIndex { ) .load(std::memory_order_acquire) == SlotMetadata::Deleted; }); + // Slots whose mapping was just erased must not keep a now-live id. + for (auto s : stale) { + std::atomic_ref(external_ids_[s]) + .store(no_external_id, std::memory_order_relaxed); + } + // Stored before the slots turn Valid (release), which readers pair with. + size_t j = 0; + for (auto e : external_ids) { + std::atomic_ref(external_ids_[slots[j++]]) + .store(e, std::memory_order_relaxed); + } } catch (...) { // Release the reserved slots back to Empty. for (auto s : slots) { @@ -1598,11 +1630,13 @@ class MutableVamanaIndex { auto status = getindex(status_, old_id); status_[new_id] = status; + external_ids_[new_id] = getindex(external_ids_, old_id); if (status == SlotMetadata::Valid) { translator_.remap_internal_id(old_id, new_id); } } status_.resize(max_index); + external_ids_.resize(max_index); // Remap the surviving anchor, or publish the genuinely empty state. auto ep = old_to_new_id_map.find(entry_point()); @@ -1737,6 +1771,10 @@ class MutableVamanaIndex { } } if (!deleted_internal_ids.empty()) { + for (auto i : deleted_internal_ids) { + std::atomic_ref(external_ids_[i]) + .store(no_external_id, std::memory_order_relaxed); + } translator_.delete_internal(deleted_internal_ids, false); } // The anchor's external mapping is removed above like any deletion, From 8f64dddc058df6a4f8a15b80175598cd1864ac96 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Wed, 4 Nov 2026 09:32:23 -0800 Subject: [PATCH 03/16] Use the translator shared lock once per search in filtered search --- include/svs/concurrent/dynamic_index.h | 71 ++++++++------------------ 1 file changed, 21 insertions(+), 50 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index f8ffd17b6..eddaffa28 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -148,18 +148,18 @@ enum class ReplaceExternalIdResult : uint8_t { inline constexpr size_t no_external_id = type_traits::sentinel_v, std::less<>>.id(); -template class ValidBuilder { +template class ValidBuilder { public: // Optional `filter` (with `index`): an entry is also invalid if // `filter(external_id)` is false. Invalid entries are navigated through but never // returned. ValidBuilder( const lib::SegmentedVector& status, - const lib::SegmentedVector* external_ids = nullptr, + const Index* index = nullptr, const std::function* filter = nullptr ) : status_{status} - , external_ids_{external_ids} + , index_{index} , filter_{filter} {} /// Filtered only: skip the filter for entries `buffer` would drop anyway. @@ -188,11 +188,9 @@ template class ValidBuilder { // marks this slot as deleted. if constexpr (Filtered) { if (!invalid) { - // Lock-free: the id was stored before the slot's Valid release above. - size_t external = - std::atomic_ref(const_cast(getindex(*external_ids_, i)) - ) - .load(std::memory_order_acquire); + // The caller holds `lock_for_translation()`. An id erased before the lock + // was taken has no external id and fails the filter. + size_t external = index_->unsafe_translate_internal_id(i); invalid = external == no_external_id || !(*filter_)(external); } } @@ -201,7 +199,7 @@ template class ValidBuilder { private: const lib::SegmentedVector& status_; - const lib::SegmentedVector* external_ids_; + const Index* index_; const std::function* filter_; const void* skip_buffer_ = nullptr; bool (*skip_)(const void*, float) = nullptr; @@ -257,9 +255,6 @@ class MutableVamanaIndex { // Grow-stable per-slot metadata: search reads status_[i] lock-free via ValidBuilder // while a concurrent add_points grows it. See svs/lib/segmented_vector.h. lib::SegmentedVector status_; - // External id of each slot (or no_external_id); mirrors translator_ for lock-free - // reads. - lib::SegmentedVector external_ids_; // a lower bound such that the append path // (reuse_empty == false) scans for Empty slots starting here. std::unique_ptr> first_empty_{ @@ -343,7 +338,6 @@ class MutableVamanaIndex { , data_{std::move(data)} , entry_point_{data_.size() == 0 ? NO_ENTRY : entry_point} , status_(data_.size(), SlotMetadata::Valid) - , external_ids_(data_.size(), no_external_id) , first_empty_{std::make_unique>(data_.size())} , first_reusable_{std::make_unique>(data_.size())} , translator_() @@ -361,9 +355,6 @@ class MutableVamanaIndex { throw ANNEXCEPTION("Graph node count does not match external IDs size"); } translator_.insert(external_ids, threads::UnitRange(0, external_ids.size())); - for (auto pair : translator_) { - external_ids_[pair.second] = pair.first; - } } public: @@ -506,7 +497,6 @@ class MutableVamanaIndex { , data_{std::move(data)} , entry_point_{data_.size() == 0 ? NO_ENTRY : lib::narrow(config.entry_point)} , status_{data_.size(), SlotMetadata::Empty} // filled later in the body - , external_ids_{data_.size(), no_external_id} , first_empty_{std::make_unique>(data_.size())} , first_reusable_{std::make_unique>(data_.size())} , translator_{std::move(translator)} @@ -572,7 +562,6 @@ class MutableVamanaIndex { pair.second ); } - external_ids_[pair.second] = pair.first; } num_valid_->store(num_valid); @@ -883,10 +872,7 @@ class MutableVamanaIndex { return ReplaceExternalIdResult::OldIdMissing; } try { - auto slot = translator_.get_internal(old_id); translator_.remap_external_id(old_id, new_id); - std::atomic_ref(external_ids_[slot]) - .store(new_id, std::memory_order_relaxed); } catch (const ANNException&) { return ReplaceExternalIdResult::NewIdExists; } return ReplaceExternalIdResult::Ok; } @@ -932,9 +918,9 @@ class MutableVamanaIndex { // Return a `greedy_search` compatible builder for this index. // This is an internal method, mostly used to help implement the batch iterator. template - ValidBuilder + ValidBuilder internal_search_builder(const std::function* filter = nullptr) const { - return ValidBuilder{status_, &external_ids_, filter}; + return ValidBuilder{status_, this, filter}; } /// @brief RAII shared lock guarding data_/graph_ against compact()'s shrink @@ -1013,6 +999,8 @@ class MutableVamanaIndex { ); } + // `filter` runs while this thread holds the translator lock shared: it must not call + // back into this index (no writers, no self-locking readers such as `has_id`). template void search( QueryResultView results, @@ -1062,6 +1050,8 @@ class MutableVamanaIndex { prefetch_parameters, cancel, filter ); if constexpr (Filtered) { + // Held once for this thread's queries, not per lookup. + auto translation_lock = lock_for_translation(); run(extensions::FilteredSearch{search, filter} ); } else { @@ -1240,7 +1230,6 @@ class MutableVamanaIndex { data_.resize(new_size); graph_.unsafe_resize(new_size); status_.resize(new_size, SlotMetadata::Empty); - external_ids_.resize(new_size, no_external_id); for (size_t i = current_size; i < new_size; ++i) { std::atomic_ref(status_[i]) .store(SlotMetadata::Pending, std::memory_order_release); @@ -1261,12 +1250,6 @@ class MutableVamanaIndex { // maps to a live slot. try { std::lock_guard lock{*translator_mutex_}; - std::vector stale{}; - for (auto e : external_ids) { - if (translator_.has_external(e)) { - stale.push_back(translator_.get_internal(e)); - } - } translator_ .replace_stale_and_insert(external_ids, slots, [this](auto internal) { return std::atomic_ref( @@ -1274,17 +1257,6 @@ class MutableVamanaIndex { ) .load(std::memory_order_acquire) == SlotMetadata::Deleted; }); - // Slots whose mapping was just erased must not keep a now-live id. - for (auto s : stale) { - std::atomic_ref(external_ids_[s]) - .store(no_external_id, std::memory_order_relaxed); - } - // Stored before the slots turn Valid (release), which readers pair with. - size_t j = 0; - for (auto e : external_ids) { - std::atomic_ref(external_ids_[slots[j++]]) - .store(e, std::memory_order_relaxed); - } } catch (...) { // Release the reserved slots back to Empty. for (auto s : slots) { @@ -1630,13 +1602,11 @@ class MutableVamanaIndex { auto status = getindex(status_, old_id); status_[new_id] = status; - external_ids_[new_id] = getindex(external_ids_, old_id); if (status == SlotMetadata::Valid) { translator_.remap_internal_id(old_id, new_id); } } status_.resize(max_index); - external_ids_.resize(max_index); // Remap the surviving anchor, or publish the genuinely empty state. auto ep = old_to_new_id_map.find(entry_point()); @@ -1771,10 +1741,6 @@ class MutableVamanaIndex { } } if (!deleted_internal_ids.empty()) { - for (auto i : deleted_internal_ids) { - std::atomic_ref(external_ids_[i]) - .store(no_external_id, std::memory_order_relaxed); - } translator_.delete_internal(deleted_internal_ids, false); } // The anchor's external mapping is removed above like any deletion, @@ -2132,7 +2098,8 @@ class MutableVamanaIndex { /// ``translator_mutex_`` shared (preserving the global compact -> translator order) /// and skipping slots that are no longer ``Valid``. /// - /// Called from the ``extensions::single_search`` override below. + /// Called from the ``extensions::single_search`` override below. With a ``filter`` the + /// caller must hold ``lock_for_translation()`` (``search()`` does). /// template void supplement_search_buffer( @@ -2147,8 +2114,12 @@ class MutableVamanaIndex { search_buffer.sort(); // translator_mutex_ shared: guards both the traversal of ``translator_`` and the - // internal IDs it yields against erasure by consolidate()/compact(). - std::shared_lock translator_lock{*translator_mutex_}; + // internal IDs it yields against erasure by consolidate()/compact(). A filtered + // search already holds it (see ``search()``); locking again would be recursive. + std::shared_lock translator_lock{*translator_mutex_, std::defer_lock}; + if (filter == nullptr) { + translator_lock.lock(); + } auto builder = internal_search_builder(); for (auto pair : translator_) { auto internal_id = pair.second; From 4331ea189e63155e9cc7453bf44b1770376b4090 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Thu, 5 Nov 2026 11:34:36 -0800 Subject: [PATCH 04/16] Remove the filtered-search test changes --- tests/svs/index/vamana/dynamic_index.cpp | 222 ----------------------- 1 file changed, 222 deletions(-) diff --git a/tests/svs/index/vamana/dynamic_index.cpp b/tests/svs/index/vamana/dynamic_index.cpp index 6bedb8ea8..94daddcf1 100644 --- a/tests/svs/index/vamana/dynamic_index.cpp +++ b/tests/svs/index/vamana/dynamic_index.cpp @@ -23,14 +23,11 @@ #include #include #include -#include #include #include -#include #include #include #include -#include // svs #include "svs/core/recall.h" @@ -467,222 +464,3 @@ CATCH_TEST_CASE("MutableVamana Index Memory Usage", "[graph_index][dynamic_index const size_t usage = index.get_memory_breakdown().total(); CATCH_REQUIRE(usage == expected_total_bytes); } - -CATCH_TEST_CASE( - "MutableVamana Index Filtered Search", "[graph_index][dynamic_index][filtered]" -) { - const size_t num_threads = 2; - const size_t n = 3000; - const size_t dim = 32; - const size_t num_queries = 50; - const size_t k = 10; - using Distance = svs::distance::DistanceL2; - - std::mt19937 rng(42); - std::normal_distribution normal; - auto data = svs::data::BlockedData(n, dim); - std::vector> raw(n, std::vector(dim)); - for (size_t i = 0; i < n; ++i) { - for (auto& x : raw[i]) { - x = normal(rng); - } - data.set_datum(i, raw[i]); - } - auto queries = svs::data::SimpleData(num_queries, dim); - for (size_t i = 0; i < num_queries; ++i) { - std::vector q(dim); - for (auto& x : q) { - x = normal(rng); - } - queries.set_datum(i, q); - } - - // External ids differ from internal ids. - std::vector ids(n); - std::iota(ids.begin(), ids.end(), 7); - svs::index::vamana::VamanaBuildParameters parameters{1.2, 32, 64, 64, 32, true}; - auto index = svs::index::vamana::MutableVamanaIndex( - parameters, std::move(data), ids, Distance(), num_threads - ); - - auto sp = svs::index::vamana::VamanaSearchParameters{}; - sp.buffer_config_ = svs::index::vamana::SearchBufferConfig{50}; - - // Runs the filtered search; `found` = number of non-padding ids per query. - auto search_filtered = [&](auto& results, - const std::function& filter, - std::vector& found) { - index.search( - results.view(), - queries.cview(), - sp, - svs::lib::Returns(svs::lib::Const()), - &filter - ); - found.assign(num_queries, 0); - for (size_t q = 0; q < num_queries; ++q) { - for (size_t j = 0; j < k; ++j) { - found[q] += results.index(q, j) != static_cast(-1); - } - } - }; - - // Brute force over live ids passing `filter`. - std::unordered_set deleted; - auto brute_force = [&](size_t q, auto&& filter) { - std::vector> all; - for (size_t i = 0; i < n; ++i) { - size_t e = ids[i]; - if (deleted.contains(e) || !filter(e)) { - continue; - } - float d = 0; - for (size_t j = 0; j < dim; ++j) { - float diff = queries.get_datum(q)[j] - raw[i][j]; - d += diff * diff; - } - all.emplace_back(d, e); - } - std::sort(all.begin(), all.end()); - std::vector out; - for (size_t i = 0; i < std::min(k, all.size()); ++i) { - out.push_back(all[i].second); - } - return out; - }; - - auto check = [&](auto&& filter, bool expect_full) { - auto results = svs::QueryResult(num_queries, k); - std::vector found; - search_filtered(results, filter, found); - CATCH_REQUIRE(found.size() == num_queries); - size_t hits = 0, total = 0; - for (size_t q = 0; q < num_queries; ++q) { - auto gt = brute_force(q, filter); - CATCH_REQUIRE(found[q] <= k); - if (expect_full) { - CATCH_REQUIRE(found[q] == k); - } - for (size_t j = 0; j < found[q]; ++j) { - size_t id = results.index(q, j); - CATCH_REQUIRE(filter(id)); - CATCH_REQUIRE(!deleted.contains(id)); - hits += std::count(gt.begin(), gt.end(), id); - } - for (size_t j = found[q]; j < k; ++j) { - CATCH_REQUIRE(results.index(q, j) == static_cast(-1)); - CATCH_REQUIRE( - results.distance(q, j) == std::numeric_limits::infinity() - ); - } - total += gt.size(); - } - return double(hits) / double(total); - }; - - auto mod10 = [](size_t e) { return e % 10 == 0; }; - - CATCH_SECTION("recall against brute force") { - CATCH_REQUIRE(check(mod10, true) >= 0.95); - } - - CATCH_SECTION("deleted ids are never returned") { - std::vector to_delete; - for (size_t i = 0; i < n; i += 3) { - to_delete.push_back(ids[i]); - } - index.delete_entries(to_delete); - deleted.insert(to_delete.begin(), to_delete.end()); - CATCH_REQUIRE(check(mod10, true) >= 0.9); - CATCH_REQUIRE(check([](size_t) { return true; }, true) >= 0.9); - } - - CATCH_SECTION("fewer than k passing ids are padded") { - auto few = [](size_t e) { return e == 100 || e == 200 || e == 300; }; - check(few, false); - auto results = svs::QueryResult(num_queries, k); - std::vector found; - search_filtered(results, few, found); - for (size_t q = 0; q < num_queries; ++q) { - CATCH_REQUIRE(found[q] == 3); - } - auto none = [](size_t) { return false; }; - search_filtered(results, none, found); - for (size_t q = 0; q < num_queries; ++q) { - CATCH_REQUIRE(found[q] == 0); - } - } - - CATCH_SECTION("unfiltered search is unchanged by the optional argument") { - index.delete_entries(std::vector{ids[0], ids[1], ids[2]}); - auto plain = svs::QueryResult(num_queries, k); - auto with_null = svs::QueryResult(num_queries, k); - index.search(plain.view(), queries.cview(), sp); - index.search( - with_null.view(), - queries.cview(), - sp, - svs::lib::Returns(svs::lib::Const()), - nullptr - ); - for (size_t q = 0; q < num_queries; ++q) { - for (size_t j = 0; j < k; ++j) { - CATCH_REQUIRE(plain.index(q, j) == with_null.index(q, j)); - CATCH_REQUIRE(plain.distance(q, j) == with_null.distance(q, j)); - } - } - } - - CATCH_SECTION("inner product pads with the worst score (-inf)") { - auto data_ip = svs::data::BlockedData(n, dim); - for (size_t i = 0; i < n; ++i) { - data_ip.set_datum(i, raw[i]); - } - svs::index::vamana::VamanaBuildParameters parameters_ip{0.95, 32, 64, 64, 32, true}; - auto index_ip = svs::index::vamana::MutableVamanaIndex( - parameters_ip, std::move(data_ip), ids, svs::distance::DistanceIP(), num_threads - ); - std::function few = [](size_t e) { return e == 100 || e == 200; }; - auto results = svs::QueryResult(num_queries, k); - index_ip.search( - results.view(), - queries.cview(), - sp, - svs::lib::Returns(svs::lib::Const()), - &few - ); - for (size_t q = 0; q < num_queries; ++q) { - for (size_t j = 2; j < k; ++j) { - CATCH_REQUIRE(results.index(q, j) == static_cast(-1)); - CATCH_REQUIRE( - results.distance(q, j) == -std::numeric_limits::infinity() - ); - } - } - } - - CATCH_SECTION("orchestrator entry point") { - auto dyn = svs::DynamicVamana::build( - parameters, - [&] { - auto d = svs::data::SimpleData(n, dim); - for (size_t i = 0; i < n; ++i) { - d.set_datum(i, raw[i]); - } - return d; - }(), - ids, - Distance(), - num_threads - ); - auto results = svs::QueryResult(num_queries, k); - CATCH_REQUIRE(dyn.filtered_search( - results.view(), queries.cview(), sp, std::function(mod10) - )); - for (size_t q = 0; q < num_queries; ++q) { - for (size_t j = 0; j < k; ++j) { - CATCH_REQUIRE(mod10(results.index(q, j))); - } - } - } -} From 4a80cf6011ab4ccc9b8df0f084fc8552b28fd848 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Thu, 5 Nov 2026 12:24:19 -0800 Subject: [PATCH 05/16] Remove dead code and trim comments in filtered search Clarify the ValidBuilder comment Put the ValidBuilder comment on the class Shorten the ValidBuilder comment Shorten comments and drop a redundant template argument --- include/svs/concurrent/dynamic_index.h | 33 +++++++-------- include/svs/index/vamana/dynamic_index.h | 9 +--- include/svs/index/vamana/extensions.h | 3 +- include/svs/orchestrators/dynamic_vamana.h | 49 ++++++++-------------- 4 files changed, 35 insertions(+), 59 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index eddaffa28..a4a983006 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -148,21 +148,19 @@ enum class ReplaceExternalIdResult : uint8_t { inline constexpr size_t no_external_id = type_traits::sentinel_v, std::less<>>.id(); -template class ValidBuilder { +// Template so the compiler builds a separate regular-search copy with no filter check. +template class ValidBuilder { public: - // Optional `filter` (with `index`): an entry is also invalid if - // `filter(external_id)` is false. Invalid entries are navigated through but never - // returned. ValidBuilder( const lib::SegmentedVector& status, - const Index* index = nullptr, + const IDTranslator* translator = nullptr, const std::function* filter = nullptr ) : status_{status} - , index_{index} + , translator_{translator} , filter_{filter} {} - /// Filtered only: skip the filter for entries `buffer` would drop anyway. + // Once the window is full, only candidates closer than its worst entry are filtered. template void skip_if_dropped_by(const Buffer& buffer) { skip_buffer_ = &buffer; skip_ = [](const void* b, float d) { @@ -188,9 +186,8 @@ template class ValidBuilder { // marks this slot as deleted. if constexpr (Filtered) { if (!invalid) { - // The caller holds `lock_for_translation()`. An id erased before the lock - // was taken has no external id and fails the filter. - size_t external = index_->unsafe_translate_internal_id(i); + // Lock-free read; an erased slot has no external id and fails. + size_t external = translator_->get_external_or(i, no_external_id); invalid = external == no_external_id || !(*filter_)(external); } } @@ -199,7 +196,7 @@ template class ValidBuilder { private: const lib::SegmentedVector& status_; - const Index* index_; + const IDTranslator* translator_; const std::function* filter_; const void* skip_buffer_ = nullptr; bool (*skip_)(const void*, float) = nullptr; @@ -918,9 +915,9 @@ class MutableVamanaIndex { // Return a `greedy_search` compatible builder for this index. // This is an internal method, mostly used to help implement the batch iterator. template - ValidBuilder + ValidBuilder internal_search_builder(const std::function* filter = nullptr) const { - return ValidBuilder{status_, this, filter}; + return ValidBuilder{status_, &translator_, filter}; } /// @brief RAII shared lock guarding data_/graph_ against compact()'s shrink @@ -994,13 +991,12 @@ class MutableVamanaIndex { scratch.buffer, scratch.scratch, query, - greedy_search_closure(scratch.prefetch_parameters, cancel), + greedy_search_closure(scratch.prefetch_parameters, cancel), *this ); } - // `filter` runs while this thread holds the translator lock shared: it must not call - // back into this index (no writers, no self-locking readers such as `has_id`). + // `filter` is called from every search thread without locks; it must be thread-safe. template void search( QueryResultView results, @@ -2098,8 +2094,7 @@ class MutableVamanaIndex { /// ``translator_mutex_`` shared (preserving the global compact -> translator order) /// and skipping slots that are no longer ``Valid``. /// - /// Called from the ``extensions::single_search`` override below. With a ``filter`` the - /// caller must hold ``lock_for_translation()`` (``search()`` does). + /// Called from the ``extensions::single_search`` override below. /// template void supplement_search_buffer( @@ -2219,7 +2214,7 @@ SVS_FORCE_INLINE void svs_invoke( } const std::function* filter = nullptr; if constexpr (requires { search.filter; }) { - filter = search.filter; // Filtered search: keep filtered-out ids out of the top-up. + filter = search.filter; } index.supplement_search_buffer(search_buffer, query, filter); } diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index b06043083..c14bdddef 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -92,11 +92,9 @@ inline constexpr std::string_view name(SlotMetadata metadata) { } // clang-format on +// Template so the compiler builds a separate regular-search copy with no filter check. template class ValidBuilder { public: - // Optional `filter` (with `translator`): an entry is also invalid if - // `filter(external_id)` is false. Invalid entries are navigated through but never - // returned. ValidBuilder( const std::vector& status, const IDTranslator* translator = nullptr, @@ -106,7 +104,7 @@ template class ValidBuilder { , translator_{translator} , filter_{filter} {} - /// Filtered only: skip the filter for entries `buffer` would drop anyway. + // Once the window is full, only candidates closer than its worst entry are filtered. template void skip_if_dropped_by(const Buffer& buffer) { skip_buffer_ = &buffer; skip_ = [](const void* b, float d) { @@ -774,9 +772,6 @@ class MutableVamanaIndex { const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), const std::function* filter = nullptr ) { - // Optional `filter`: only entries whose external id passes are returned. It is - // called from all search threads. Rows with fewer passing entries than requested - // are padded with id `size_t(-1)` and the worst score. threads::parallel_for( threadpool_, threads::StaticPartition{queries.size()}, diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index 9ec594486..a745a7401 100644 --- a/include/svs/index/vamana/extensions.h +++ b/include/svs/index/vamana/extensions.h @@ -501,8 +501,7 @@ SVS_FORCE_INLINE void svs_invoke( if constexpr (Index::needs_id_translation) { const std::function* filter = nullptr; if constexpr (requires { search.filter; }) { - filter = - search.filter; // Filtered search: keep filtered-out ids out of the top-up. + filter = search.filter; } check_and_supplement_search_buffer(index, search_buffer, query, filter); } diff --git a/include/svs/orchestrators/dynamic_vamana.h b/include/svs/orchestrators/dynamic_vamana.h index 92d8d1e60..6ace9b035 100644 --- a/include/svs/orchestrators/dynamic_vamana.h +++ b/include/svs/orchestrators/dynamic_vamana.h @@ -124,36 +124,23 @@ class DynamicVamanaImpl : public VamanaImpl& filter ) override { - // Filtered search is available for every data type. Indexes whose `search` has no - // filter argument (e.g. the concurrent index) report "unsupported". - constexpr bool supported = requires( - Impl & idx, - svs::QueryResultView r, - data::ConstSimpleDataView q, - const index::vamana::VamanaSearchParameters& sp, - const std::function* filter - ) { idx.search(r, q, sp, lib::Returns(lib::Const()), filter); }; - if constexpr (supported) { - lib::match( - QueryTypes{}, - queries.type(), - [&](lib::Type SVS_UNUSED(type)) { - impl().search( - results, - data::ConstSimpleDataView(queries), - search_parameters, - lib::Returns(lib::Const()), - &filter - ); - }, - [&](svs::DataType data_type) { - throw ANNEXCEPTION("Unsupported query datatype! Got: {}.", data_type); - } - ); - return true; - } else { - return false; - } + lib::match( + QueryTypes{}, + queries.type(), + [&](lib::Type SVS_UNUSED(type)) { + impl().search( + results, + data::ConstSimpleDataView(queries), + search_parameters, + lib::Returns(lib::Const()), + &filter + ); + }, + [&](svs::DataType data_type) { + throw ANNEXCEPTION("Unsupported query datatype! Got: {}.", data_type); + } + ); + return true; } }; @@ -657,7 +644,7 @@ class DynamicVamana : public manager::IndexManager { bool is_consolidated() const { return impl_->is_consolidated(); } /// @brief Filtered search: only ids for which ``filter(id)`` is true are returned. - /// Returns false if the data type does not support it. + /// Rows with fewer passing entries than requested are padded with id ``size_t(-1)``. template bool filtered_search( QueryResultView results, From bb8df6c275d2f81f4255323b861eb3e2a901c604 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Fri, 6 Nov 2026 14:52:22 -0800 Subject: [PATCH 06/16] Address review: padding and FilteredValidBuilder Filtered search on the static Vamana index Fix unused lambda capture in regular search Fix unused lambda capture in concurrent regular search --- include/svs/concurrent/dynamic_index.h | 105 ++++++++----- include/svs/index/vamana/dynamic_index.h | 91 ++++++----- include/svs/index/vamana/extensions.h | 19 ++- include/svs/index/vamana/index.h | 169 +++++++++++++++------ include/svs/orchestrators/dynamic_vamana.h | 33 ---- include/svs/orchestrators/vamana.h | 48 ++++++ 6 files changed, 296 insertions(+), 169 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index a4a983006..ddba11c3c 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -148,17 +148,40 @@ enum class ReplaceExternalIdResult : uint8_t { inline constexpr size_t no_external_id = type_traits::sentinel_v, std::less<>>.id(); -// Template so the compiler builds a separate regular-search copy with no filter check. -template class ValidBuilder { +class ValidBuilder { public: - ValidBuilder( + ValidBuilder(const lib::SegmentedVector& status) + : status_{status} {} + + template + constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { + // A neighbor is returnable only if its slot is Valid. Deleted slots + // must be skipped; Pending slots are reserved by an in-flight add and + // their vectors/edges are not yet fully published. Empty slots should + // never be reached via a valid edge, but we defend anyway. + bool invalid = + std::atomic_ref(const_cast(getindex(status_, i))) + .load(std::memory_order_acquire) != SlotMetadata::Valid; + // This neighbor should be skipped if the metadata corresponding to the given index + // marks this slot as deleted. + return PredicatedSearchNeighbor(i, distance, !invalid); + } + + private: + const lib::SegmentedVector& status_; +}; + +// Separate template so the regular search compiles without any filter check. +template class FilteredValidBuilder { + public: + FilteredValidBuilder( const lib::SegmentedVector& status, - const IDTranslator* translator = nullptr, - const std::function* filter = nullptr + const IDTranslator& translator, + const Filter& filter ) : status_{status} - , translator_{translator} - , filter_{filter} {} + , translator_{&translator} + , filter_{&filter} {} // Once the window is full, only candidates closer than its worst entry are filtered. template void skip_if_dropped_by(const Buffer& buffer) { @@ -170,26 +193,16 @@ template class ValidBuilder { template constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { - if constexpr (Filtered) { - if (skip_ != nullptr && skip_(skip_buffer_, distance)) { - return PredicatedSearchNeighbor(i, distance, false); - } + if (skip_ != nullptr && skip_(skip_buffer_, distance)) { + return PredicatedSearchNeighbor(i, distance, false); } - // A neighbor is returnable only if its slot is Valid. Deleted slots - // must be skipped; Pending slots are reserved by an in-flight add and - // their vectors/edges are not yet fully published. Empty slots should - // never be reached via a valid edge, but we defend anyway. bool invalid = std::atomic_ref(const_cast(getindex(status_, i))) .load(std::memory_order_acquire) != SlotMetadata::Valid; - // This neighbor should be skipped if the metadata corresponding to the given index - // marks this slot as deleted. - if constexpr (Filtered) { - if (!invalid) { - // Lock-free read; an erased slot has no external id and fails. - size_t external = translator_->get_external_or(i, no_external_id); - invalid = external == no_external_id || !(*filter_)(external); - } + if (!invalid) { + // Lock-free read; an erased slot has no external id and fails. + size_t external = translator_->get_external_or(i, no_external_id); + invalid = external == no_external_id || !(*filter_)(external); } return PredicatedSearchNeighbor(i, distance, !invalid); } @@ -197,7 +210,7 @@ template class ValidBuilder { private: const lib::SegmentedVector& status_; const IDTranslator* translator_; - const std::function* filter_; + const Filter* filter_; const void* skip_buffer_ = nullptr; bool (*skip_)(const void*, float) = nullptr; }; @@ -914,10 +927,11 @@ class MutableVamanaIndex { // Return a `greedy_search` compatible builder for this index. // This is an internal method, mostly used to help implement the batch iterator. - template - ValidBuilder - internal_search_builder(const std::function* filter = nullptr) const { - return ValidBuilder{status_, &translator_, filter}; + ValidBuilder internal_search_builder() const { return ValidBuilder{status_}; } + + template + FilteredValidBuilder internal_search_builder(const Filter& filter) const { + return FilteredValidBuilder{status_, translator_, filter}; } /// @brief RAII shared lock guarding data_/graph_ against compact()'s shrink @@ -947,28 +961,35 @@ class MutableVamanaIndex { return [&, prefetch_parameters, filter](const auto& query, auto& accessor, auto& distance, auto& buffer) { + static_cast(filter); // Unused in regular search. const Idx seed = entry_point(); if (seed == NO_ENTRY) { buffer.clear(); return; } - auto builder = internal_search_builder(filter); + // Perform the greedy search using the provided resources. + auto run = [&](auto& builder) { + concurrent::greedy_search( + graph_, + data_, + accessor, + query, + distance, + buffer, + vamana::EntryPointInitializer{std::span{&seed, 1}}, + builder, + prefetch_parameters, + cancel + ); + }; if constexpr (Filtered) { + auto builder = internal_search_builder(*filter); builder.skip_if_dropped_by(buffer); + run(builder); + } else { + auto builder = internal_search_builder(); + run(builder); } - // Perform the greedy search using the provided resources. - concurrent::greedy_search( - graph_, - data_, - accessor, - query, - distance, - buffer, - vamana::EntryPointInitializer{std::span{&seed, 1}}, - builder, - prefetch_parameters, - cancel - ); // Take a pass over the search buffer to remove any deleted elements that // might remain. buffer.cleanup(); diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index c14bdddef..d4605f268 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -92,17 +92,34 @@ inline constexpr std::string_view name(SlotMetadata metadata) { } // clang-format on -// Template so the compiler builds a separate regular-search copy with no filter check. -template class ValidBuilder { +class ValidBuilder { public: - ValidBuilder( + ValidBuilder(const std::vector& status) + : status_{status} {} + + template + constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { + bool invalid = getindex(status_, i) == SlotMetadata::Deleted; + // This neighbor should be skipped if the metadata corresponding to the given index + // marks this slot as deleted. + return PredicatedSearchNeighbor(i, distance, !invalid); + } + + private: + const std::vector& status_; +}; + +// Separate template so the regular search compiles without any filter check. +template class FilteredValidBuilder { + public: + FilteredValidBuilder( const std::vector& status, - const IDTranslator* translator = nullptr, - const std::function* filter = nullptr + const IDTranslator& translator, + const Filter& filter ) : status_{status} - , translator_{translator} - , filter_{filter} {} + , translator_{&translator} + , filter_{&filter} {} // Once the window is full, only candidates closer than its worst entry are filtered. template void skip_if_dropped_by(const Buffer& buffer) { @@ -114,18 +131,12 @@ template class ValidBuilder { template constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { - if constexpr (Filtered) { - if (skip_ != nullptr && skip_(skip_buffer_, distance)) { - return PredicatedSearchNeighbor(i, distance, false); - } + if (skip_ != nullptr && skip_(skip_buffer_, distance)) { + return PredicatedSearchNeighbor(i, distance, false); } bool invalid = getindex(status_, i) == SlotMetadata::Deleted; - // This neighbor should be skipped if the metadata corresponding to the given index - // marks this slot as deleted. - if constexpr (Filtered) { - if (!invalid) { - invalid = !(*filter_)(translator_->get_external(i)); - } + if (!invalid) { + invalid = !(*filter_)(translator_->get_external(i)); } return PredicatedSearchNeighbor(i, distance, !invalid); } @@ -133,7 +144,7 @@ template class ValidBuilder { private: const std::vector& status_; const IDTranslator* translator_; - const std::function* filter_; + const Filter* filter_; const void* skip_buffer_ = nullptr; bool (*skip_)(const void*, float) = nullptr; }; @@ -709,10 +720,11 @@ class MutableVamanaIndex { // Return a `greedy_search` compatible builder for this index. // This is an internal method, mostly used to help implement the batch iterator. - template - ValidBuilder - internal_search_builder(const std::function* filter = nullptr) const { - return ValidBuilder{status_, &translator_, filter}; + ValidBuilder internal_search_builder() const { return ValidBuilder{status_}; } + + template + FilteredValidBuilder internal_search_builder(const Filter& filter) const { + return FilteredValidBuilder{status_, translator_, filter}; } template @@ -724,23 +736,30 @@ class MutableVamanaIndex { return [&, prefetch_parameters, filter](const auto& query, auto& accessor, auto& distance, auto& buffer) { - auto builder = internal_search_builder(filter); + static_cast(filter); // Unused in regular search. + // Perform the greedy search using the provided resources. + auto run = [&](auto& builder) { + greedy_search( + graph_, + data_, + accessor, + query, + distance, + buffer, + vamana::EntryPointInitializer{lib::as_const_span(entry_point_)}, + builder, + prefetch_parameters, + cancel + ); + }; if constexpr (Filtered) { + auto builder = internal_search_builder(*filter); builder.skip_if_dropped_by(buffer); + run(builder); + } else { + auto builder = internal_search_builder(); + run(builder); } - // Perform the greedy search using the provided resources. - greedy_search( - graph_, - data_, - accessor, - query, - distance, - buffer, - vamana::EntryPointInitializer{lib::as_const_span(entry_point_)}, - builder, - prefetch_parameters, - cancel - ); // Take a pass over the search buffer to remove any deleted elements that // might remain. buffer.cleanup(); diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index a745a7401..b7c3983a5 100644 --- a/include/svs/index/vamana/extensions.h +++ b/include/svs/index/vamana/extensions.h @@ -607,18 +607,17 @@ void svs_invoke( ); // Copy back results. - for (size_t j = 0; j < num_neighbors; ++j) { - if constexpr (requires { search.filter; }) { - if (j >= search_buffer.size()) { // Filtered: fewer than k passed. - result.index(i, j) = static_cast(-1); - result.distance(i, j) = distance::comparator(distance)(0.0f, 1.0f) - ? std::numeric_limits::infinity() - : -std::numeric_limits::infinity(); - continue; - } - } + auto num_results = std::min(num_neighbors, search_buffer.size()); + for (size_t j = 0; j < num_results; ++j) { result.set(search_buffer[j], i, j); } + // Fewer than k results (e.g. a selective filter): pad with invalid ids. + for (size_t j = num_results; j < num_neighbors; ++j) { + result.index(i, j) = static_cast(-1); + result.distance(i, j) = distance::comparator(distance)(0.0f, 1.0f) + ? std::numeric_limits::infinity() + : -std::numeric_limits::infinity(); + } } } diff --git a/include/svs/index/vamana/index.h b/include/svs/index/vamana/index.h index 4d4a47f09..d5c87d9a6 100644 --- a/include/svs/index/vamana/index.h +++ b/include/svs/index/vamana/index.h @@ -24,6 +24,7 @@ #include "svs/core/query_result.h" #include "svs/core/recall.h" #include "svs/index/vamana/calibrate.h" +#include "svs/index/vamana/dynamic_search_buffer.h" #include "svs/index/vamana/extensions.h" #include "svs/index/vamana/greedy_search.h" #include "svs/index/vamana/search_buffer.h" @@ -39,6 +40,7 @@ #include #include #include +#include #include #include #include @@ -50,6 +52,33 @@ namespace svs::index::vamana { template class BatchIterator; +// Marks candidates failing the filter invalid. +template class FilteredNeighborBuilder { + public: + explicit FilteredNeighborBuilder(const Filter& filter) + : filter_{&filter} {} + + // Once the window is full, only candidates closer than its worst entry are filtered. + template void skip_if_dropped_by(const Buffer& buffer) { + skip_buffer_ = &buffer; + skip_ = [](const void* b, float d) { + return static_cast(b)->can_skip(d); + }; + } + + template + constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { + bool valid = !(skip_ != nullptr && skip_(skip_buffer_, distance)) && + (*filter_)(static_cast(i)); + return PredicatedSearchNeighbor(i, distance, valid); + } + + private: + const Filter* filter_; + const void* skip_buffer_ = nullptr; + bool (*skip_)(const void*, float) = nullptr; +}; + struct VamanaIndexParameters { // Members public: @@ -485,25 +514,41 @@ class VamanaIndex { // This is an internal method, mostly used to help implement the batch iterator. static NeighborBuilder internal_search_builder() { return NeighborBuilder(); } + template auto greedy_search_closure( GreedySearchPrefetchParameters prefetch_parameters, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const std::function* filter = nullptr ) const { - return [&, prefetch_parameters]( - const auto& query, auto& accessor, auto& distance, auto& buffer - ) { - greedy_search( - graph_, - data_, - accessor, - query, - distance, - buffer, - vamana::EntryPointInitializer{lib::as_const_span(entry_point_)}, - internal_search_builder(), + return [&, prefetch_parameters, - cancel - ); + filter](const auto& query, auto& accessor, auto& distance, auto& buffer) { + static_cast(filter); // Unused in regular search. + auto run = [&](auto& builder) { + greedy_search( + graph_, + data_, + accessor, + query, + distance, + buffer, + vamana::EntryPointInitializer{lib::as_const_span(entry_point_)}, + builder, + prefetch_parameters, + cancel + ); + }; + if constexpr (Filtered) { + auto builder = + FilteredNeighborBuilder>{*filter}; + builder.skip_if_dropped_by(buffer); + run(builder); + // Remove the invalid entries that remain in the buffer. + buffer.cleanup(); + } else { + auto builder = internal_search_builder(); + run(builder); + } }; } @@ -578,44 +623,72 @@ class VamanaIndex { QueryResultView result, const Queries& queries, const search_parameters_type& search_parameters, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const std::function* filter = nullptr ) { threads::parallel_for( threadpool_, threads::StaticPartition{queries.size()}, [&](const auto is, uint64_t SVS_UNUSED(tid)) { - // The number of neighbors to store in the result. - size_t num_neighbors = result.n_neighbors(); - - // Allocate scratchspace according to the provided search parameters. - auto search_buffer = search_buffer_type{ - // Increase the search window size if the defaults are not suitable for - // the requested number of neighbors. - search_parameters.buffer_config_.get_total_capacity() < num_neighbors - ? SearchBufferConfig{num_neighbors} - : search_parameters.buffer_config_, - distance::comparator(distance_), - search_parameters.search_buffer_visited_set_}; - - auto prefetch_parameters = GreedySearchPrefetchParameters{ - search_parameters.prefetch_lookahead_, - search_parameters.prefetch_step_}; - - // Pre-allocate scratch space needed by the dataset implementation. - auto scratch = extensions::per_thread_batch_search_setup(data_, distance_); - - // Perform a search over the batch of queries. - extensions::per_thread_batch_search( - data_, - search_buffer, - scratch, - queries, - result, - threads::UnitRange{is}, - greedy_search_closure(prefetch_parameters, cancel), - *this, - cancel - ); + auto body = [&](std::bool_constant) { + // Filtered search needs a buffer that can hold invalid entries. + using buffer_type = std::conditional_t< + Filtered, + MutableBuffer>, + search_buffer_type>; + + // The number of neighbors to store in the result. + size_t num_neighbors = result.n_neighbors(); + + // Allocate scratchspace according to the provided search parameters. + auto search_buffer = buffer_type{ + // Increase the search window size if the defaults are not + // suitable for the requested number of neighbors. + search_parameters.buffer_config_.get_total_capacity() < + num_neighbors + ? SearchBufferConfig{num_neighbors} + : search_parameters.buffer_config_, + distance::comparator(distance_), + search_parameters.search_buffer_visited_set_}; + + auto prefetch_parameters = GreedySearchPrefetchParameters{ + search_parameters.prefetch_lookahead_, + search_parameters.prefetch_step_}; + + // Pre-allocate scratch space needed by the dataset implementation. + auto scratch = + extensions::per_thread_batch_search_setup(data_, distance_); + + auto run = [&](const auto& search) { + // Perform a search over the batch of queries. + extensions::per_thread_batch_search( + data_, + search_buffer, + scratch, + queries, + result, + threads::UnitRange{is}, + search, + *this, + cancel + ); + }; + auto search = greedy_search_closure( + prefetch_parameters, cancel, filter + ); + if constexpr (Filtered) { + run(extensions::FilteredSearch{search, filter}); + } else { + run(search); + } + }; + // Keep the filtered body out of line so regular search is unaffected. + if (filter != nullptr) { + [&]() __attribute__((noinline)) { body(std::true_type{}); } + (); + } else { + body(std::false_type{}); + } } ); } diff --git a/include/svs/orchestrators/dynamic_vamana.h b/include/svs/orchestrators/dynamic_vamana.h index 6ace9b035..339974899 100644 --- a/include/svs/orchestrators/dynamic_vamana.h +++ b/include/svs/orchestrators/dynamic_vamana.h @@ -56,14 +56,6 @@ class DynamicVamanaInterface : public VamanaInterface { // Check if the index has been consolidated - no `Deleted` entries remain. virtual bool is_consolidated() const = 0; - - // Filtered search; false if the data type does not support it. Keep last (ABI). - virtual bool filtered_search( - svs::QueryResultView results, - AnonymousArray<2> queries, - const index::vamana::VamanaSearchParameters& search_parameters, - const std::function& filter - ) = 0; }; template @@ -117,31 +109,6 @@ class DynamicVamanaImpl : public VamanaImpl results, - AnonymousArray<2> queries, - const index::vamana::VamanaSearchParameters& search_parameters, - const std::function& filter - ) override { - lib::match( - QueryTypes{}, - queries.type(), - [&](lib::Type SVS_UNUSED(type)) { - impl().search( - results, - data::ConstSimpleDataView(queries), - search_parameters, - lib::Returns(lib::Const()), - &filter - ); - }, - [&](svs::DataType data_type) { - throw ANNEXCEPTION("Unsupported query datatype! Got: {}.", data_type); - } - ); - return true; - } }; // Forward Declaractions. diff --git a/include/svs/orchestrators/vamana.h b/include/svs/orchestrators/vamana.h index 5787e8a7a..5bd633a50 100644 --- a/include/svs/orchestrators/vamana.h +++ b/include/svs/orchestrators/vamana.h @@ -35,6 +35,7 @@ // stdlib #include +#include #include #include #include @@ -108,6 +109,14 @@ class VamanaInterface { // through the wrong slot with no link-time diagnostic. virtual svs::index::vamana::MemoryBreakdown get_memory_breakdown() const = 0; virtual svs::index::vamana::VamanaIndexParameters parameters() const = 0; + + // Filtered search; keep last (ABI). + virtual bool filtered_search( + svs::QueryResultView results, + AnonymousArray<2> queries, + const index::vamana::VamanaSearchParameters& search_parameters, + const std::function& filter + ) = 0; }; template @@ -283,6 +292,31 @@ class VamanaImpl : public manager::ManagerImpl { svs::index::vamana::VamanaIndexParameters parameters() const override { return impl().parameters(); } + + bool filtered_search( + svs::QueryResultView results, + AnonymousArray<2> queries, + const index::vamana::VamanaSearchParameters& search_parameters, + const std::function& filter + ) override { + lib::match( + QueryTypes{}, + queries.type(), + [&](lib::Type SVS_UNUSED(type)) { + impl().search( + results, + data::ConstSimpleDataView(queries), + search_parameters, + lib::Returns(lib::Const()), + &filter + ); + }, + [&](svs::DataType data_type) { + throw ANNEXCEPTION("Unsupported query datatype! Got: {}.", data_type); + } + ); + return true; + } }; ///// Forward declarations @@ -776,6 +810,20 @@ class Vamana : public manager::IndexManager { return impl_->parameters(); } + /// @brief Filtered search: only ids for which ``filter(id)`` is true are returned. + /// Rows with fewer passing entries than requested are padded with id ``size_t(-1)``. + template + bool filtered_search( + QueryResultView results, + data::ConstSimpleDataView queries, + const VamanaSearchParameters& search_parameters, + const std::function& filter + ) { + return impl_->filtered_search( + results, AnonymousArray<2>(queries), search_parameters, filter + ); + } + private: template < manager::QueryTypeDefinition QueryTypes, From 38cf98973fd11d6930d1d60ad734fa3d94150fb3 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Mon, 9 Nov 2026 14:35:21 -0800 Subject: [PATCH 07/16] Pass the filter to the search top-up explicitly Drop the FilteredSearch closure wrapper: single_search and per_thread_batch_search take the filter as a trailing argument and hand it to the buffer top-up. A filtered concurrent search re-checks the filter on the external ids it returns, and the filter contract is documented. --- include/svs/concurrent/dynamic_index.h | 40 +++++++++++++-------- include/svs/index/vamana/dynamic_index.h | 9 ++--- include/svs/index/vamana/extensions.h | 42 +++++++++++----------- include/svs/index/vamana/index.h | 9 ++--- include/svs/orchestrators/dynamic_vamana.h | 1 + include/svs/orchestrators/vamana.h | 1 + 6 files changed, 55 insertions(+), 47 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index ddba11c3c..1eca7ec48 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -1017,7 +1017,8 @@ class MutableVamanaIndex { ); } - // `filter` is called from every search thread without locks; it must be thread-safe. + // `filter` is called from every search thread without locks; it must be thread-safe + // and must not call into this index. template void search( QueryResultView results, @@ -1060,20 +1061,14 @@ class MutableVamanaIndex { threads::UnitRange{is}, search, *this, - cancel + cancel, + filter ); }; auto search = greedy_search_closure( prefetch_parameters, cancel, filter ); - if constexpr (Filtered) { - // Held once for this thread's queries, not per lookup. - auto translation_lock = lock_for_translation(); - run(extensions::FilteredSearch{search, filter} - ); - } else { - run(search); - } + run(search); }; if (filter != nullptr) { [&]() __attribute__((noinline)) { body(std::true_type{}); } @@ -1093,6 +1088,24 @@ class MutableVamanaIndex { // After the search procedure, the indices in `results` are internal. // Perform one more pass to convert these to external ids. translate_to_external(results.indices()); + + if (filter != nullptr) { + // A concurrent remap may have changed the answer: only return ids that pass + // now. + const float worst = distance::comparator(distance_)(0.0f, 1.0f) + ? std::numeric_limits::infinity() + : -std::numeric_limits::infinity(); + for (size_t i = 0; i < results.n_queries(); ++i) { + for (size_t j = 0; j < results.n_neighbors(); ++j) { + auto id = results.index(i, j); + if (id != static_cast(-1) && + (id == no_external_id || !(*filter)(id))) { + results.index(i, j) = static_cast(-1); + results.distance(i, j) = worst; + } + } + } + } } /// @@ -2216,7 +2229,8 @@ SVS_FORCE_INLINE void svs_invoke( const Query& query, const Search& search, const MutableVamanaIndex& index, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const std::function* filter = nullptr ) { using index_type = MutableVamanaIndex; vamana::extensions::single_search( @@ -2233,10 +2247,6 @@ SVS_FORCE_INLINE void svs_invoke( if (cancel()) { return; } - const std::function* filter = nullptr; - if constexpr (requires { search.filter; }) { - filter = search.filter; - } index.supplement_search_buffer(search_buffer, query, filter); } diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index d4605f268..ff60c3a08 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -821,17 +821,14 @@ class MutableVamanaIndex { threads::UnitRange{is}, search, *this, - cancel + cancel, + filter ); }; auto search = greedy_search_closure( prefetch_parameters, cancel, filter ); - if constexpr (Filtered) { - run(extensions::FilteredSearch{search, filter}); - } else { - run(search); - } + run(search); }; if (filter != nullptr) { [&]() __attribute__((noinline)) { body(std::true_type{}); } diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index b7c3983a5..7c9545117 100644 --- a/include/svs/index/vamana/extensions.h +++ b/include/svs/index/vamana/extensions.h @@ -395,6 +395,7 @@ struct VamanaSingleSearchType { /// ``svs::index::vamana::extensions::single_search_setup``(). /// @param query The query used for this search. /// @param search A search functor. See the extended description. + /// @param filter Optional filter of a filtered search, used to top up the buffer. /// /// API of the ``search`` argument. /// This argument is invocable as follows: @@ -422,9 +423,12 @@ struct VamanaSingleSearchType { const Query& query, const Search& search, const Index& index, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const std::function* filter = nullptr ) const { - svs::svs_invoke(*this, data, search_buffer, scratch, query, search, index, cancel); + svs::svs_invoke( + *this, data, search_buffer, scratch, query, search, index, cancel, filter + ); } }; @@ -458,15 +462,6 @@ void check_and_supplement_search_buffer( } } -/// A search closure that also carries the filter of a filtered search. -template struct FilteredSearch { - Search search; - const std::function* filter; - template void operator()(Args&&... args) const { - search(std::forward(args)...); - } -}; - /// Customization point object for processing single queries. inline constexpr VamanaSingleSearchType single_search{}; @@ -488,7 +483,8 @@ SVS_FORCE_INLINE void svs_invoke( const Query& query, const Search& search, const Index& index, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const std::function* filter = nullptr ) { // Check if request to cancel the search if (cancel()) { @@ -499,10 +495,6 @@ SVS_FORCE_INLINE void svs_invoke( search(query, accessor, distance, search_buffer); if constexpr (Index::needs_id_translation) { - const std::function* filter = nullptr; - if constexpr (requires { search.filter; }) { - filter = search.filter; - } check_and_supplement_search_buffer(index, search_buffer, query, filter); } } @@ -553,7 +545,8 @@ struct VamanaPerThreadBatchSearchType { threads::UnitRange thread_indices, const Search& search, const Index& index, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const std::function* filter = nullptr ) const { svs::svs_invoke( *this, @@ -565,7 +558,8 @@ struct VamanaPerThreadBatchSearchType { thread_indices, search, index, - cancel + cancel, + filter ); } }; @@ -592,7 +586,8 @@ void svs_invoke( threads::UnitRange thread_indices, const Search& search, const Index& index, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const std::function* filter = nullptr ) { // Fallback implementation size_t num_neighbors = result.n_neighbors(); @@ -603,7 +598,14 @@ void svs_invoke( } // Perform search - results will be queued in the search buffer. single_search( - dataset, search_buffer, distance, queries.get_datum(i), search, index, cancel + dataset, + search_buffer, + distance, + queries.get_datum(i), + search, + index, + cancel, + filter ); // Copy back results. diff --git a/include/svs/index/vamana/index.h b/include/svs/index/vamana/index.h index d5c87d9a6..92a3d3b94 100644 --- a/include/svs/index/vamana/index.h +++ b/include/svs/index/vamana/index.h @@ -670,17 +670,14 @@ class VamanaIndex { threads::UnitRange{is}, search, *this, - cancel + cancel, + filter ); }; auto search = greedy_search_closure( prefetch_parameters, cancel, filter ); - if constexpr (Filtered) { - run(extensions::FilteredSearch{search, filter}); - } else { - run(search); - } + run(search); }; // Keep the filtered body out of line so regular search is unaffected. if (filter != nullptr) { diff --git a/include/svs/orchestrators/dynamic_vamana.h b/include/svs/orchestrators/dynamic_vamana.h index 339974899..e256c42e2 100644 --- a/include/svs/orchestrators/dynamic_vamana.h +++ b/include/svs/orchestrators/dynamic_vamana.h @@ -612,6 +612,7 @@ class DynamicVamana : public manager::IndexManager { /// @brief Filtered search: only ids for which ``filter(id)`` is true are returned. /// Rows with fewer passing entries than requested are padded with id ``size_t(-1)``. + /// ``filter`` must be thread-safe and must not call into the same index. template bool filtered_search( QueryResultView results, diff --git a/include/svs/orchestrators/vamana.h b/include/svs/orchestrators/vamana.h index 5bd633a50..2637e7f58 100644 --- a/include/svs/orchestrators/vamana.h +++ b/include/svs/orchestrators/vamana.h @@ -812,6 +812,7 @@ class Vamana : public manager::IndexManager { /// @brief Filtered search: only ids for which ``filter(id)`` is true are returned. /// Rows with fewer passing entries than requested are padded with id ``size_t(-1)``. + /// ``filter`` must be thread-safe and must not call into the same index. template bool filtered_search( QueryResultView results, From ad5697a429b87582f377f988e941e20c1f7ae093 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Mon, 9 Nov 2026 15:24:38 -0800 Subject: [PATCH 08/16] Keep FilteredSearch for now --- include/svs/concurrent/dynamic_index.h | 17 +++++++--- include/svs/index/vamana/dynamic_index.h | 9 +++-- include/svs/index/vamana/extensions.h | 42 +++++++++++------------- include/svs/index/vamana/index.h | 9 +++-- 4 files changed, 44 insertions(+), 33 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index 1eca7ec48..44de523de 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -1061,14 +1061,18 @@ class MutableVamanaIndex { threads::UnitRange{is}, search, *this, - cancel, - filter + cancel ); }; auto search = greedy_search_closure( prefetch_parameters, cancel, filter ); - run(search); + if constexpr (Filtered) { + run(extensions::FilteredSearch{search, filter} + ); + } else { + run(search); + } }; if (filter != nullptr) { [&]() __attribute__((noinline)) { body(std::true_type{}); } @@ -2229,8 +2233,7 @@ SVS_FORCE_INLINE void svs_invoke( const Query& query, const Search& search, const MutableVamanaIndex& index, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), - const std::function* filter = nullptr + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) { using index_type = MutableVamanaIndex; vamana::extensions::single_search( @@ -2247,6 +2250,10 @@ SVS_FORCE_INLINE void svs_invoke( if (cancel()) { return; } + const std::function* filter = nullptr; + if constexpr (requires { search.filter; }) { + filter = search.filter; + } index.supplement_search_buffer(search_buffer, query, filter); } diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index ff60c3a08..d4605f268 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -821,14 +821,17 @@ class MutableVamanaIndex { threads::UnitRange{is}, search, *this, - cancel, - filter + cancel ); }; auto search = greedy_search_closure( prefetch_parameters, cancel, filter ); - run(search); + if constexpr (Filtered) { + run(extensions::FilteredSearch{search, filter}); + } else { + run(search); + } }; if (filter != nullptr) { [&]() __attribute__((noinline)) { body(std::true_type{}); } diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index 7c9545117..b7c3983a5 100644 --- a/include/svs/index/vamana/extensions.h +++ b/include/svs/index/vamana/extensions.h @@ -395,7 +395,6 @@ struct VamanaSingleSearchType { /// ``svs::index::vamana::extensions::single_search_setup``(). /// @param query The query used for this search. /// @param search A search functor. See the extended description. - /// @param filter Optional filter of a filtered search, used to top up the buffer. /// /// API of the ``search`` argument. /// This argument is invocable as follows: @@ -423,12 +422,9 @@ struct VamanaSingleSearchType { const Query& query, const Search& search, const Index& index, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), - const std::function* filter = nullptr + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) const { - svs::svs_invoke( - *this, data, search_buffer, scratch, query, search, index, cancel, filter - ); + svs::svs_invoke(*this, data, search_buffer, scratch, query, search, index, cancel); } }; @@ -462,6 +458,15 @@ void check_and_supplement_search_buffer( } } +/// A search closure that also carries the filter of a filtered search. +template struct FilteredSearch { + Search search; + const std::function* filter; + template void operator()(Args&&... args) const { + search(std::forward(args)...); + } +}; + /// Customization point object for processing single queries. inline constexpr VamanaSingleSearchType single_search{}; @@ -483,8 +488,7 @@ SVS_FORCE_INLINE void svs_invoke( const Query& query, const Search& search, const Index& index, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), - const std::function* filter = nullptr + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) { // Check if request to cancel the search if (cancel()) { @@ -495,6 +499,10 @@ SVS_FORCE_INLINE void svs_invoke( search(query, accessor, distance, search_buffer); if constexpr (Index::needs_id_translation) { + const std::function* filter = nullptr; + if constexpr (requires { search.filter; }) { + filter = search.filter; + } check_and_supplement_search_buffer(index, search_buffer, query, filter); } } @@ -545,8 +553,7 @@ struct VamanaPerThreadBatchSearchType { threads::UnitRange thread_indices, const Search& search, const Index& index, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), - const std::function* filter = nullptr + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) const { svs::svs_invoke( *this, @@ -558,8 +565,7 @@ struct VamanaPerThreadBatchSearchType { thread_indices, search, index, - cancel, - filter + cancel ); } }; @@ -586,8 +592,7 @@ void svs_invoke( threads::UnitRange thread_indices, const Search& search, const Index& index, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), - const std::function* filter = nullptr + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) { // Fallback implementation size_t num_neighbors = result.n_neighbors(); @@ -598,14 +603,7 @@ void svs_invoke( } // Perform search - results will be queued in the search buffer. single_search( - dataset, - search_buffer, - distance, - queries.get_datum(i), - search, - index, - cancel, - filter + dataset, search_buffer, distance, queries.get_datum(i), search, index, cancel ); // Copy back results. diff --git a/include/svs/index/vamana/index.h b/include/svs/index/vamana/index.h index 92a3d3b94..d5c87d9a6 100644 --- a/include/svs/index/vamana/index.h +++ b/include/svs/index/vamana/index.h @@ -670,14 +670,17 @@ class VamanaIndex { threads::UnitRange{is}, search, *this, - cancel, - filter + cancel ); }; auto search = greedy_search_closure( prefetch_parameters, cancel, filter ); - run(search); + if constexpr (Filtered) { + run(extensions::FilteredSearch{search, filter}); + } else { + run(search); + } }; // Keep the filtered body out of line so regular search is unaffected. if (filter != nullptr) { From 4abf93c33bc892c3dea8147d7b23d52cbc909291 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Mon, 9 Nov 2026 16:15:11 -0800 Subject: [PATCH 09/16] Do not apply the filter in the search top-up yet --- include/svs/concurrent/dynamic_index.h | 15 +++------------ include/svs/index/vamana/dynamic_index.h | 2 +- include/svs/index/vamana/extensions.h | 24 ++---------------------- include/svs/index/vamana/index.h | 2 +- 4 files changed, 7 insertions(+), 36 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index 44de523de..a50efca3d 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -1068,8 +1068,7 @@ class MutableVamanaIndex { prefetch_parameters, cancel, filter ); if constexpr (Filtered) { - run(extensions::FilteredSearch{search, filter} - ); + run(search); } else { run(search); } @@ -2135,11 +2134,7 @@ class MutableVamanaIndex { /// Called from the ``extensions::single_search`` override below. /// template - void supplement_search_buffer( - SearchBuffer& search_buffer, - const Query& query, - const std::function* filter = nullptr - ) const { + void supplement_search_buffer(SearchBuffer& search_buffer, const Query& query) const { if (search_buffer.valid() >= search_buffer.target_window() || search_buffer.valid() >= size()) { return; @@ -2250,11 +2245,7 @@ SVS_FORCE_INLINE void svs_invoke( if (cancel()) { return; } - const std::function* filter = nullptr; - if constexpr (requires { search.filter; }) { - filter = search.filter; - } - index.supplement_search_buffer(search_buffer, query, filter); + index.supplement_search_buffer(search_buffer, query); } ///// Deduction Guides. diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index d4605f268..298d04be6 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -828,7 +828,7 @@ class MutableVamanaIndex { prefetch_parameters, cancel, filter ); if constexpr (Filtered) { - run(extensions::FilteredSearch{search, filter}); + run(search); } else { run(search); } diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index b7c3983a5..b13e43f21 100644 --- a/include/svs/index/vamana/extensions.h +++ b/include/svs/index/vamana/extensions.h @@ -27,7 +27,6 @@ #include "svs/lib/preprocessor.h" #include "svs/lib/threads.h" -#include #include namespace svs::index::vamana::extensions { @@ -435,18 +434,12 @@ struct VamanaSingleSearchType { /// with additional results. template void check_and_supplement_search_buffer( - const Index& index, - SearchBuffer& search_buffer, - const Query& query, - const std::function* filter = nullptr + const Index& index, SearchBuffer& search_buffer, const Query& query ) { if (search_buffer.valid() < search_buffer.target_window() && search_buffer.valid() < index.size()) { search_buffer.sort(); for (auto external_id : index.external_ids()) { - if (filter != nullptr && !(*filter)(external_id)) { - continue; - } auto internal_id = index.translate_external_id(external_id); auto dist = index.get_distance(external_id, query); auto builder = index.internal_search_builder(); @@ -458,15 +451,6 @@ void check_and_supplement_search_buffer( } } -/// A search closure that also carries the filter of a filtered search. -template struct FilteredSearch { - Search search; - const std::function* filter; - template void operator()(Args&&... args) const { - search(std::forward(args)...); - } -}; - /// Customization point object for processing single queries. inline constexpr VamanaSingleSearchType single_search{}; @@ -499,11 +483,7 @@ SVS_FORCE_INLINE void svs_invoke( search(query, accessor, distance, search_buffer); if constexpr (Index::needs_id_translation) { - const std::function* filter = nullptr; - if constexpr (requires { search.filter; }) { - filter = search.filter; - } - check_and_supplement_search_buffer(index, search_buffer, query, filter); + check_and_supplement_search_buffer(index, search_buffer, query); } } diff --git a/include/svs/index/vamana/index.h b/include/svs/index/vamana/index.h index d5c87d9a6..390235b52 100644 --- a/include/svs/index/vamana/index.h +++ b/include/svs/index/vamana/index.h @@ -677,7 +677,7 @@ class VamanaIndex { prefetch_parameters, cancel, filter ); if constexpr (Filtered) { - run(extensions::FilteredSearch{search, filter}); + run(search); } else { run(search); } From 90aebdcdfbfc5b0e5023252ae71fc2757c34f79e Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Mon, 9 Nov 2026 16:54:02 -0800 Subject: [PATCH 10/16] Skip candidates a full buffer would drop in greedy_search --- include/svs/concurrent/dynamic_index.h | 14 -------------- include/svs/concurrent/greedy_search.h | 4 +++- include/svs/index/vamana/dynamic_index.h | 14 -------------- include/svs/index/vamana/greedy_search.h | 4 +++- include/svs/index/vamana/index.h | 14 +------------- 5 files changed, 7 insertions(+), 43 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index a50efca3d..69eb91241 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -183,19 +183,8 @@ template class FilteredValidBuilder { , translator_{&translator} , filter_{&filter} {} - // Once the window is full, only candidates closer than its worst entry are filtered. - template void skip_if_dropped_by(const Buffer& buffer) { - skip_buffer_ = &buffer; - skip_ = [](const void* b, float d) { - return static_cast(b)->can_skip(d); - }; - } - template constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { - if (skip_ != nullptr && skip_(skip_buffer_, distance)) { - return PredicatedSearchNeighbor(i, distance, false); - } bool invalid = std::atomic_ref(const_cast(getindex(status_, i))) .load(std::memory_order_acquire) != SlotMetadata::Valid; @@ -211,8 +200,6 @@ template class FilteredValidBuilder { const lib::SegmentedVector& status_; const IDTranslator* translator_; const Filter* filter_; - const void* skip_buffer_ = nullptr; - bool (*skip_)(const void*, float) = nullptr; }; template @@ -984,7 +971,6 @@ class MutableVamanaIndex { }; if constexpr (Filtered) { auto builder = internal_search_builder(*filter); - builder.skip_if_dropped_by(buffer); run(builder); } else { auto builder = internal_search_builder(); diff --git a/include/svs/concurrent/greedy_search.h b/include/svs/concurrent/greedy_search.h index fe8d7fd59..0b0864f9e 100644 --- a/include/svs/concurrent/greedy_search.h +++ b/include/svs/concurrent/greedy_search.h @@ -146,7 +146,9 @@ void greedy_search( // Compute distance and update search buffer. auto dist = distance::compute(distance_function, query, accessor(dataset, id)); - search_buffer.insert(builder(id, dist)); + if (!search_buffer.can_skip(dist)) { + search_buffer.insert(builder(id, dist)); + } } // Validate that no concurrent write occurred during the read. diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index 298d04be6..e83aeb3cb 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -121,19 +121,8 @@ template class FilteredValidBuilder { , translator_{&translator} , filter_{&filter} {} - // Once the window is full, only candidates closer than its worst entry are filtered. - template void skip_if_dropped_by(const Buffer& buffer) { - skip_buffer_ = &buffer; - skip_ = [](const void* b, float d) { - return static_cast(b)->can_skip(d); - }; - } - template constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { - if (skip_ != nullptr && skip_(skip_buffer_, distance)) { - return PredicatedSearchNeighbor(i, distance, false); - } bool invalid = getindex(status_, i) == SlotMetadata::Deleted; if (!invalid) { invalid = !(*filter_)(translator_->get_external(i)); @@ -145,8 +134,6 @@ template class FilteredValidBuilder { const std::vector& status_; const IDTranslator* translator_; const Filter* filter_; - const void* skip_buffer_ = nullptr; - bool (*skip_)(const void*, float) = nullptr; }; namespace detail { @@ -754,7 +741,6 @@ class MutableVamanaIndex { }; if constexpr (Filtered) { auto builder = internal_search_builder(*filter); - builder.skip_if_dropped_by(buffer); run(builder); } else { auto builder = internal_search_builder(); diff --git a/include/svs/index/vamana/greedy_search.h b/include/svs/index/vamana/greedy_search.h index f12c0129f..30225578f 100644 --- a/include/svs/index/vamana/greedy_search.h +++ b/include/svs/index/vamana/greedy_search.h @@ -197,7 +197,9 @@ void greedy_search( // Compute distance and update search buffer. auto dist = distance::compute(distance_function, query, accessor(dataset, id)); - search_buffer.insert(builder(id, dist)); + if (!search_buffer.can_skip(dist)) { + search_buffer.insert(builder(id, dist)); + } } } } diff --git a/include/svs/index/vamana/index.h b/include/svs/index/vamana/index.h index 390235b52..da4721459 100644 --- a/include/svs/index/vamana/index.h +++ b/include/svs/index/vamana/index.h @@ -58,25 +58,14 @@ template class FilteredNeighborBuilder { explicit FilteredNeighborBuilder(const Filter& filter) : filter_{&filter} {} - // Once the window is full, only candidates closer than its worst entry are filtered. - template void skip_if_dropped_by(const Buffer& buffer) { - skip_buffer_ = &buffer; - skip_ = [](const void* b, float d) { - return static_cast(b)->can_skip(d); - }; - } - template constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { - bool valid = !(skip_ != nullptr && skip_(skip_buffer_, distance)) && - (*filter_)(static_cast(i)); + bool valid = (*filter_)(static_cast(i)); return PredicatedSearchNeighbor(i, distance, valid); } private: const Filter* filter_; - const void* skip_buffer_ = nullptr; - bool (*skip_)(const void*, float) = nullptr; }; struct VamanaIndexParameters { @@ -541,7 +530,6 @@ class VamanaIndex { if constexpr (Filtered) { auto builder = FilteredNeighborBuilder>{*filter}; - builder.skip_if_dropped_by(buffer); run(builder); // Remove the invalid entries that remain in the buffer. buffer.cleanup(); From d95ce278fd0851c0c0692db237b4a5e4912e91d8 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Mon, 9 Nov 2026 16:54:07 -0800 Subject: [PATCH 11/16] Fail when the filter calls into the concurrent index --- include/svs/concurrent/dynamic_index.h | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index 69eb91241..8f9431f13 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -171,6 +171,20 @@ class ValidBuilder { const lib::SegmentedVector& status_; }; +// Set while the user's filter runs on this thread, so re-entering the index fails fast. +inline thread_local bool in_user_filter = false; + +struct FilterScope { + FilterScope() { in_user_filter = true; } + ~FilterScope() { in_user_filter = false; } +}; + +inline void check_not_in_filter() { + if (in_user_filter) { + throw ANNEXCEPTION("filter must not call into the same index"); + } +} + // Separate template so the regular search compiles without any filter check. template class FilteredValidBuilder { public: @@ -184,13 +198,14 @@ template class FilteredValidBuilder { , filter_{&filter} {} template - constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { + PredicatedSearchNeighbor operator()(I i, float distance) const { bool invalid = std::atomic_ref(const_cast(getindex(status_, i))) .load(std::memory_order_acquire) != SlotMetadata::Valid; if (!invalid) { // Lock-free read; an erased slot has no external id and fails. size_t external = translator_->get_external_or(i, no_external_id); + FilterScope scope; invalid = external == no_external_id || !(*filter_)(external); } return PredicatedSearchNeighbor(i, distance, !invalid); @@ -928,6 +943,7 @@ class MutableVamanaIndex { /// Hold this through internal-to-external ID translation. Acquire the translation /// lock inside this guard, preserving the compact -> translator lock order. [[nodiscard]] std::shared_lock lock_storage_shared() const { + check_not_in_filter(); std::shared_lock gatekeeper_lock{*compact_gatekeeper_}; return std::shared_lock(*compact_mutex_); } @@ -1087,6 +1103,7 @@ class MutableVamanaIndex { for (size_t i = 0; i < results.n_queries(); ++i) { for (size_t j = 0; j < results.n_neighbors(); ++j) { auto id = results.index(i, j); + FilterScope scope; if (id != static_cast(-1) && (id == no_external_id || !(*filter)(id))) { results.index(i, j) = static_cast(-1); @@ -1490,6 +1507,7 @@ class MutableVamanaIndex { /// improve performance but requires more working memory. /// void compact(Idx batch_size = 1'000) { + check_not_in_filter(); std::lock_guard gatekeeper_lock{*compact_gatekeeper_}; std::lock_guard compact_lock{*compact_mutex_}; From cd0936619c68bbf31f661a47bd4bc99c1370268a Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Thu, 12 Nov 2026 12:34:13 -0800 Subject: [PATCH 12/16] Use only the translator in the dynamic filtered builder --- include/svs/index/vamana/dynamic_index.h | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index e83aeb3cb..582a9f18c 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -112,26 +112,19 @@ class ValidBuilder { // Separate template so the regular search compiles without any filter check. template class FilteredValidBuilder { public: - FilteredValidBuilder( - const std::vector& status, - const IDTranslator& translator, - const Filter& filter - ) - : status_{status} - , translator_{&translator} + FilteredValidBuilder(const IDTranslator& translator, const Filter& filter) + : translator_{&translator} , filter_{&filter} {} template constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { - bool invalid = getindex(status_, i) == SlotMetadata::Deleted; - if (!invalid) { - invalid = !(*filter_)(translator_->get_external(i)); - } + // delete_entries clears the translator entry, so a missing id means deleted. + auto id = translator_->get_external_or(i, IDTranslator::invalid_external_id); + bool invalid = id == IDTranslator::invalid_external_id || !(*filter_)(id); return PredicatedSearchNeighbor(i, distance, !invalid); } private: - const std::vector& status_; const IDTranslator* translator_; const Filter* filter_; }; @@ -711,7 +704,7 @@ class MutableVamanaIndex { template FilteredValidBuilder internal_search_builder(const Filter& filter) const { - return FilteredValidBuilder{status_, translator_, filter}; + return FilteredValidBuilder{translator_, filter}; } template @@ -1047,12 +1040,14 @@ class MutableVamanaIndex { return ids.size(); } + private: void delete_entry(size_t i) { SlotMetadata& meta = getindex(status_, i); assert(meta == SlotMetadata::Valid); meta = SlotMetadata::Deleted; } + public: bool is_deleted(size_t i) const { return status_[i] != SlotMetadata::Valid; } Idx entry_point() const { From e565b288dcfda3bb9cd2c935926426864c6bf708 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Thu, 12 Nov 2026 14:06:47 -0800 Subject: [PATCH 13/16] Address review: small fixes Reject the reserved external id, make the filter re-entry guard per index, mark translated ids that vanish as invalid, drop identical filtered/unfiltered branches, share the query-type dispatch for filtered_search (now void), and fix the metadata estimate comment. --- include/svs/concurrent/dynamic_index.h | 80 +++++++++++----------- include/svs/core/translation.h | 14 ++++ include/svs/index/vamana/dynamic_index.h | 37 ++++------ include/svs/index/vamana/index.h | 31 ++++----- include/svs/orchestrators/dynamic_vamana.h | 4 +- include/svs/orchestrators/manager.h | 49 ++++++++----- include/svs/orchestrators/vamana.h | 30 +++----- 7 files changed, 122 insertions(+), 123 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index 8f9431f13..317a1b754 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -171,16 +171,20 @@ class ValidBuilder { const lib::SegmentedVector& status_; }; -// Set while the user's filter runs on this thread, so re-entering the index fails fast. -inline thread_local bool in_user_filter = false; +// The index whose user filter runs on this thread, so re-entering it fails fast. +inline thread_local const void* filtering_index = nullptr; struct FilterScope { - FilterScope() { in_user_filter = true; } - ~FilterScope() { in_user_filter = false; } + explicit FilterScope(const void* index) + : previous_{filtering_index} { + filtering_index = index; + } + ~FilterScope() { filtering_index = previous_; } + const void* previous_; }; -inline void check_not_in_filter() { - if (in_user_filter) { +inline void check_not_in_filter(const void* index) { + if (filtering_index == index) { throw ANNEXCEPTION("filter must not call into the same index"); } } @@ -191,11 +195,13 @@ template class FilteredValidBuilder { FilteredValidBuilder( const lib::SegmentedVector& status, const IDTranslator& translator, - const Filter& filter + const Filter& filter, + const void* owner ) : status_{status} , translator_{&translator} - , filter_{&filter} {} + , filter_{&filter} + , owner_{owner} {} template PredicatedSearchNeighbor operator()(I i, float distance) const { @@ -205,7 +211,7 @@ template class FilteredValidBuilder { if (!invalid) { // Lock-free read; an erased slot has no external id and fails. size_t external = translator_->get_external_or(i, no_external_id); - FilterScope scope; + FilterScope scope{owner_}; invalid = external == no_external_id || !(*filter_)(external); } return PredicatedSearchNeighbor(i, distance, !invalid); @@ -215,6 +221,7 @@ template class FilteredValidBuilder { const lib::SegmentedVector& status_; const IDTranslator* translator_; const Filter* filter_; + const void* owner_; }; template @@ -652,11 +659,9 @@ class MutableVamanaIndex { size_t metadata_bytes = status_.capacity() * sizeof(SlotMetadata); metadata_bytes += entry_point_.capacity() * sizeof(typename entry_point_type::value_type); - // The IDTranslator holds two tsl::robin_map instances (external->internal and - // internal->external), neither of which exposes its allocated byte count. We - // approximate the storage as the id pair held in each of the two directions. This - // ignores the maps' load-factor slack and control bytes, so it is an estimate of - // the hash-map overhead that is accurate to within a few percent. + // Estimate: the id pair per entry, counted twice (external->internal hash map and + // internal->external vector); ignores hash-map load-factor slack and vector spare + // capacity. metadata_bytes += 2 * translator_.size() * (sizeof(IDTranslator::external_id_type) + sizeof(IDTranslator::internal_id_type)); @@ -933,7 +938,7 @@ class MutableVamanaIndex { template FilteredValidBuilder internal_search_builder(const Filter& filter) const { - return FilteredValidBuilder{status_, translator_, filter}; + return FilteredValidBuilder{status_, translator_, filter, this}; } /// @brief RAII shared lock guarding data_/graph_ against compact()'s shrink @@ -943,7 +948,7 @@ class MutableVamanaIndex { /// Hold this through internal-to-external ID translation. Acquire the translation /// lock inside this guard, preserving the compact -> translator lock order. [[nodiscard]] std::shared_lock lock_storage_shared() const { - check_not_in_filter(); + check_not_in_filter(this); std::shared_lock gatekeeper_lock{*compact_gatekeeper_}; return std::shared_lock(*compact_mutex_); } @@ -1053,27 +1058,20 @@ class MutableVamanaIndex { auto scratch = extensions::per_thread_batch_search_setup(data_, distance_); - auto run = [&](const auto& search) { - extensions::per_thread_batch_search( - data_, - buffer, - scratch, - queries, - results, - threads::UnitRange{is}, - search, - *this, - cancel - ); - }; auto search = greedy_search_closure( prefetch_parameters, cancel, filter ); - if constexpr (Filtered) { - run(search); - } else { - run(search); - } + extensions::per_thread_batch_search( + data_, + buffer, + scratch, + queries, + results, + threads::UnitRange{is}, + search, + *this, + cancel + ); }; if (filter != nullptr) { [&]() __attribute__((noinline)) { body(std::true_type{}); } @@ -1103,10 +1101,14 @@ class MutableVamanaIndex { for (size_t i = 0; i < results.n_queries(); ++i) { for (size_t j = 0; j < results.n_neighbors(); ++j) { auto id = results.index(i, j); - FilterScope scope; - if (id != static_cast(-1) && - (id == no_external_id || !(*filter)(id))) { - results.index(i, j) = static_cast(-1); + if (id != static_cast(-1)) { + FilterScope scope{this}; + if (!(*filter)(id)) { + results.index(i, j) = static_cast(-1); + } + } + // Also covers ids a concurrent erase left without a translation. + if (results.index(i, j) == static_cast(-1)) { results.distance(i, j) = worst; } } @@ -1507,7 +1509,7 @@ class MutableVamanaIndex { /// improve performance but requires more working memory. /// void compact(Idx batch_size = 1'000) { - check_not_in_filter(); + check_not_in_filter(this); std::lock_guard gatekeeper_lock{*compact_gatekeeper_}; std::lock_guard compact_lock{*compact_mutex_}; diff --git a/include/svs/core/translation.h b/include/svs/core/translation.h index 88b95311f..5b1a09e9a 100644 --- a/include/svs/core/translation.h +++ b/include/svs/core/translation.h @@ -38,6 +38,7 @@ #include #include #include +#include namespace svs { @@ -124,6 +125,7 @@ class IDTranslator { if (!lib::all_unique(int_begin, int_end)) { throw ANNEXCEPTION("Internal IDs contain repeat elements!"); } + check_external_not_reserved(ext_begin, ext_end); check_external_free(ext_begin, ext_end); check_internal_free(int_begin, int_end); } @@ -183,6 +185,8 @@ class IDTranslator { throw ANNEXCEPTION("Internal IDs contain repeat elements!"); } + check_external_not_reserved(ext_begin, ext_end); + // Validation pass for (auto e = ext_begin; e != ext_end; ++e) { auto found = external_to_internal_.find(*e); @@ -377,6 +381,16 @@ class IDTranslator { /// @param begin Start forward iterator to the external IDs to check. /// @param end End forward iterator to the external IDs to check. /// + template + void check_external_not_reserved(const Begin& begin, const End& end) const { + check( + begin, + end, + [](auto e) { return std::cmp_equal(e, invalid_external_id); }, + "Reserved external" + ); + } + template void check_external_free(const Begin& begin, const End& end) const { check(begin, end, external_to_internal_, "Index already contains external"); diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index 582a9f18c..ac7131b71 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -537,11 +537,9 @@ class MutableVamanaIndex { size_t metadata_bytes = status_.capacity() * sizeof(SlotMetadata); metadata_bytes += entry_point_.capacity() * sizeof(typename entry_point_type::value_type); - // The IDTranslator holds two tsl::robin_map instances (external->internal and - // internal->external), neither of which exposes its allocated byte count. We - // approximate the storage as the id pair held in each of the two directions. This - // ignores the maps' load-factor slack and control bytes, so it is an estimate of - // the hash-map overhead that is accurate to within a few percent. + // Estimate: the id pair per entry, counted twice (external->internal hash map and + // internal->external vector); ignores hash-map load-factor slack and vector spare + // capacity. metadata_bytes += 2 * translator_.size() * (sizeof(IDTranslator::external_id_type) + sizeof(IDTranslator::internal_id_type)); @@ -790,27 +788,20 @@ class MutableVamanaIndex { auto scratch = extensions::per_thread_batch_search_setup(data_, distance_); - auto run = [&](const auto& search) { - extensions::per_thread_batch_search( - data_, - buffer, - scratch, - queries, - results, - threads::UnitRange{is}, - search, - *this, - cancel - ); - }; auto search = greedy_search_closure( prefetch_parameters, cancel, filter ); - if constexpr (Filtered) { - run(search); - } else { - run(search); - } + extensions::per_thread_batch_search( + data_, + buffer, + scratch, + queries, + results, + threads::UnitRange{is}, + search, + *this, + cancel + ); }; if (filter != nullptr) { [&]() __attribute__((noinline)) { body(std::true_type{}); } diff --git a/include/svs/index/vamana/index.h b/include/svs/index/vamana/index.h index da4721459..f3911d2ae 100644 --- a/include/svs/index/vamana/index.h +++ b/include/svs/index/vamana/index.h @@ -647,28 +647,21 @@ class VamanaIndex { auto scratch = extensions::per_thread_batch_search_setup(data_, distance_); - auto run = [&](const auto& search) { - // Perform a search over the batch of queries. - extensions::per_thread_batch_search( - data_, - search_buffer, - scratch, - queries, - result, - threads::UnitRange{is}, - search, - *this, - cancel - ); - }; auto search = greedy_search_closure( prefetch_parameters, cancel, filter ); - if constexpr (Filtered) { - run(search); - } else { - run(search); - } + // Perform a search over the batch of queries. + extensions::per_thread_batch_search( + data_, + search_buffer, + scratch, + queries, + result, + threads::UnitRange{is}, + search, + *this, + cancel + ); }; // Keep the filtered body out of line so regular search is unaffected. if (filter != nullptr) { diff --git a/include/svs/orchestrators/dynamic_vamana.h b/include/svs/orchestrators/dynamic_vamana.h index e256c42e2..5e1f53a0e 100644 --- a/include/svs/orchestrators/dynamic_vamana.h +++ b/include/svs/orchestrators/dynamic_vamana.h @@ -614,13 +614,13 @@ class DynamicVamana : public manager::IndexManager { /// Rows with fewer passing entries than requested are padded with id ``size_t(-1)``. /// ``filter`` must be thread-safe and must not call into the same index. template - bool filtered_search( + void filtered_search( QueryResultView results, data::ConstSimpleDataView queries, const VamanaSearchParameters& search_parameters, const std::function& filter ) { - return impl_->filtered_search( + impl_->filtered_search( results, AnonymousArray<2>(queries), search_parameters, filter ); } diff --git a/include/svs/orchestrators/manager.h b/include/svs/orchestrators/manager.h index b3f4d33d2..3fcbb4ed6 100644 --- a/include/svs/orchestrators/manager.h +++ b/include/svs/orchestrators/manager.h @@ -146,25 +146,11 @@ class ManagerImpl : public ManagerInterface { const search_parameters_type& search_parameters, const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) override { - // See if we have a specialization for this particular query type. - // If so, invoke that specialization, otherwise throw - lib::match( - QueryTypes{}, - data.type(), - [&](lib::Type SVS_UNUSED(type)) { - const auto view = data::ConstSimpleDataView(data); - svs::index::search_batch_into_with( - implementation_, result, view, search_parameters, cancel - ); - }, - [&](svs::DataType data_type) { - throw ANNEXCEPTION( - "Unsupported datatype! Got: {}. Expected one of: {}.", - data_type, - fmt::join(QueryTypes::data_types(), ", ") - ); - } - ); + dispatch_queries(result, data, [&](const auto& view) { + svs::index::search_batch_into_with( + implementation_, result, view, search_parameters, cancel + ); + }); } // Data Interface @@ -191,6 +177,31 @@ class ManagerImpl : public ManagerInterface { Impl& impl() { return implementation_; } const Impl& impl() const { return implementation_; } + // Invoke `f` with the query view of the matching supported type, otherwise throw. + template + void dispatch_queries( + [[maybe_unused]] QueryResultView result, + const AnonymousArray<2>& data, + F&& f + ) const { + lib::match( + QueryTypes{}, + data.type(), + [&](lib::Type SVS_UNUSED(type)) { + const auto view = data::ConstSimpleDataView(data); + assert(result.n_queries() == view.size()); + f(view); + }, + [&](svs::DataType data_type) { + throw ANNEXCEPTION( + "Unsupported datatype! Got: {}. Expected one of: {}.", + data_type, + fmt::join(QueryTypes::data_types(), ", ") + ); + } + ); + } + private: friend class IndexManager; Impl implementation_; diff --git a/include/svs/orchestrators/vamana.h b/include/svs/orchestrators/vamana.h index 2637e7f58..e43ba617c 100644 --- a/include/svs/orchestrators/vamana.h +++ b/include/svs/orchestrators/vamana.h @@ -111,7 +111,7 @@ class VamanaInterface { virtual svs::index::vamana::VamanaIndexParameters parameters() const = 0; // Filtered search; keep last (ABI). - virtual bool filtered_search( + virtual void filtered_search( svs::QueryResultView results, AnonymousArray<2> queries, const index::vamana::VamanaSearchParameters& search_parameters, @@ -293,29 +293,17 @@ class VamanaImpl : public manager::ManagerImpl { return impl().parameters(); } - bool filtered_search( + void filtered_search( svs::QueryResultView results, AnonymousArray<2> queries, const index::vamana::VamanaSearchParameters& search_parameters, const std::function& filter ) override { - lib::match( - QueryTypes{}, - queries.type(), - [&](lib::Type SVS_UNUSED(type)) { - impl().search( - results, - data::ConstSimpleDataView(queries), - search_parameters, - lib::Returns(lib::Const()), - &filter - ); - }, - [&](svs::DataType data_type) { - throw ANNEXCEPTION("Unsupported query datatype! Got: {}.", data_type); - } - ); - return true; + this->dispatch_queries(results, queries, [&](const auto& view) { + impl().search( + results, view, search_parameters, lib::Returns(lib::Const()), &filter + ); + }); } }; @@ -814,13 +802,13 @@ class Vamana : public manager::IndexManager { /// Rows with fewer passing entries than requested are padded with id ``size_t(-1)``. /// ``filter`` must be thread-safe and must not call into the same index. template - bool filtered_search( + void filtered_search( QueryResultView results, data::ConstSimpleDataView queries, const VamanaSearchParameters& search_parameters, const std::function& filter ) { - return impl_->filtered_search( + impl_->filtered_search( results, AnonymousArray<2>(queries), search_parameters, filter ); } From 0660e60f40941c428bc29da49c8d69615faec493 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Thu, 12 Nov 2026 15:52:53 -0800 Subject: [PATCH 14/16] Shrink the filtered search diff --- include/svs/concepts/distance.h | 7 ++ include/svs/concurrent/dynamic_index.h | 131 ++++++++++---------- include/svs/core/translation.h | 22 +++- include/svs/index/vamana/dynamic_index.h | 119 +++++++++--------- include/svs/index/vamana/extensions.h | 6 +- include/svs/index/vamana/index.h | 150 ++++++++++++----------- include/svs/orchestrators/manager.h | 9 +- include/svs/orchestrators/vamana.h | 2 +- 8 files changed, 239 insertions(+), 207 deletions(-) diff --git a/include/svs/concepts/distance.h b/include/svs/concepts/distance.h index ec240b88e..7877fab5d 100644 --- a/include/svs/concepts/distance.h +++ b/include/svs/concepts/distance.h @@ -25,6 +25,7 @@ #include #include +#include #include #include @@ -215,6 +216,12 @@ template auto comparator(const T& /*x*/) -> compare_t { return typename T::compare{}; } +/// Distance reported for a missing neighbor: it sorts after every real distance. +template float worst_distance(const T& x) { + return comparator(x)(0.0f, 1.0f) ? std::numeric_limits::infinity() + : -std::numeric_limits::infinity(); +} + ///// ///// Traits ///// diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index 317a1b754..d893798a4 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -659,9 +659,7 @@ class MutableVamanaIndex { size_t metadata_bytes = status_.capacity() * sizeof(SlotMetadata); metadata_bytes += entry_point_.capacity() * sizeof(typename entry_point_type::value_type); - // Estimate: the id pair per entry, counted twice (external->internal hash map and - // internal->external vector); ignores hash-map load-factor slack and vector spare - // capacity. + // Estimate: one id pair per entry for each translation direction. metadata_bytes += 2 * translator_.size() * (sizeof(IDTranslator::external_id_type) + sizeof(IDTranslator::internal_id_type)); @@ -975,28 +973,26 @@ class MutableVamanaIndex { buffer.clear(); return; } + auto builder = [&] { + if constexpr (Filtered) { + return internal_search_builder(*filter); + } else { + return internal_search_builder(); + } + }(); // Perform the greedy search using the provided resources. - auto run = [&](auto& builder) { - concurrent::greedy_search( - graph_, - data_, - accessor, - query, - distance, - buffer, - vamana::EntryPointInitializer{std::span{&seed, 1}}, - builder, - prefetch_parameters, - cancel - ); - }; - if constexpr (Filtered) { - auto builder = internal_search_builder(*filter); - run(builder); - } else { - auto builder = internal_search_builder(); - run(builder); - } + concurrent::greedy_search( + graph_, + data_, + accessor, + query, + distance, + buffer, + vamana::EntryPointInitializer{std::span{&seed, 1}}, + builder, + prefetch_parameters, + cancel + ); // Take a pass over the search buffer to remove any deleted elements that // might remain. buffer.cleanup(); @@ -1024,8 +1020,6 @@ class MutableVamanaIndex { ); } - // `filter` is called from every search thread without locks; it must be thread-safe - // and must not call into this index. template void search( QueryResultView results, @@ -1041,44 +1035,52 @@ class MutableVamanaIndex { threadpool_, threads::StaticPartition{queries.size()}, [&](const auto is, uint64_t SVS_UNUSED(tid)) { - auto body = [&](std::bool_constant) { - size_t num_neighbors = results.n_neighbors(); - auto buffer = search_buffer_type{ - sp.buffer_config_, - distance::comparator(distance_), - sp.search_buffer_visited_set_}; - - auto prefetch_parameters = GreedySearchPrefetchParameters{ - sp.prefetch_lookahead_, sp.prefetch_step_}; - - // Legalize search buffer for this search. - if (buffer.target_capacity() < num_neighbors) { - buffer.change_maxsize(num_neighbors); - } - auto scratch = - extensions::per_thread_batch_search_setup(data_, distance_); - - auto search = greedy_search_closure( - prefetch_parameters, cancel, filter - ); - extensions::per_thread_batch_search( - data_, - buffer, - scratch, - queries, - results, - threads::UnitRange{is}, - search, - *this, - cancel - ); - }; + size_t num_neighbors = results.n_neighbors(); + auto buffer = search_buffer_type{ + sp.buffer_config_, + distance::comparator(distance_), + sp.search_buffer_visited_set_}; + + auto prefetch_parameters = GreedySearchPrefetchParameters{ + sp.prefetch_lookahead_, sp.prefetch_step_}; + + // Legalize search buffer for this search. + if (buffer.target_capacity() < num_neighbors) { + buffer.change_maxsize(num_neighbors); + } + auto scratch = + extensions::per_thread_batch_search_setup(data_, distance_); + if (filter != nullptr) { - [&]() __attribute__((noinline)) { body(std::true_type{}); } + [&]() __attribute__((noinline)) { + extensions::per_thread_batch_search( + data_, + buffer, + scratch, + queries, + results, + threads::UnitRange{is}, + greedy_search_closure( + prefetch_parameters, cancel, filter + ), + *this, + cancel + ); + } (); - } else { - body(std::false_type{}); + return; } + extensions::per_thread_batch_search( + data_, + buffer, + scratch, + queries, + results, + threads::UnitRange{is}, + greedy_search_closure(prefetch_parameters, cancel), + *this, + cancel + ); } ); } @@ -1093,11 +1095,8 @@ class MutableVamanaIndex { translate_to_external(results.indices()); if (filter != nullptr) { - // A concurrent remap may have changed the answer: only return ids that pass - // now. - const float worst = distance::comparator(distance_)(0.0f, 1.0f) - ? std::numeric_limits::infinity() - : -std::numeric_limits::infinity(); + // A concurrent remap may have changed the answer: re-check the final ids. + const float worst = distance::worst_distance(distance_); for (size_t i = 0; i < results.n_queries(); ++i) { for (size_t j = 0; j < results.n_neighbors(); ++j) { auto id = results.index(i, j); diff --git a/include/svs/core/translation.h b/include/svs/core/translation.h index 5b1a09e9a..77da3ce43 100644 --- a/include/svs/core/translation.h +++ b/include/svs/core/translation.h @@ -531,7 +531,27 @@ class IDTranslator { } tsl::robin_map external_to_internal_{}; - tsl::robin_map internal_to_external_{}; + // Vector for lock-free reads; TODO: moves to #447 (same table), not in this PR. + lib::SegmentedVector internal_to_external_{}; + + external_id_type load_external(internal_id_type i) const { + if (i >= internal_to_external_.size()) { + return invalid_external_id; + } + return std::atomic_ref( + const_cast(internal_to_external_[i]) + ) + .load(std::memory_order_acquire); + } + + // Writers only; grows the table first when `i` is beyond it. + void store_external(size_t i, external_id_type e) { + if (i >= internal_to_external_.size()) { + internal_to_external_.resize(i + 1, invalid_external_id); + } + std::atomic_ref(internal_to_external_[i]) + .store(e, std::memory_order_release); + } }; } // namespace svs diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index ac7131b71..072ecb3c3 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -537,9 +537,7 @@ class MutableVamanaIndex { size_t metadata_bytes = status_.capacity() * sizeof(SlotMetadata); metadata_bytes += entry_point_.capacity() * sizeof(typename entry_point_type::value_type); - // Estimate: the id pair per entry, counted twice (external->internal hash map and - // internal->external vector); ignores hash-map load-factor slack and vector spare - // capacity. + // Estimate: one id pair per entry for each translation direction. metadata_bytes += 2 * translator_.size() * (sizeof(IDTranslator::external_id_type) + sizeof(IDTranslator::internal_id_type)); @@ -715,28 +713,26 @@ class MutableVamanaIndex { prefetch_parameters, filter](const auto& query, auto& accessor, auto& distance, auto& buffer) { static_cast(filter); // Unused in regular search. + auto builder = [&] { + if constexpr (Filtered) { + return internal_search_builder(*filter); + } else { + return internal_search_builder(); + } + }(); // Perform the greedy search using the provided resources. - auto run = [&](auto& builder) { - greedy_search( - graph_, - data_, - accessor, - query, - distance, - buffer, - vamana::EntryPointInitializer{lib::as_const_span(entry_point_)}, - builder, - prefetch_parameters, - cancel - ); - }; - if constexpr (Filtered) { - auto builder = internal_search_builder(*filter); - run(builder); - } else { - auto builder = internal_search_builder(); - run(builder); - } + greedy_search( + graph_, + data_, + accessor, + query, + distance, + buffer, + vamana::EntryPointInitializer{lib::as_const_span(entry_point_)}, + builder, + prefetch_parameters, + cancel + ); // Take a pass over the search buffer to remove any deleted elements that // might remain. buffer.cleanup(); @@ -772,43 +768,50 @@ class MutableVamanaIndex { threadpool_, threads::StaticPartition{queries.size()}, [&](const auto is, uint64_t SVS_UNUSED(tid)) { - auto body = [&](std::bool_constant) { - size_t num_neighbors = results.n_neighbors(); - auto buffer = search_buffer_type{ - // Legalize search buffer for this search. - sp.buffer_config_.get_total_capacity() < num_neighbors - ? SearchBufferConfig{num_neighbors} - : sp.buffer_config_, - distance::comparator(distance_), - sp.search_buffer_visited_set_}; - - auto prefetch_parameters = GreedySearchPrefetchParameters{ - sp.prefetch_lookahead_, sp.prefetch_step_}; - - auto scratch = - extensions::per_thread_batch_search_setup(data_, distance_); - - auto search = greedy_search_closure( - prefetch_parameters, cancel, filter - ); - extensions::per_thread_batch_search( - data_, - buffer, - scratch, - queries, - results, - threads::UnitRange{is}, - search, - *this, - cancel - ); - }; + size_t num_neighbors = results.n_neighbors(); + auto buffer = search_buffer_type{ + // Legalize search buffer for this search. + sp.buffer_config_.get_total_capacity() < num_neighbors + ? SearchBufferConfig{num_neighbors} + : sp.buffer_config_, + distance::comparator(distance_), + sp.search_buffer_visited_set_}; + + auto prefetch_parameters = GreedySearchPrefetchParameters{ + sp.prefetch_lookahead_, sp.prefetch_step_}; + + auto scratch = extensions::per_thread_batch_search_setup(data_, distance_); + if (filter != nullptr) { - [&]() __attribute__((noinline)) { body(std::true_type{}); } + [&]() __attribute__((noinline)) { + extensions::per_thread_batch_search( + data_, + buffer, + scratch, + queries, + results, + threads::UnitRange{is}, + greedy_search_closure( + prefetch_parameters, cancel, filter + ), + *this, + cancel + ); + } (); - } else { - body(std::false_type{}); + return; } + extensions::per_thread_batch_search( + data_, + buffer, + scratch, + queries, + results, + threads::UnitRange{is}, + greedy_search_closure(prefetch_parameters, cancel), + *this, + cancel + ); } ); diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index b13e43f21..a1b87ccc2 100644 --- a/include/svs/index/vamana/extensions.h +++ b/include/svs/index/vamana/extensions.h @@ -27,8 +27,6 @@ #include "svs/lib/preprocessor.h" #include "svs/lib/threads.h" -#include - namespace svs::index::vamana::extensions { ///// @@ -594,9 +592,7 @@ void svs_invoke( // Fewer than k results (e.g. a selective filter): pad with invalid ids. for (size_t j = num_results; j < num_neighbors; ++j) { result.index(i, j) = static_cast(-1); - result.distance(i, j) = distance::comparator(distance)(0.0f, 1.0f) - ? std::numeric_limits::infinity() - : -std::numeric_limits::infinity(); + result.distance(i, j) = distance::worst_distance(distance); } } } diff --git a/include/svs/index/vamana/index.h b/include/svs/index/vamana/index.h index f3911d2ae..bce8d8b81 100644 --- a/include/svs/index/vamana/index.h +++ b/include/svs/index/vamana/index.h @@ -513,29 +513,28 @@ class VamanaIndex { prefetch_parameters, filter](const auto& query, auto& accessor, auto& distance, auto& buffer) { static_cast(filter); // Unused in regular search. - auto run = [&](auto& builder) { - greedy_search( - graph_, - data_, - accessor, - query, - distance, - buffer, - vamana::EntryPointInitializer{lib::as_const_span(entry_point_)}, - builder, - prefetch_parameters, - cancel - ); - }; + auto builder = [&] { + if constexpr (Filtered) { + return FilteredNeighborBuilder>{*filter}; + } else { + return internal_search_builder(); + } + }(); + greedy_search( + graph_, + data_, + accessor, + query, + distance, + buffer, + vamana::EntryPointInitializer{lib::as_const_span(entry_point_)}, + builder, + prefetch_parameters, + cancel + ); if constexpr (Filtered) { - auto builder = - FilteredNeighborBuilder>{*filter}; - run(builder); // Remove the invalid entries that remain in the buffer. buffer.cleanup(); - } else { - auto builder = internal_search_builder(); - run(builder); } }; } @@ -618,58 +617,71 @@ class VamanaIndex { threadpool_, threads::StaticPartition{queries.size()}, [&](const auto is, uint64_t SVS_UNUSED(tid)) { - auto body = [&](std::bool_constant) { - // Filtered search needs a buffer that can hold invalid entries. - using buffer_type = std::conditional_t< - Filtered, - MutableBuffer>, - search_buffer_type>; - - // The number of neighbors to store in the result. - size_t num_neighbors = result.n_neighbors(); - - // Allocate scratchspace according to the provided search parameters. - auto search_buffer = buffer_type{ - // Increase the search window size if the defaults are not - // suitable for the requested number of neighbors. - search_parameters.buffer_config_.get_total_capacity() < - num_neighbors - ? SearchBufferConfig{num_neighbors} - : search_parameters.buffer_config_, - distance::comparator(distance_), - search_parameters.search_buffer_visited_set_}; - - auto prefetch_parameters = GreedySearchPrefetchParameters{ - search_parameters.prefetch_lookahead_, - search_parameters.prefetch_step_}; - - // Pre-allocate scratch space needed by the dataset implementation. - auto scratch = - extensions::per_thread_batch_search_setup(data_, distance_); - - auto search = greedy_search_closure( - prefetch_parameters, cancel, filter - ); - // Perform a search over the batch of queries. - extensions::per_thread_batch_search( - data_, - search_buffer, - scratch, - queries, - result, - threads::UnitRange{is}, - search, - *this, - cancel - ); - }; - // Keep the filtered body out of line so regular search is unaffected. if (filter != nullptr) { - [&]() __attribute__((noinline)) { body(std::true_type{}); } + [&]() __attribute__((noinline)) { + // The filtered search buffer must hold invalid entries. + auto search_buffer = MutableBuffer>{ + search_parameters.buffer_config_.get_total_capacity() < + result.n_neighbors() + ? SearchBufferConfig{result.n_neighbors()} + : search_parameters.buffer_config_, + distance::comparator(distance_), + search_parameters.search_buffer_visited_set_}; + auto prefetch_parameters = GreedySearchPrefetchParameters{ + search_parameters.prefetch_lookahead_, + search_parameters.prefetch_step_}; + auto scratch = + extensions::per_thread_batch_search_setup(data_, distance_); + extensions::per_thread_batch_search( + data_, + search_buffer, + scratch, + queries, + result, + threads::UnitRange{is}, + greedy_search_closure( + prefetch_parameters, cancel, filter + ), + *this, + cancel + ); + } (); - } else { - body(std::false_type{}); + return; } + + // The number of neighbors to store in the result. + size_t num_neighbors = result.n_neighbors(); + + // Allocate scratchspace according to the provided search parameters. + auto search_buffer = search_buffer_type{ + // Increase the search window size if the defaults are not suitable for + // the requested number of neighbors. + search_parameters.buffer_config_.get_total_capacity() < num_neighbors + ? SearchBufferConfig{num_neighbors} + : search_parameters.buffer_config_, + distance::comparator(distance_), + search_parameters.search_buffer_visited_set_}; + + auto prefetch_parameters = GreedySearchPrefetchParameters{ + search_parameters.prefetch_lookahead_, + search_parameters.prefetch_step_}; + + // Pre-allocate scratch space needed by the dataset implementation. + auto scratch = extensions::per_thread_batch_search_setup(data_, distance_); + + // Perform a search over the batch of queries. + extensions::per_thread_batch_search( + data_, + search_buffer, + scratch, + queries, + result, + threads::UnitRange{is}, + greedy_search_closure(prefetch_parameters, cancel), + *this, + cancel + ); } ); } diff --git a/include/svs/orchestrators/manager.h b/include/svs/orchestrators/manager.h index 3fcbb4ed6..1625f256d 100644 --- a/include/svs/orchestrators/manager.h +++ b/include/svs/orchestrators/manager.h @@ -146,7 +146,7 @@ class ManagerImpl : public ManagerInterface { const search_parameters_type& search_parameters, const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) override { - dispatch_queries(result, data, [&](const auto& view) { + dispatch_queries(data, [&](const auto& view) { svs::index::search_batch_into_with( implementation_, result, view, search_parameters, cancel ); @@ -179,17 +179,12 @@ class ManagerImpl : public ManagerInterface { // Invoke `f` with the query view of the matching supported type, otherwise throw. template - void dispatch_queries( - [[maybe_unused]] QueryResultView result, - const AnonymousArray<2>& data, - F&& f - ) const { + void dispatch_queries(const AnonymousArray<2>& data, F&& f) const { lib::match( QueryTypes{}, data.type(), [&](lib::Type SVS_UNUSED(type)) { const auto view = data::ConstSimpleDataView(data); - assert(result.n_queries() == view.size()); f(view); }, [&](svs::DataType data_type) { diff --git a/include/svs/orchestrators/vamana.h b/include/svs/orchestrators/vamana.h index e43ba617c..cada48419 100644 --- a/include/svs/orchestrators/vamana.h +++ b/include/svs/orchestrators/vamana.h @@ -299,7 +299,7 @@ class VamanaImpl : public manager::ManagerImpl { const index::vamana::VamanaSearchParameters& search_parameters, const std::function& filter ) override { - this->dispatch_queries(results, queries, [&](const auto& view) { + this->dispatch_queries(queries, [&](const auto& view) { impl().search( results, view, search_parameters, lib::Returns(lib::Const()), &filter ); From 4b0aa589d9ea966cb9f98b47507dadf6511a03d0 Mon Sep 17 00:00:00 2001 From: Rafik Saliev Date: Wed, 25 Nov 2026 06:57:11 -0700 Subject: [PATCH 15/16] Refactor and fix filtered search --- include/svs/concurrent/dynamic_index.h | 128 +++++++++-------------- include/svs/core/translation.h | 36 +------ include/svs/index/vamana/dynamic_index.h | 75 ++++++------- include/svs/index/vamana/extensions.h | 9 ++ include/svs/index/vamana/index.h | 92 +++++++--------- include/svs/orchestrators/vamana.h | 2 +- 6 files changed, 129 insertions(+), 213 deletions(-) diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index d893798a4..10658a7aa 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -195,32 +195,42 @@ template class FilteredValidBuilder { FilteredValidBuilder( const lib::SegmentedVector& status, const IDTranslator& translator, + std::shared_mutex& translator_mutex, const Filter& filter, const void* owner ) : status_{status} - , translator_{&translator} - , filter_{&filter} + , translator_{translator} + , translator_mutex_{translator_mutex} + , filter_{filter} , owner_{owner} {} template PredicatedSearchNeighbor operator()(I i, float distance) const { - bool invalid = + bool valid = std::atomic_ref(const_cast(getindex(status_, i))) - .load(std::memory_order_acquire) != SlotMetadata::Valid; - if (!invalid) { - // Lock-free read; an erased slot has no external id and fails. - size_t external = translator_->get_external_or(i, no_external_id); + .load(std::memory_order_acquire) == SlotMetadata::Valid; + if (valid) { + size_t external; + // TODO: refactor translator to provide a more efficient way to get the external + // id without locking. + { + // Released before the filter runs so a slow filter cannot stall writers. + std::shared_lock lock{translator_mutex_}; + external = translator_.get_external_or(i, no_external_id); + } + // An erased slot has no external id and fails. FilterScope scope{owner_}; - invalid = external == no_external_id || !(*filter_)(external); + valid = external != no_external_id && filter_(external); } - return PredicatedSearchNeighbor(i, distance, !invalid); + return PredicatedSearchNeighbor(i, distance, valid); } private: const lib::SegmentedVector& status_; - const IDTranslator* translator_; - const Filter* filter_; + const IDTranslator& translator_; + std::shared_mutex& translator_mutex_; + const Filter& filter_; const void* owner_; }; @@ -932,11 +942,14 @@ class MutableVamanaIndex { // Return a `greedy_search` compatible builder for this index. // This is an internal method, mostly used to help implement the batch iterator. - ValidBuilder internal_search_builder() const { return ValidBuilder{status_}; } + ValidBuilder internal_search_builder(const AcceptAll& SVS_UNUSED(filter) = {}) const { + return ValidBuilder{status_}; + } template FilteredValidBuilder internal_search_builder(const Filter& filter) const { - return FilteredValidBuilder{status_, translator_, filter, this}; + return FilteredValidBuilder{ + status_, translator_, *translator_mutex_, filter, this}; } /// @brief RAII shared lock guarding data_/graph_ against compact()'s shrink @@ -958,28 +971,20 @@ class MutableVamanaIndex { return std::shared_lock(*translator_mutex_); } - template + template auto greedy_search_closure( + const Builder& builder, GreedySearchPrefetchParameters prefetch_parameters, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), - const std::function* filter = nullptr + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) const { return [&, prefetch_parameters, - filter](const auto& query, auto& accessor, auto& distance, auto& buffer) { - static_cast(filter); // Unused in regular search. + builder](const auto& query, auto& accessor, auto& distance, auto& buffer) { const Idx seed = entry_point(); if (seed == NO_ENTRY) { buffer.clear(); return; } - auto builder = [&] { - if constexpr (Filtered) { - return internal_search_builder(*filter); - } else { - return internal_search_builder(); - } - }(); // Perform the greedy search using the provided resources. concurrent::greedy_search( graph_, @@ -1015,18 +1020,20 @@ class MutableVamanaIndex { scratch.buffer, scratch.scratch, query, - greedy_search_closure(scratch.prefetch_parameters, cancel), + greedy_search_closure( + internal_search_builder(), scratch.prefetch_parameters, cancel + ), *this ); } - template + template void search( QueryResultView results, const Queries& queries, const search_parameters_type& sp, const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), - const std::function* filter = nullptr + const Filter& filter = AcceptAll{} ) { // Internal IDs must retain their meaning until translation has completed. auto compact_lock = lock_storage_shared(); @@ -1051,25 +1058,12 @@ class MutableVamanaIndex { auto scratch = extensions::per_thread_batch_search_setup(data_, distance_); - if (filter != nullptr) { - [&]() __attribute__((noinline)) { - extensions::per_thread_batch_search( - data_, - buffer, - scratch, - queries, - results, - threads::UnitRange{is}, - greedy_search_closure( - prefetch_parameters, cancel, filter - ), - *this, - cancel - ); - } - (); - return; - } + // The buffer top-up ignores the filter, so a filtered search skips it. + using topup_index_type = std::conditional_t< + std::is_same_v, + const MutableVamanaIndex&, + extensions::SupplementSuppressed>; + extensions::per_thread_batch_search( data_, buffer, @@ -1077,8 +1071,10 @@ class MutableVamanaIndex { queries, results, threads::UnitRange{is}, - greedy_search_closure(prefetch_parameters, cancel), - *this, + greedy_search_closure( + internal_search_builder(filter), prefetch_parameters, cancel + ), + static_cast(*this), cancel ); } @@ -1094,7 +1090,7 @@ class MutableVamanaIndex { // Perform one more pass to convert these to external ids. translate_to_external(results.indices()); - if (filter != nullptr) { + if constexpr (!std::is_same_v) { // A concurrent remap may have changed the answer: re-check the final ids. const float worst = distance::worst_distance(distance_); for (size_t i = 0; i < results.n_queries(); ++i) { @@ -1102,7 +1098,7 @@ class MutableVamanaIndex { auto id = results.index(i, j); if (id != static_cast(-1)) { FilterScope scope{this}; - if (!(*filter)(id)) { + if (!filter(id)) { results.index(i, j) = static_cast(-1); } } @@ -2147,19 +2143,11 @@ class MutableVamanaIndex { search_buffer.sort(); // translator_mutex_ shared: guards both the traversal of ``translator_`` and the - // internal IDs it yields against erasure by consolidate()/compact(). A filtered - // search already holds it (see ``search()``); locking again would be recursive. - std::shared_lock translator_lock{*translator_mutex_, std::defer_lock}; - if (filter == nullptr) { - translator_lock.lock(); - } + // internal IDs it yields against erasure by consolidate()/compact(). + std::shared_lock translator_lock{*translator_mutex_}; auto builder = internal_search_builder(); for (auto pair : translator_) { auto internal_id = pair.second; - // `pair.first` is the external id, read under the lock held above. - if (filter != nullptr && !(*filter)(pair.first)) { - continue; - } // Skip slots pending deferred translator cleanup, reserved by an in-flight // add_points, or otherwise not live. if (std::atomic_ref(const_cast(status_[internal_id] @@ -2184,22 +2172,6 @@ class MutableVamanaIndex { } }; -/// -/// @brief Hides an index's id translation from the search extensions. -/// -/// Every ``extensions::single_search`` implementation tops the search buffer up itself, by -/// calling the generic ``extensions::check_and_supplement_search_buffer`` under -/// ``if constexpr (Index::needs_id_translation)``. That routine is unsafe for this index -- -/// see ``MutableVamanaIndex::supplement_search_buffer`` -- and it is a plain function, not -/// a customization point, so it cannot be overridden. Passing this wrapper in place of the -/// index makes that branch disappear, leaving the top-up to the index itself. -/// -/// The implementations touch nothing else on the index, so nothing else needs forwarding. -/// -template struct SupplementSuppressed { - static constexpr bool needs_id_translation = false; -}; - /// /// @brief ``extensions::single_search`` for the concurrent mutable index. /// @@ -2242,7 +2214,7 @@ SVS_FORCE_INLINE void svs_invoke( scratch, query, search, - SupplementSuppressed{}, + vamana::extensions::SupplementSuppressed{}, cancel ); diff --git a/include/svs/core/translation.h b/include/svs/core/translation.h index 77da3ce43..88b95311f 100644 --- a/include/svs/core/translation.h +++ b/include/svs/core/translation.h @@ -38,7 +38,6 @@ #include #include #include -#include namespace svs { @@ -125,7 +124,6 @@ class IDTranslator { if (!lib::all_unique(int_begin, int_end)) { throw ANNEXCEPTION("Internal IDs contain repeat elements!"); } - check_external_not_reserved(ext_begin, ext_end); check_external_free(ext_begin, ext_end); check_internal_free(int_begin, int_end); } @@ -185,8 +183,6 @@ class IDTranslator { throw ANNEXCEPTION("Internal IDs contain repeat elements!"); } - check_external_not_reserved(ext_begin, ext_end); - // Validation pass for (auto e = ext_begin; e != ext_end; ++e) { auto found = external_to_internal_.find(*e); @@ -381,16 +377,6 @@ class IDTranslator { /// @param begin Start forward iterator to the external IDs to check. /// @param end End forward iterator to the external IDs to check. /// - template - void check_external_not_reserved(const Begin& begin, const End& end) const { - check( - begin, - end, - [](auto e) { return std::cmp_equal(e, invalid_external_id); }, - "Reserved external" - ); - } - template void check_external_free(const Begin& begin, const End& end) const { check(begin, end, external_to_internal_, "Index already contains external"); @@ -531,27 +517,7 @@ class IDTranslator { } tsl::robin_map external_to_internal_{}; - // Vector for lock-free reads; TODO: moves to #447 (same table), not in this PR. - lib::SegmentedVector internal_to_external_{}; - - external_id_type load_external(internal_id_type i) const { - if (i >= internal_to_external_.size()) { - return invalid_external_id; - } - return std::atomic_ref( - const_cast(internal_to_external_[i]) - ) - .load(std::memory_order_acquire); - } - - // Writers only; grows the table first when `i` is beyond it. - void store_external(size_t i, external_id_type e) { - if (i >= internal_to_external_.size()) { - internal_to_external_.resize(i + 1, invalid_external_id); - } - std::atomic_ref(internal_to_external_[i]) - .store(e, std::memory_order_release); - } + tsl::robin_map internal_to_external_{}; }; } // namespace svs diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index 072ecb3c3..62ac332ba 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -113,20 +113,22 @@ class ValidBuilder { template class FilteredValidBuilder { public: FilteredValidBuilder(const IDTranslator& translator, const Filter& filter) - : translator_{&translator} - , filter_{&filter} {} + : translator_{translator} + , filter_{filter} {} template constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { + using id_type = typename IDTranslator::external_id_type; + constexpr id_type invalid_id = std::numeric_limits::max(); // delete_entries clears the translator entry, so a missing id means deleted. - auto id = translator_->get_external_or(i, IDTranslator::invalid_external_id); - bool invalid = id == IDTranslator::invalid_external_id || !(*filter_)(id); - return PredicatedSearchNeighbor(i, distance, !invalid); + auto id = translator_.get_external_or(i, invalid_id); + bool valid = id != invalid_id && filter_(id); + return PredicatedSearchNeighbor(i, distance, valid); } private: - const IDTranslator* translator_; - const Filter* filter_; + const IDTranslator& translator_; + const Filter& filter_; }; namespace detail { @@ -696,30 +698,24 @@ class MutableVamanaIndex { // Return a `greedy_search` compatible builder for this index. // This is an internal method, mostly used to help implement the batch iterator. - ValidBuilder internal_search_builder() const { return ValidBuilder{status_}; } + ValidBuilder internal_search_builder(const AcceptAll& SVS_UNUSED(filter) = {}) const { + return ValidBuilder{status_}; + } template FilteredValidBuilder internal_search_builder(const Filter& filter) const { return FilteredValidBuilder{translator_, filter}; } - template + template auto greedy_search_closure( + const Builder& builder, GreedySearchPrefetchParameters prefetch_parameters, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), - const std::function* filter = nullptr + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) const { return [&, prefetch_parameters, - filter](const auto& query, auto& accessor, auto& distance, auto& buffer) { - static_cast(filter); // Unused in regular search. - auto builder = [&] { - if constexpr (Filtered) { - return internal_search_builder(*filter); - } else { - return internal_search_builder(); - } - }(); + builder](const auto& query, auto& accessor, auto& distance, auto& buffer) { // Perform the greedy search using the provided resources. greedy_search( graph_, @@ -751,18 +747,20 @@ class MutableVamanaIndex { scratch.buffer, scratch.scratch, query, - greedy_search_closure(scratch.prefetch_parameters, cancel), + greedy_search_closure( + internal_search_builder(), scratch.prefetch_parameters, cancel + ), *this ); } - template + template void search( QueryResultView results, const Queries& queries, const search_parameters_type& sp, const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), - const std::function* filter = nullptr + const Filter& filter = AcceptAll{} ) { threads::parallel_for( threadpool_, @@ -782,25 +780,12 @@ class MutableVamanaIndex { auto scratch = extensions::per_thread_batch_search_setup(data_, distance_); - if (filter != nullptr) { - [&]() __attribute__((noinline)) { - extensions::per_thread_batch_search( - data_, - buffer, - scratch, - queries, - results, - threads::UnitRange{is}, - greedy_search_closure( - prefetch_parameters, cancel, filter - ), - *this, - cancel - ); - } - (); - return; - } + // The buffer top-up ignores the filter, so a filtered search skips it. + using topup_index_type = std::conditional_t< + std::is_same_v, + const MutableVamanaIndex&, + extensions::SupplementSuppressed>; + extensions::per_thread_batch_search( data_, buffer, @@ -808,8 +793,10 @@ class MutableVamanaIndex { queries, results, threads::UnitRange{is}, - greedy_search_closure(prefetch_parameters, cancel), - *this, + greedy_search_closure( + internal_search_builder(filter), prefetch_parameters, cancel + ), + static_cast(*this), cancel ); } diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index a1b87ccc2..f533494d1 100644 --- a/include/svs/index/vamana/extensions.h +++ b/include/svs/index/vamana/extensions.h @@ -449,6 +449,15 @@ void check_and_supplement_search_buffer( } } +/// @brief Passed to ``single_search`` in place of the index to skip the buffer top-up. +/// +/// The search extensions read nothing but ``needs_id_translation`` from the index. +template struct SupplementSuppressed { + SupplementSuppressed() = default; + explicit SupplementSuppressed(const Index&) {} + static constexpr bool needs_id_translation = false; +}; + /// Customization point object for processing single queries. inline constexpr VamanaSingleSearchType single_search{}; diff --git a/include/svs/index/vamana/index.h b/include/svs/index/vamana/index.h index bce8d8b81..9062bd25c 100644 --- a/include/svs/index/vamana/index.h +++ b/include/svs/index/vamana/index.h @@ -52,20 +52,25 @@ namespace svs::index::vamana { template class BatchIterator; +// The filter of an unfiltered search. +struct AcceptAll { + constexpr bool operator()(size_t) const { return true; } +}; + // Marks candidates failing the filter invalid. template class FilteredNeighborBuilder { public: explicit FilteredNeighborBuilder(const Filter& filter) - : filter_{&filter} {} + : filter_{filter} {} template constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { - bool valid = (*filter_)(static_cast(i)); + bool valid = filter_(static_cast(i)); return PredicatedSearchNeighbor(i, distance, valid); } private: - const Filter* filter_; + const Filter& filter_; }; struct VamanaIndexParameters { @@ -321,6 +326,7 @@ class VamanaIndex { /// Type of the distance functor. using distance_type = Dist; using search_buffer_type = SearchBuffer>; + using filtered_buffer_type = MutableBuffer>; /// Type of the graph. using graph_type = Graph; /// Type of the dataset. @@ -501,25 +507,25 @@ class VamanaIndex { // Return a `greedy_search` compatible builder for this index. // This is an internal method, mostly used to help implement the batch iterator. - static NeighborBuilder internal_search_builder() { return NeighborBuilder(); } + static NeighborBuilder + internal_search_builder(const AcceptAll& SVS_UNUSED(filter) = {}) { + return NeighborBuilder(); + } + + template + static FilteredNeighborBuilder internal_search_builder(const Filter& filter) { + return FilteredNeighborBuilder{filter}; + } - template + template auto greedy_search_closure( + const Builder& builder, GreedySearchPrefetchParameters prefetch_parameters, - const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), - const std::function* filter = nullptr + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) const { return [&, prefetch_parameters, - filter](const auto& query, auto& accessor, auto& distance, auto& buffer) { - static_cast(filter); // Unused in regular search. - auto builder = [&] { - if constexpr (Filtered) { - return FilteredNeighborBuilder>{*filter}; - } else { - return internal_search_builder(); - } - }(); + builder](const auto& query, auto& accessor, auto& distance, auto& buffer) { greedy_search( graph_, data_, @@ -532,7 +538,7 @@ class VamanaIndex { prefetch_parameters, cancel ); - if constexpr (Filtered) { + if constexpr (requires { buffer.cleanup(); }) { // Remove the invalid entries that remain in the buffer. buffer.cleanup(); } @@ -564,7 +570,9 @@ class VamanaIndex { scratch.buffer, scratch.scratch, query, - greedy_search_closure(scratch.prefetch_parameters, cancel), + greedy_search_closure( + internal_search_builder(), scratch.prefetch_parameters, cancel + ), *this ); } @@ -605,56 +613,28 @@ class VamanaIndex { /// - The value type of ``queries`` is compatible with the value type of the index /// dataset with respect to the stored distance functor. /// - template + template void search( QueryResultView result, const Queries& queries, const search_parameters_type& search_parameters, const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), - const std::function* filter = nullptr + const Filter& filter = AcceptAll{} ) { threads::parallel_for( threadpool_, threads::StaticPartition{queries.size()}, [&](const auto is, uint64_t SVS_UNUSED(tid)) { - if (filter != nullptr) { - [&]() __attribute__((noinline)) { - // The filtered search buffer must hold invalid entries. - auto search_buffer = MutableBuffer>{ - search_parameters.buffer_config_.get_total_capacity() < - result.n_neighbors() - ? SearchBufferConfig{result.n_neighbors()} - : search_parameters.buffer_config_, - distance::comparator(distance_), - search_parameters.search_buffer_visited_set_}; - auto prefetch_parameters = GreedySearchPrefetchParameters{ - search_parameters.prefetch_lookahead_, - search_parameters.prefetch_step_}; - auto scratch = - extensions::per_thread_batch_search_setup(data_, distance_); - extensions::per_thread_batch_search( - data_, - search_buffer, - scratch, - queries, - result, - threads::UnitRange{is}, - greedy_search_closure( - prefetch_parameters, cancel, filter - ), - *this, - cancel - ); - } - (); - return; - } - // The number of neighbors to store in the result. size_t num_neighbors = result.n_neighbors(); + using buffer_type = std::conditional_t< + std::is_same_v, + search_buffer_type, + filtered_buffer_type>; + // Allocate scratchspace according to the provided search parameters. - auto search_buffer = search_buffer_type{ + auto search_buffer = buffer_type{ // Increase the search window size if the defaults are not suitable for // the requested number of neighbors. search_parameters.buffer_config_.get_total_capacity() < num_neighbors @@ -678,7 +658,9 @@ class VamanaIndex { queries, result, threads::UnitRange{is}, - greedy_search_closure(prefetch_parameters, cancel), + greedy_search_closure( + internal_search_builder(filter), prefetch_parameters, cancel + ), *this, cancel ); diff --git a/include/svs/orchestrators/vamana.h b/include/svs/orchestrators/vamana.h index cada48419..d82014167 100644 --- a/include/svs/orchestrators/vamana.h +++ b/include/svs/orchestrators/vamana.h @@ -301,7 +301,7 @@ class VamanaImpl : public manager::ManagerImpl { ) override { this->dispatch_queries(queries, [&](const auto& view) { impl().search( - results, view, search_parameters, lib::Returns(lib::Const()), &filter + results, view, search_parameters, lib::Returns(lib::Const()), filter ); }); } From 1e6c7526b086d658f7218425065a975171dd3da0 Mon Sep 17 00:00:00 2001 From: Rafik Saliev Date: Wed, 25 Nov 2026 08:06:01 -0700 Subject: [PATCH 16/16] Add filtered search tests for MutableVamana and Static Vamana indices --- tests/svs/concepts/distance.cpp | 14 ++ tests/svs/concurrent/concurrency.cpp | 156 +++++++++++++++++ tests/svs/concurrent/dynamic_index.cpp | 132 ++++++++++++++ tests/svs/index/vamana/dynamic_index.cpp | 84 +++++++++ tests/svs/index/vamana/index.cpp | 69 ++++++++ tests/utils/filtered_search.h | 210 +++++++++++++++++++++++ 6 files changed, 665 insertions(+) create mode 100644 tests/utils/filtered_search.h diff --git a/tests/svs/concepts/distance.cpp b/tests/svs/concepts/distance.cpp index d5ec1b38f..6f04c0992 100644 --- a/tests/svs/concepts/distance.cpp +++ b/tests/svs/concepts/distance.cpp @@ -23,6 +23,10 @@ // catch2 #include "catch2/catch_test_macros.hpp" +// stl +#include +#include + namespace { // Comparison operators. struct CustomComparator : std::less<> { @@ -41,6 +45,10 @@ struct NoComparator { using compare = std::less<>; }; +struct LargerIsBetter { + using compare = std::greater<>; +}; + // Implicit Broadcasting. struct ImplicitBroadcast { static constexpr bool implicit_broadcast = true; @@ -83,6 +91,12 @@ CATCH_TEST_CASE("Distance Concepts", "[core][distance]") { CATCH_REQUIRE(std::is_same_v>); } + CATCH_SECTION("Worst Distance") { + const float infinity = std::numeric_limits::infinity(); + CATCH_REQUIRE(svs::distance::worst_distance(NoComparator{}) == infinity); + CATCH_REQUIRE(svs::distance::worst_distance(LargerIsBetter{}) == -infinity); + } + CATCH_SECTION("Implicit Broadcast") { CATCH_REQUIRE(svs::distance::implicitly_broadcastable() == true); CATCH_REQUIRE( diff --git a/tests/svs/concurrent/concurrency.cpp b/tests/svs/concurrent/concurrency.cpp index e5f4b9e9d..5e779c19f 100644 --- a/tests/svs/concurrent/concurrency.cpp +++ b/tests/svs/concurrent/concurrency.cpp @@ -46,7 +46,9 @@ // stl #include #include +#include #include +#include #include #include #include @@ -581,3 +583,157 @@ CATCH_TEST_CASE("Concurrent MutableVamanaIndex batch iterator", "[concurrent][in CATCH_REQUIRE(batches_completed.load() > 0); } } + +// A filtered search reads the label of every candidate while writers insert, delete and +// relabel. The filter passes even labels and the relabeler keeps flipping entries between +// an even and an odd label, so an entry accepted under a label it has since lost must not +// come back under the new one. +CATCH_TEST_CASE( + "Concurrent MutableVamanaIndex filtered search during mutation", "[concurrent][index]" +) { + const size_t total = kInitialPoints + kIncrementalPoints; + auto base = random_vectors(total, kDim, 1357); + + std::vector initial_ids(kInitialPoints); + std::iota(initial_ids.begin(), initial_ids.end(), 0); + auto initial_slice = std::vector( + base.begin(), base.begin() + static_cast(kInitialPoints * kDim) + ); + auto index = build_index(initial_slice, kDim, initial_ids, kBuildThreads); + + auto sp = index->get_search_parameters(); + sp.buffer_config({100}); + + auto queries_raw = random_vectors(kNumQueries, kDim, 2468); + auto queries = make_dataset(queries_raw, kDim); + + const auto passes = [](size_t id) { return id % 2 == 0; }; + const auto never_cancel = svs::lib::Returns(svs::lib::Const()); + // Odd, and past every label the writer inserts. + const size_t relabel_offset = 2 * total + 1; + // The relabeler owns the labels with residue 0 modulo this stride. + constexpr size_t kStride = 40; + + std::atomic writer_done{false}; + std::atomic searches_completed{0}; + std::atomic filter_violations{0}; + std::atomic bad_padding{0}; + std::atomic duplicate_ids{0}; + std::atomic failed_relabels{0}; + std::atomic exceptions{0}; + + std::thread writer{[&] { + try { + constexpr size_t kBatch = 250; + for (size_t offset = 0; offset < kIncrementalPoints; offset += kBatch) { + const size_t n = std::min(kBatch, kIncrementalPoints - offset); + add_batch(*index, base, kInitialPoints + offset, n); + + // Retire passing labels: an even residue, never the relabeler's. + const size_t residue = 2 * ((offset / kBatch) % (kStride / 2 - 1) + 1); + std::vector to_delete; + for (size_t id = residue; id < kInitialPoints; id += kStride) { + to_delete.push_back(id); + } + index->delete_entries(to_delete); + } + } catch (const std::exception& e) { + CATCH_WARN("writer threw: " << e.what()); + exceptions.fetch_add(1); + } + writer_done.store(true); + }}; + + std::thread relabeler{[&] { + try { + // Stop only after an even number of passes, so every entry ends under its + // original label. + bool flipped = false; + while (!writer_done.load() || flipped) { + for (size_t id = 0; id < kInitialPoints; id += kStride) { + const size_t from = flipped ? id + relabel_offset : id; + const size_t to = flipped ? id : id + relabel_offset; + if (index->replace_external_id(from, to) != + cc::ReplaceExternalIdResult::Ok) { + failed_relabels.fetch_add(1, std::memory_order_relaxed); + } + } + flipped = !flipped; + std::this_thread::yield(); + } + } catch (const std::exception& e) { + CATCH_WARN("relabeler threw: " << e.what()); + exceptions.fetch_add(1); + } + }}; + + auto searcher = [&] { + try { + auto results = svs::QueryResult{kNumQueries, kNumNeighbors}; + std::unordered_set seen_ids; + while (!writer_done.load(std::memory_order_relaxed)) { + index->search(results.view(), queries, sp, never_cancel, passes); + for (size_t q = 0; q < kNumQueries; ++q) { + seen_ids.clear(); + for (size_t j = 0; j < kNumNeighbors; ++j) { + const size_t id = results.index(q, j); + // A relabel caught by the final re-check leaves padding anywhere + // in the row, not only at its end. + if (id == static_cast(-1)) { + if (results.distance(q, j) != + std::numeric_limits::infinity()) { + bad_padding.fetch_add(1, std::memory_order_relaxed); + } + continue; + } + if (!passes(id)) { + filter_violations.fetch_add(1, std::memory_order_relaxed); + } + if (!seen_ids.insert(id).second) { + duplicate_ids.fetch_add(1, std::memory_order_relaxed); + } + } + } + searches_completed.fetch_add(1, std::memory_order_relaxed); + // A batch search holds the index's thread pool for its whole duration and + // `add_points` needs it too: step aside so the writer is not starved. + std::this_thread::sleep_for(std::chrono::microseconds(200)); + } + } catch (const std::exception& e) { + CATCH_WARN("searcher threw: " << e.what()); + exceptions.fetch_add(1); + } + }; + + std::vector searchers; + for (int i = 0; i < 2; ++i) { + searchers.emplace_back(searcher); + } + writer.join(); + relabeler.join(); + for (auto& t : searchers) { + t.join(); + } + + CATCH_INFO("filtered searches completed: " << searches_completed.load()); + CATCH_REQUIRE(exceptions.load() == 0); + CATCH_REQUIRE(failed_relabels.load() == 0); + CATCH_REQUIRE(filter_violations.load() == 0); + CATCH_REQUIRE(bad_padding.load() == 0); + CATCH_REQUIRE(duplicate_ids.load() == 0); + CATCH_REQUIRE(searches_completed.load() > 0); + + // Quiescent again, the filtered search must still find the passing neighbors. + std::unordered_set live; + index->on_ids([&](size_t id) { + if (passes(id)) { + live.insert(id); + } + }); + auto truth = ground_truth(base, live, queries_raw, kDim, kNumNeighbors); + auto results = svs::QueryResult{kNumQueries, kNumNeighbors}; + index->search(results.view(), queries, sp, never_cancel, passes); + const double recall = recall_at_k(results, truth); + CATCH_INFO("post-mutation filtered recall@" << kNumNeighbors << " = " << recall); + CATCH_REQUIRE(recall > 0.85); +} diff --git a/tests/svs/concurrent/dynamic_index.cpp b/tests/svs/concurrent/dynamic_index.cpp index 214dec205..a3832b3b3 100644 --- a/tests/svs/concurrent/dynamic_index.cpp +++ b/tests/svs/concurrent/dynamic_index.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -33,12 +34,16 @@ #include "svs/core/recall.h" #include "svs/lib/spinlock.h" #include "svs/lib/timing.h" +#include "svs/orchestrators/concurrent_dynamic_vamana.h" // catch2 +#include "catch2/catch_template_test_macros.hpp" #include "catch2/catch_test_macros.hpp" +#include "catch2/matchers/catch_matchers_string.hpp" #include // tests +#include "tests/utils/filtered_search.h" #include "tests/utils/test_dataset.h" #include "tests/utils/utils.h" @@ -627,3 +632,130 @@ CATCH_TEST_CASE( const size_t usage = index.get_memory_breakdown().total(); CATCH_REQUIRE(usage == expected_total_bytes); } + +CATCH_TEMPLATE_TEST_CASE( + "Concurrent MutableVamana Index Filtered Search", + "[concurrent][graph_index][dynamic_index][filtered]", + svs::distance::DistanceL2, + svs::distance::DistanceIP +) { + using Distance = TestType; + const size_t num_threads = 2; + const size_t num_neighbors = 10; + + // Labels differ from internal ids, so a filter applied to the wrong kind of id fails. + // Enough queries for each search thread to get a batch of its own. + auto reference = svs_test::FilteredSearchReference(64, 1'000'003); + const auto& queries = reference.queries(); + const auto& ids = reference.ids(); + const auto parameters = reference.build_parameters(); + auto search_parameters = svs::index::vamana::VamanaSearchParameters{}; + search_parameters.buffer_config_ = svs::index::vamana::SearchBufferConfig{100}; + auto unfiltered = svs::QueryResult(queries.size(), num_neighbors); + + CATCH_SECTION("Index") { + auto index = cc::MutableVamanaIndex( + parameters, data_segmented_f32(), ids, Distance(), num_threads + ); + auto search = [&](const auto& filter) { + auto results = svs::QueryResult(queries.size(), num_neighbors); + index.search( + results.view(), + queries.cview(), + search_parameters, + svs::lib::Returns(svs::lib::Const()), + filter + ); + return results; + }; + index.search(unfiltered.view(), queries.cview(), search_parameters); + svs_test::check_filtered_search(reference, search, unfiltered); + + // The filter sees the current label of a relabeled entry. + const size_t old_id = ids[43]; + const size_t new_id = 7; + CATCH_REQUIRE( + index.replace_external_id(old_id, new_id) == cc::ReplaceExternalIdResult::Ok + ); + reference.relabel(old_id, new_id); + const auto only_new = [=](size_t id) { return id == new_id; }; + CATCH_REQUIRE(reference.check(search(only_new), only_new) == 1.0); + const auto only_old = [=](size_t id) { return id == old_id; }; + CATCH_REQUIRE(reference.check(search(only_old), only_old) == 1.0); + + // Deleted entries are never returned, before or after consolidation. + auto deleted = std::vector{}; + for (size_t i = 0; i < ids.size(); i += 3) { + deleted.push_back(ids[i]); + } + index.delete_entries(deleted); + reference.erase(deleted); + const auto every_tenth = [](size_t id) { return id % 10 == 0; }; + CATCH_REQUIRE( + reference.check(search(every_tenth), every_tenth) > + reference.min_selective_recall + ); + // Consolidating a quick build costs recall, so only require well-formed rows. + index.consolidate(); + reference.check(search(every_tenth), every_tenth); + } + + CATCH_SECTION("Orchestrator") { + auto index = svs::ConcurrentDynamicVamana::build( + parameters, data_segmented_f32(), ids, Distance(), num_threads + ); + auto search = [&](const std::function& filter) { + auto results = svs::QueryResult(queries.size(), num_neighbors); + index.filtered_search( + results.view(), queries.cview(), search_parameters, filter + ); + return results; + }; + index.search(unfiltered.view(), queries.cview(), search_parameters); + svs_test::check_filtered_search(reference, search, unfiltered); + } +} + +CATCH_TEST_CASE( + "Concurrent MutableVamana Index Filter Reentrancy", + "[concurrent][graph_index][dynamic_index][filtered]" +) { + using Distance = svs::distance::DistanceL2; + const size_t num_threads = 2; + const size_t num_neighbors = 10; + + auto reference = svs_test::FilteredSearchReference(64); + const auto& queries = reference.queries(); + const auto& ids = reference.ids(); + const auto parameters = reference.build_parameters(); + auto search_parameters = svs::index::vamana::VamanaSearchParameters{}; + search_parameters.buffer_config_ = svs::index::vamana::SearchBufferConfig{100}; + + auto index = cc::MutableVamanaIndex( + parameters, data_segmented_f32(), ids, Distance(), num_threads + ); + auto search = [&](const auto& filter) { + auto results = svs::QueryResult(queries.size(), num_neighbors); + index.search( + results.view(), + queries.cview(), + search_parameters, + svs::lib::Returns(svs::lib::Const()), + filter + ); + return results; + }; + + const auto reentrant = [&](size_t id) { return index.get_datum(id).size() != 0; }; + CATCH_REQUIRE_THROWS_WITH( + search(reentrant), + Catch::Matchers::ContainsSubstring("filter must not call into the same index") + ); + + // Only the index being filtered is off limits, and only while its filter runs. + auto other = cc::MutableVamanaIndex( + parameters, data_segmented_f32(), ids, Distance(), num_threads + ); + const auto calls_other = [&](size_t id) { return other.get_datum(id).size() != 0; }; + reference.check(search(calls_other), calls_other); +} diff --git a/tests/svs/index/vamana/dynamic_index.cpp b/tests/svs/index/vamana/dynamic_index.cpp index 94daddcf1..ab3ad82de 100644 --- a/tests/svs/index/vamana/dynamic_index.cpp +++ b/tests/svs/index/vamana/dynamic_index.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -35,10 +36,12 @@ #include "svs/orchestrators/dynamic_vamana.h" // catch2 +#include "catch2/catch_template_test_macros.hpp" #include "catch2/catch_test_macros.hpp" #include // tests +#include "tests/utils/filtered_search.h" #include "tests/utils/test_dataset.h" #include "tests/utils/utils.h" @@ -464,3 +467,84 @@ CATCH_TEST_CASE("MutableVamana Index Memory Usage", "[graph_index][dynamic_index const size_t usage = index.get_memory_breakdown().total(); CATCH_REQUIRE(usage == expected_total_bytes); } + +CATCH_TEMPLATE_TEST_CASE( + "MutableVamana Index Filtered Search", + "[graph_index][dynamic_index][filtered]", + svs::distance::DistanceL2, + svs::distance::DistanceIP +) { + using Distance = TestType; + const size_t num_threads = 2; + const size_t num_neighbors = 10; + + // Labels differ from internal ids, so a filter applied to the wrong kind of id fails. + // Enough queries for each search thread to get a batch of its own. + auto reference = svs_test::FilteredSearchReference(64, 1'000'003); + const auto& queries = reference.queries(); + const auto& ids = reference.ids(); + const auto parameters = reference.build_parameters(); + auto search_parameters = svs::index::vamana::VamanaSearchParameters{}; + search_parameters.buffer_config_ = svs::index::vamana::SearchBufferConfig{100}; + auto unfiltered = svs::QueryResult(queries.size(), num_neighbors); + + CATCH_SECTION("Index") { + auto index = svs::index::vamana::MutableVamanaIndex( + parameters, test_dataset::data_blocked_f32(), ids, Distance(), num_threads + ); + auto search = [&](const auto& filter) { + auto results = svs::QueryResult(queries.size(), num_neighbors); + index.search( + results.view(), + queries.cview(), + search_parameters, + svs::lib::Returns(svs::lib::Const()), + filter + ); + return results; + }; + index.search(unfiltered.view(), queries.cview(), search_parameters); + svs_test::check_filtered_search(reference, search, unfiltered); + + // The filter sees the current label of a relabeled entry. + const size_t old_id = ids[43]; + const size_t new_id = 7; + index.replace_external_id(old_id, new_id); + reference.relabel(old_id, new_id); + const auto only_new = [=](size_t id) { return id == new_id; }; + CATCH_REQUIRE(reference.check(search(only_new), only_new) == 1.0); + const auto only_old = [=](size_t id) { return id == old_id; }; + CATCH_REQUIRE(reference.check(search(only_old), only_old) == 1.0); + + // Deleted entries are never returned, before or after consolidation. + auto deleted = std::vector{}; + for (size_t i = 0; i < ids.size(); i += 3) { + deleted.push_back(ids[i]); + } + index.delete_entries(deleted); + reference.erase(deleted); + const auto every_tenth = [](size_t id) { return id % 10 == 0; }; + CATCH_REQUIRE( + reference.check(search(every_tenth), every_tenth) > + reference.min_selective_recall + ); + // Consolidating a quick build costs recall, so only require well-formed rows. + index.consolidate(); + reference.check(search(every_tenth), every_tenth); + } + + CATCH_SECTION("Orchestrator") { + auto index = svs::DynamicVamana::build( + parameters, test_dataset::data_blocked_f32(), ids, Distance(), num_threads + ); + auto search = [&](const std::function& filter) { + auto results = svs::QueryResult(queries.size(), num_neighbors); + index.filtered_search( + results.view(), queries.cview(), search_parameters, filter + ); + return results; + }; + index.search(unfiltered.view(), queries.cview(), search_parameters); + svs_test::check_filtered_search(reference, search, unfiltered); + } +} diff --git a/tests/svs/index/vamana/index.cpp b/tests/svs/index/vamana/index.cpp index 3cd7ea211..8d6a2491a 100644 --- a/tests/svs/index/vamana/index.cpp +++ b/tests/svs/index/vamana/index.cpp @@ -29,10 +29,12 @@ #include "svs/quantization/scalar/scalar.h" // catch2 +#include "catch2/catch_template_test_macros.hpp" #include "catch2/catch_test_macros.hpp" #include // tests +#include "tests/utils/filtered_search.h" #include "tests/utils/generators.h" #include "tests/utils/test_dataset.h" #include "tests/utils/utils.h" @@ -41,6 +43,7 @@ // svsbenchmark #include "svs-benchmark/benchmark.h" // stl +#include #include #include @@ -847,3 +850,69 @@ CATCH_TEST_CASE("Vamana Index Bugcheck and Regression", "[vamana][index][regress CATCH_CHECK(build_and_search(64, 3072)); } } + +CATCH_TEMPLATE_TEST_CASE( + "Static VamanaIndex Filtered Search", + "[vamana][index][filtered]", + svs::distance::DistanceL2, + svs::distance::DistanceIP +) { + using Distance = TestType; + const size_t num_threads = 2; + const size_t num_neighbors = 10; + + // Enough queries for each search thread to get a batch of its own. + auto reference = svs_test::FilteredSearchReference(64); + const auto& queries = reference.queries(); + const auto parameters = reference.build_parameters(); + auto search_parameters = svs::index::vamana::VamanaSearchParameters{}; + search_parameters.buffer_config_ = svs::index::vamana::SearchBufferConfig{100}; + auto unfiltered = svs::QueryResult(queries.size(), num_neighbors); + + CATCH_SECTION("Index") { + auto index = svs::index::vamana::auto_build( + parameters, test_dataset::data_f32(), Distance(), num_threads + ); + auto search = [&](const auto& filter) { + auto results = svs::QueryResult(queries.size(), num_neighbors); + index.search( + results.view(), + queries.cview(), + search_parameters, + svs::lib::Returns(svs::lib::Const()), + filter + ); + return results; + }; + index.search(unfiltered.view(), queries.cview(), search_parameters); + svs_test::check_filtered_search(reference, search, unfiltered); + } + + CATCH_SECTION("Orchestrator") { + auto index = svs::Vamana::build( + parameters, test_dataset::data_f32(), Distance(), num_threads + ); + auto search = [&](const std::function& filter) { + auto results = svs::QueryResult(queries.size(), num_neighbors); + index.filtered_search( + results.view(), queries.cview(), search_parameters, filter + ); + return results; + }; + index.search(unfiltered.view(), queries.cview(), search_parameters); + svs_test::check_filtered_search(reference, search, unfiltered); + + // The index was built for float queries only. + auto results = svs::QueryResult(queries.size(), num_neighbors); + auto bytes = svs::data::SimpleData(queries.size(), queries.dimensions()); + CATCH_REQUIRE_THROWS_AS( + index.filtered_search( + results.view(), + bytes.cview(), + search_parameters, + [](size_t) { return true; } + ), + svs::ANNException + ); + } +} diff --git a/tests/utils/filtered_search.h b/tests/utils/filtered_search.h new file mode 100644 index 000000000..69eff3427 --- /dev/null +++ b/tests/utils/filtered_search.h @@ -0,0 +1,210 @@ +/* + * Copyright 2026 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +// svs +#include "svs/concepts/distance.h" +#include "svs/core/data.h" +#include "svs/core/distance.h" +#include "svs/core/query_result.h" +#include "svs/index/vamana/build_params.h" + +// tests +#include "tests/utils/test_dataset.h" + +// catch2 +#include "catch2/catch_approx.hpp" +#include "catch2/catch_test_macros.hpp" + +// stl +#include +#include +#include +#include +#include +#include +#include +#include + +namespace svs_test { + +/// @brief Checks filtered search results against an exhaustive scan of the test dataset. +/// +/// Row ``i`` of the dataset is labeled ``first_id + i``. Only the first ``num_queries`` +/// test queries are used, to keep the scan cheap. +template class FilteredSearchReference { + public: + /// The id a filtered search writes to result slots it could not fill. + static constexpr size_t padding = static_cast(-1); + + explicit FilteredSearchReference(size_t num_queries, size_t first_id = 0) + : data_{test_dataset::data_f32()} + , queries_{num_queries, data_.dimensions()} + , ids_(data_.size()) { + auto all_queries = test_dataset::queries(); + for (size_t i = 0; i < num_queries; ++i) { + queries_.set_datum(i, all_queries.get_datum(i)); + } + for (size_t i = 0; i < ids_.size(); ++i) { + ids_[i] = first_id + i; + rows_.emplace(ids_[i], i); + } + } + + const svs::data::SimpleData& queries() const { return queries_; } + + /// The initial labels of the dataset rows, in row order. + const std::vector& ids() const { return ids_; } + + /// Parameters for a quick build over the test dataset with ``Distance``. + static svs::index::vamana::VamanaBuildParameters build_parameters() { + // Distances where larger is better need alpha below one. + const bool smaller_is_better = svs::distance::comparator(Distance{})(0.0f, 1.0f); + return {smaller_is_better ? 1.2f : 0.95f, 64, 10, 20, 10, true}; + } + + /// Recall floor for a filter passing one label in ten: such a filter makes the search + /// look much further than the plain search does, even on a quick build. + static constexpr double min_selective_recall = 0.9; + + /// Forget labels that were deleted from the index under test. + void erase(std::span ids) { + for (auto id : ids) { + rows_.erase(id); + } + } + + /// Follow a relabel made in the index under test. + void relabel(size_t old_id, size_t new_id) { + auto node = rows_.extract(old_id); + node.key() = new_id; + rows_.insert(std::move(node)); + } + + /// @brief Require well-formed results for a search with ``filter``; return the recall. + /// + /// Each row must hold as many neighbors as there are live labels passing ``filter`` + /// (up to the row length), best first and each with its true distance, followed only + /// by padding. + template + double check(const svs::QueryResult& results, const Filter& filter) const { + CATCH_REQUIRE(results.n_queries() == queries_.size()); + const size_t num_neighbors = results.n_neighbors(); + const auto compare = svs::distance::comparator(Distance{}); + + size_t hits = 0; + size_t total = 0; + auto exact = std::vector>{}; + auto seen = std::unordered_set{}; + for (size_t q = 0; q < queries_.size(); ++q) { + const auto query = queries_.get_datum(q); + auto distance = Distance{}; + svs::distance::maybe_fix_argument(distance, query); + auto true_distance = [&](size_t row) { + return svs::distance::compute(distance, query, data_.get_datum(row)); + }; + + exact.clear(); + for (const auto& [id, row] : rows_) { + if (filter(id)) { + exact.emplace_back(true_distance(row), id); + } + } + std::sort(exact.begin(), exact.end(), [&](const auto& a, const auto& b) { + return compare(a.first, b.first); + }); + exact.resize(std::min(num_neighbors, exact.size())); + + seen.clear(); + size_t found = 0; + for (; found < num_neighbors; ++found) { + const size_t id = results.index(q, found); + if (id == padding) { + break; + } + CATCH_INFO("query " << q << ", neighbor " << found << ", id " << id); + CATCH_REQUIRE(filter(id)); + CATCH_REQUIRE(seen.insert(id).second); + auto row = rows_.find(id); + CATCH_REQUIRE(row != rows_.end()); + const float returned = results.distance(q, found); + CATCH_REQUIRE( + returned == + Catch::Approx(true_distance(row->second)).epsilon(1e-4).margin(1e-3) + ); + if (found > 0) { + CATCH_REQUIRE(!compare(returned, results.distance(q, found - 1))); + } + hits += std::any_of(exact.begin(), exact.end(), [&](const auto& e) { + return e.second == id; + }); + } + CATCH_INFO("query " << q << " found " << found << " neighbors"); + CATCH_REQUIRE(found == exact.size()); + for (size_t j = found; j < num_neighbors; ++j) { + CATCH_REQUIRE(results.index(q, j) == padding); + // Padding must sort after every real distance. + const float distance_j = results.distance(q, j); + CATCH_REQUIRE(std::isinf(distance_j)); + CATCH_REQUIRE(!compare(distance_j, 0.0f)); + } + total += exact.size(); + } + return total == 0 ? 1.0 : static_cast(hits) / static_cast(total); + } + + private: + svs::data::SimpleData data_; + svs::data::SimpleData queries_; + std::vector ids_; + std::unordered_map rows_{}; +}; + +/// @brief The checks every filtered search must pass on an index nothing was deleted from. +/// +/// ``search(filter)`` returns the results of a filtered search for the reference queries, +/// ``unfiltered`` those of the plain search with the same parameters. +template +void check_filtered_search( + const FilteredSearchReference& reference, + const Search& search, + const svs::QueryResult& unfiltered +) { + const auto every_tenth = [](size_t id) { return id % 10 == 0; }; + CATCH_REQUIRE( + reference.check(search(every_tenth), every_tenth) > reference.min_selective_recall + ); + + // A filter passing everything must not cost recall against the plain search. + const auto accept_all = [](size_t) { return true; }; + const double unfiltered_recall = reference.check(unfiltered, accept_all); + CATCH_REQUIRE( + reference.check(search(accept_all), accept_all) > unfiltered_recall - 0.05 + ); + + // Fewer passing labels than requested neighbors: all of them, then padding. + const auto& ids = reference.ids(); + const auto few = [&](size_t id) { + return id == ids[100] || id == ids[2000] || id == ids[7000]; + }; + CATCH_REQUIRE(reference.check(search(few), few) == 1.0); + + const auto none = [](size_t) { return false; }; + CATCH_REQUIRE(reference.check(search(none), none) == 1.0); +} + +} // namespace svs_test