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 1fc1a8980..10658a7aa 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -171,6 +171,69 @@ class ValidBuilder { const lib::SegmentedVector& status_; }; +// 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 { + explicit FilterScope(const void* index) + : previous_{filtering_index} { + filtering_index = index; + } + ~FilterScope() { filtering_index = previous_; } + const void* previous_; +}; + +inline void check_not_in_filter(const void* index) { + if (filtering_index == index) { + 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: + FilteredValidBuilder( + const lib::SegmentedVector& status, + const IDTranslator& translator, + std::shared_mutex& translator_mutex, + const Filter& filter, + const void* owner + ) + : status_{status} + , translator_{translator} + , translator_mutex_{translator_mutex} + , filter_{filter} + , owner_{owner} {} + + template + PredicatedSearchNeighbor operator()(I i, float distance) const { + bool valid = + std::atomic_ref(const_cast(getindex(status_, i))) + .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_}; + valid = external != no_external_id && filter_(external); + } + return PredicatedSearchNeighbor(i, distance, valid); + } + + private: + const lib::SegmentedVector& status_; + const IDTranslator& translator_; + std::shared_mutex& translator_mutex_; + const Filter& filter_; + const void* owner_; +}; + template class MutableVamanaIndex { friend class MultiMutableVamanaIndex; @@ -606,11 +669,7 @@ 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: one id pair per entry for each translation direction. metadata_bytes += 2 * translator_.size() * (sizeof(IDTranslator::external_id_type) + sizeof(IDTranslator::internal_id_type)); @@ -810,6 +869,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 +942,15 @@ 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_, *translator_mutex_, filter, this}; + } /// @brief RAII shared lock guarding data_/graph_ against compact()'s shrink /// (which frees segments). Used by searches, iterators and mutations that @@ -889,6 +959,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(this); std::shared_lock gatekeeper_lock{*compact_gatekeeper_}; return std::shared_lock(*compact_mutex_); } @@ -900,13 +971,15 @@ class MutableVamanaIndex { return std::shared_lock(*translator_mutex_); } + template auto greedy_search_closure( + const Builder& builder, GreedySearchPrefetchParameters prefetch_parameters, const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) const { - return [&, prefetch_parameters]( - const auto& query, auto& accessor, auto& distance, auto& buffer - ) { + return [&, + prefetch_parameters, + builder](const auto& query, auto& accessor, auto& distance, auto& buffer) { const Idx seed = entry_point(); if (seed == NO_ENTRY) { buffer.clear(); @@ -921,7 +994,7 @@ class MutableVamanaIndex { distance, buffer, vamana::EntryPointInitializer{std::span{&seed, 1}}, - internal_search_builder(), + builder, prefetch_parameters, cancel ); @@ -947,17 +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 lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const Filter& filter = AcceptAll{} ) { // Internal IDs must retain their meaning until translation has completed. auto compact_lock = lock_storage_shared(); @@ -982,6 +1058,12 @@ class MutableVamanaIndex { auto scratch = extensions::per_thread_batch_search_setup(data_, distance_); + // 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, @@ -989,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 ); } @@ -1005,6 +1089,26 @@ 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 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) { + for (size_t j = 0; j < results.n_neighbors(); ++j) { + auto id = results.index(i, j); + 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; + } + } + } + } } /// @@ -1400,6 +1504,7 @@ class MutableVamanaIndex { /// improve performance but requires more working memory. /// void compact(Idx batch_size = 1'000) { + check_not_in_filter(this); std::lock_guard gatekeeper_lock{*compact_gatekeeper_}; std::lock_guard compact_lock{*compact_mutex_}; @@ -2067,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. /// @@ -2125,7 +2214,7 @@ SVS_FORCE_INLINE void svs_invoke( scratch, query, search, - SupplementSuppressed{}, + vamana::extensions::SupplementSuppressed{}, cancel ); 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 8a9a64dd1..62ac332ba 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -109,6 +109,28 @@ class ValidBuilder { const std::vector& status_; }; +// Separate template so the regular search compiles without any filter check. +template class FilteredValidBuilder { + public: + FilteredValidBuilder(const IDTranslator& translator, const 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, invalid_id); + bool valid = id != invalid_id && filter_(id); + return PredicatedSearchNeighbor(i, distance, valid); + } + + private: + const IDTranslator& translator_; + const Filter& filter_; +}; + namespace detail { template @@ -517,11 +539,7 @@ 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: one id pair per entry for each translation direction. metadata_bytes += 2 * translator_.size() * (sizeof(IDTranslator::external_id_type) + sizeof(IDTranslator::internal_id_type)); @@ -636,6 +654,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 +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 auto greedy_search_closure( + const Builder& builder, GreedySearchPrefetchParameters prefetch_parameters, const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) const { - return [&, prefetch_parameters]( - const auto& query, auto& accessor, auto& distance, auto& buffer - ) { + return [&, + prefetch_parameters, + builder](const auto& query, auto& accessor, auto& distance, auto& buffer) { // Perform the greedy search using the provided resources. greedy_search( graph_, @@ -695,7 +725,7 @@ class MutableVamanaIndex { distance, buffer, vamana::EntryPointInitializer{lib::as_const_span(entry_point_)}, - internal_search_builder(), + builder, prefetch_parameters, cancel ); @@ -717,17 +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 lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const Filter& filter = AcceptAll{} ) { threads::parallel_for( threadpool_, @@ -747,6 +780,12 @@ class MutableVamanaIndex { auto scratch = extensions::per_thread_batch_search_setup(data_, distance_); + // 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, @@ -754,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 ); } @@ -980,12 +1021,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 { diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index 96ffeaa06..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{}; @@ -585,9 +594,15 @@ void svs_invoke( ); // Copy back results. - for (size_t j = 0; j < num_neighbors; ++j) { + 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::worst_distance(distance); + } } } 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 4d4a47f09..9062bd25c 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,27 @@ 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} {} + + template + constexpr PredicatedSearchNeighbor operator()(I i, float distance) const { + bool valid = filter_(static_cast(i)); + return PredicatedSearchNeighbor(i, distance, valid); + } + + private: + const Filter& filter_; +}; + struct VamanaIndexParameters { // Members public: @@ -303,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. @@ -483,15 +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 auto greedy_search_closure( + const Builder& builder, GreedySearchPrefetchParameters prefetch_parameters, const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) const { - return [&, prefetch_parameters]( - const auto& query, auto& accessor, auto& distance, auto& buffer - ) { + return [&, + prefetch_parameters, + builder](const auto& query, auto& accessor, auto& distance, auto& buffer) { greedy_search( graph_, data_, @@ -500,10 +534,14 @@ class VamanaIndex { distance, buffer, vamana::EntryPointInitializer{lib::as_const_span(entry_point_)}, - internal_search_builder(), + builder, prefetch_parameters, cancel ); + if constexpr (requires { buffer.cleanup(); }) { + // Remove the invalid entries that remain in the buffer. + buffer.cleanup(); + } }; } @@ -532,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 ); } @@ -573,12 +613,13 @@ 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 lib::DefaultPredicate& cancel = lib::Returns(lib::Const()), + const Filter& filter = AcceptAll{} ) { threads::parallel_for( threadpool_, @@ -587,8 +628,13 @@ class VamanaIndex { // 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 @@ -612,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/dynamic_vamana.h b/include/svs/orchestrators/dynamic_vamana.h index 261278d7b..5e1f53a0e 100644 --- a/include/svs/orchestrators/dynamic_vamana.h +++ b/include/svs/orchestrators/dynamic_vamana.h @@ -609,6 +609,21 @@ 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. + /// 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 + void filtered_search( + QueryResultView results, + data::ConstSimpleDataView queries, + const VamanaSearchParameters& search_parameters, + const std::function& filter + ) { + 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..1625f256d 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(data, [&](const auto& view) { + svs::index::search_batch_into_with( + implementation_, result, view, search_parameters, cancel + ); + }); } // Data Interface @@ -191,6 +177,26 @@ 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(const AnonymousArray<2>& data, F&& f) const { + lib::match( + QueryTypes{}, + data.type(), + [&](lib::Type SVS_UNUSED(type)) { + const auto view = data::ConstSimpleDataView(data); + 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 5787e8a7a..d82014167 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 void filtered_search( + svs::QueryResultView results, + AnonymousArray<2> queries, + const index::vamana::VamanaSearchParameters& search_parameters, + const std::function& filter + ) = 0; }; template @@ -283,6 +292,19 @@ class VamanaImpl : public manager::ManagerImpl { svs::index::vamana::VamanaIndexParameters parameters() const override { return impl().parameters(); } + + void filtered_search( + svs::QueryResultView results, + AnonymousArray<2> queries, + const index::vamana::VamanaSearchParameters& search_parameters, + const std::function& filter + ) override { + this->dispatch_queries(queries, [&](const auto& view) { + impl().search( + results, view, search_parameters, lib::Returns(lib::Const()), filter + ); + }); + } }; ///// Forward declarations @@ -776,6 +798,21 @@ 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)``. + /// ``filter`` must be thread-safe and must not call into the same index. + template + void filtered_search( + QueryResultView results, + data::ConstSimpleDataView queries, + const VamanaSearchParameters& search_parameters, + const std::function& filter + ) { + impl_->filtered_search( + results, AnonymousArray<2>(queries), search_parameters, filter + ); + } + private: template < manager::QueryTypeDefinition QueryTypes, 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