diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index 1fc1a8980..fc6f11600 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -810,6 +810,10 @@ class MutableVamanaIndex { [&](const auto is, uint64_t /*tid*/) { for (auto i : is) { for (size_t j = 0, jmax = getsize<1>(ids); j < jmax; ++j) { + // Skip the invalid-neighbor marker written by a cancelled search. + if (ids.at(i, j) == no_external_id) { + continue; + } auto internal = lib::narrow_cast(ids.at(i, j)); ids.at(i, j) = unsafe_translate_internal_id(internal); } @@ -948,10 +952,13 @@ class MutableVamanaIndex { scratch.scratch, query, greedy_search_closure(scratch.prefetch_parameters, cancel), - *this + *this, + cancel ); } + // On cancel, see ``VamanaIndex::search``. Here a marker can also appear mid-row (an + // ID consolidated concurrently translates to the marker ID). template void search( QueryResultView results, @@ -997,13 +1004,10 @@ class MutableVamanaIndex { ); } - // Check if request to cancel the search - if (cancel()) { - return; - } - // After the search procedure, the indices in `results` are internal. // Perform one more pass to convert these to external ids. + // This also runs when the search was cancelled so that the partial results are + // external; slots holding the invalid-neighbor marker are left untouched. translate_to_external(results.indices()); } diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index 8a9a64dd1..f4afd0787 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -630,12 +630,18 @@ class MutableVamanaIndex { requires(std::tuple_size_v == 2) void translate_to_external(DenseArray& ids) { // N.B.: lib::narrow_cast should be valid because the origin of the IDs is internal. + constexpr size_t invalid_id = + type_traits::sentinel_v, std::less<>>.id(); threads::parallel_for( threadpool_, threads::StaticPartition{getsize<0>(ids)}, [&](const auto is, uint64_t /*tid*/) { for (auto i : is) { for (size_t j = 0, jmax = getsize<1>(ids); j < jmax; ++j) { + // Skip the invalid-neighbor marker written by a cancelled search. + if (ids.at(i, j) == invalid_id) { + continue; + } auto internal = lib::narrow_cast(ids.at(i, j)); ids.at(i, j) = translate_internal_id(internal); } @@ -718,10 +724,13 @@ class MutableVamanaIndex { scratch.scratch, query, greedy_search_closure(scratch.prefetch_parameters, cancel), - *this + *this, + cancel ); } + // If ``cancel`` returns ``true``, ``results`` holds the (external) neighbors found so + // far, followed by the invalid-neighbor marker. See ``VamanaIndex::search``. template void search( QueryResultView results, @@ -761,13 +770,10 @@ class MutableVamanaIndex { } ); - // Check if request to cancel the search - if (cancel()) { - return; - } - // After the search procedure, the indices in `results` are internal. // Perform one more pass to convert these to external ids. + // This also runs when the search was cancelled so that the partial results are + // external; slots holding the invalid-neighbor marker are left untouched. translate_to_external(results.indices()); } diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index 96ffeaa06..ece65b474 100644 --- a/include/svs/index/vamana/extensions.h +++ b/include/svs/index/vamana/extensions.h @@ -430,12 +430,18 @@ struct VamanaSingleSearchType { /// and the graph becomes sparsely connected. It's a corner case and should /// not happen frequently, but when it does, we may need to supplement the buffer /// with additional results. +/// +/// The top-up is skipped if ``cancel`` returns ``true``, so that a cancelled search keeps +/// exactly the candidates it found before being interrupted. 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 lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) { if (search_buffer.valid() < search_buffer.target_window() && - search_buffer.valid() < index.size()) { + search_buffer.valid() < index.size() && !cancel()) { search_buffer.sort(); for (auto external_id : index.external_ids()) { auto internal_id = index.translate_external_id(external_id); @@ -452,9 +458,9 @@ void check_and_supplement_search_buffer( /// Customization point object for processing single queries. inline constexpr VamanaSingleSearchType single_search{}; -/// In this function, cancel does not need to be called since search will call cancel -/// However, lvq requires cancel to be called to skip reranking -/// Here we have cancel to make the interface consistent with lvq +/// ``search`` polls ``cancel`` itself; after a cancel the buffer holds the candidates found +/// so far (a query that never started holds only its entry points). Compressed datasets +/// (LVQ, LeanVec) take the same argument and rerank those candidates. template < typename Data, typename SearchBuffer, @@ -472,16 +478,46 @@ SVS_FORCE_INLINE void svs_invoke( const Index& index, const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) { - // Check if request to cancel the search - if (cancel()) { - return; - } // Perform graph search. auto accessor = data::GetDatumAccessor(); search(query, accessor, distance, search_buffer); if constexpr (Index::needs_id_translation) { - check_and_supplement_search_buffer(index, search_buffer, query); + check_and_supplement_search_buffer(index, search_buffer, query, cancel); + } +} + +/// +/// @brief Copy the results of ``search_buffer`` into row ``query`` of ``result``. +/// +/// Normally all ``result.n_neighbors()`` entries are copied. If the buffer holds fewer +/// entries than that and ``cancel`` returns ``true``, only the entries found so far are +/// copied and the rest of the row is padded with the invalid-neighbor marker +/// (``type_traits::sentinel_v, Cmp>``: the largest ``I`` as the id and the +/// worst distance). +/// +template +void copy_results( + const SearchBuffer& search_buffer, + QueryResultView& result, + size_t query, + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) +) { + size_t num_neighbors = result.n_neighbors(); + size_t found = search_buffer.size(); + if (found < num_neighbors && cancel()) { + for (size_t j = 0; j < found; ++j) { + result.set(search_buffer[j], query, j); + } + constexpr auto marker = + type_traits::sentinel_v, typename SearchBuffer::compare_type>; + for (size_t j = found; j < num_neighbors; ++j) { + result.set(marker, query, j); + } + return; + } + for (size_t j = 0; j < num_neighbors; ++j) { + result.set(search_buffer[j], query, j); } } @@ -573,21 +609,16 @@ void svs_invoke( const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) { // Fallback implementation - size_t num_neighbors = result.n_neighbors(); for (auto i : thread_indices) { - // Check if request to cancel the search - if (cancel()) { - return; - } - // Perform search - results will be queued in the search buffer. + // Perform search - results will be queued in the search buffer. If ``cancel`` + // fires, the buffer holds what was found so far (only the entry points if the + // query never started) and ``copy_results`` pads the rest of the row. single_search( dataset, search_buffer, distance, queries.get_datum(i), search, index, cancel ); // Copy back results. - for (size_t j = 0; j < num_neighbors; ++j) { - result.set(search_buffer[j], i, j); - } + copy_results(search_buffer, result, i, cancel); } } diff --git a/include/svs/index/vamana/index.h b/include/svs/index/vamana/index.h index 4d4a47f09..b129aa7b8 100644 --- a/include/svs/index/vamana/index.h +++ b/include/svs/index/vamana/index.h @@ -533,7 +533,8 @@ class VamanaIndex { scratch.scratch, query, greedy_search_closure(scratch.prefetch_parameters, cancel), - *this + *this, + cancel ); } @@ -552,9 +553,16 @@ class VamanaIndex { /// @param search_parameters search parameters to use for the search. /// @param cancel A predicate called during the search to determine if the search should /// be cancelled. - // Return ``true`` if the search should be cancelled. This functor must implement - // ``bool operator()()``. Note: This predicate should be thread-safe as it can be - // called concurrently by different threads during the search. + /// Return ``true`` if the search should be cancelled. This functor must implement + /// ``bool operator()()``. Note: This predicate should be thread-safe as it can be + /// called concurrently by different threads during the search. Once it returns + /// ``true`` it must keep returning ``true`` for the rest of the call. + /// After a cancel, each row holds the neighbors found so far (nearest first, + /// final distances, external IDs), followed by the invalid-neighbor marker + /// ``type_traits::sentinel_v, Cmp>`` (max ID, worst distance). + /// Queries that had not started may hold only their entry points. Treat every + /// slot whose ID is the marker as empty: in the concurrent index a marker can + /// also appear mid-row. /// /// Perform a multi-threaded graph search over the index, overwriting the contents /// of ``result`` with the results of search. diff --git a/include/svs/index/vamana/iterator.h b/include/svs/index/vamana/iterator.h index 7bf3a9b69..f379d2caf 100644 --- a/include/svs/index/vamana/iterator.h +++ b/include/svs/index/vamana/iterator.h @@ -309,7 +309,8 @@ class BatchIteratorBase { scratchspace_.scratch, lib::as_const_span(query_), search_closure, - *parent_ + *parent_, + cancel ); }); diff --git a/include/svs/orchestrators/manager.h b/include/svs/orchestrators/manager.h index b3f4d33d2..5aeb533ff 100644 --- a/include/svs/orchestrators/manager.h +++ b/include/svs/orchestrators/manager.h @@ -72,8 +72,10 @@ template class ManagerInterface : public IFace { virtual search_parameters_type get_search_parameters() const = 0; virtual void set_search_parameters(const search_parameters_type&) = 0; - // Cancel callback is not thread safe and can be called multiple times - // Cancel does not return the partial results + // Cancel callback must be thread-safe and can be called multiple times + // Vamana: after a cancel, `results` holds the neighbors found so far, padded with the + // invalid-neighbor marker (see VamanaIndex::search). Other index types: contents of + // `results` are unspecified after a cancel. // Cancel is not templated as this is a pure virtual function virtual void search( svs::QueryResultView results, diff --git a/tests/svs/index/vamana/dynamic_index.cpp b/tests/svs/index/vamana/dynamic_index.cpp index 94daddcf1..ca5e70cc5 100644 --- a/tests/svs/index/vamana/dynamic_index.cpp +++ b/tests/svs/index/vamana/dynamic_index.cpp @@ -17,12 +17,15 @@ // header under test. #include "svs/index/vamana/dynamic_index.h" #include "svs/index/vamana/consolidate.h" +#include "svs/index/vamana/index.h" // stl #include +#include #include #include #include +#include #include #include #include @@ -464,3 +467,109 @@ 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("Vamana Cancelled Search", "[graph_index][dynamic_index][cancel]") { + using Distance = svs::distance::DistanceL2; + const size_t num_neighbors = 10; + auto data = test_dataset::data_f32(); + auto queries = test_dataset::queries(); + auto sp = svs::index::vamana::VamanaSearchParameters{}; + sp.buffer_config_ = svs::index::vamana::SearchBufferConfig{20}; + svs::index::vamana::VamanaBuildParameters parameters{1.2, 64, 10, 20, 10, true}; + + // ``to_row`` maps a returned ID to the row of ``data`` holding its vector; ``live`` + // says whether that row is still in the index. + auto check = [&](auto& index, auto to_row, auto live) { + auto exact = [&](size_t id, size_t q) { + float sum = 0; + for (size_t d = 0; d < queries.dimensions(); ++d) { + float diff = data.get_datum(to_row(id))[d] - queries.get_datum(q)[d]; + sum += diff * diff; + } + return sum; + }; + const size_t marker = std::numeric_limits::max(); + auto search = [&](auto cancel) { + svs::QueryResult results{queries.size(), num_neighbors}; + index.search(results.view(), queries.cview(), sp, cancel); + return results; + }; + + // A predicate that never fires gives the same results as no predicate. + svs::QueryResult reference{queries.size(), num_neighbors}; + index.search(reference.view(), queries.cview(), sp); + auto never = search(svs::lib::Returns(svs::lib::Const())); + for (size_t q = 0; q < queries.size(); ++q) { + for (size_t j = 0; j < num_neighbors; ++j) { + CATCH_REQUIRE(reference.index(q, j) != marker); + CATCH_REQUIRE(live(to_row(reference.index(q, j)))); + CATCH_REQUIRE(never.index(q, j) == reference.index(q, j)); + CATCH_REQUIRE(never.distance(q, j) == reference.distance(q, j)); + } + } + + // Fire after a number of polls: each row is a prefix of live neighbors (nearest + // first, exact distances), followed only by markers. + std::atomic polls{0}; + auto results = search([&]() { return polls.fetch_add(1) >= 500; }); + size_t partial = 0; + for (size_t q = 0; q < queries.size(); ++q) { + size_t valid = 0; + while (valid < num_neighbors && results.index(q, valid) != marker) { + size_t id = results.index(q, valid); + CATCH_REQUIRE(live(to_row(id))); + CATCH_REQUIRE(results.distance(q, valid) == Catch::Approx(exact(id, q))); + CATCH_REQUIRE( + (valid == 0 || + results.distance(q, valid - 1) <= results.distance(q, valid)) + ); + ++valid; + } + for (size_t j = valid; j < num_neighbors; ++j) { + CATCH_REQUIRE(results.index(q, j) == marker); + } + partial += valid < num_neighbors; + } + CATCH_REQUIRE(partial > 0); + }; + + CATCH_SECTION("Static index") { + auto index = svs::index::vamana::auto_build(parameters, data, Distance(), 2); + check( + index, [](size_t id) { return id; }, [](size_t) { return true; } + ); + } + + CATCH_SECTION("Dynamic index with deletions and external IDs") { + std::vector ids(data.size()); + for (size_t i = 0; i < ids.size(); ++i) { + ids[i] = 1000 + 3 * i; + } + auto index = svs::index::vamana::MutableVamanaIndex( + parameters, test_dataset::data_blocked_f32(), ids, Distance(), 2 + ); + std::vector deleted; + for (size_t i = 0; i < ids.size(); i += 7) { + deleted.push_back(ids[i]); + } + // Row `i` has external ID `1000 + 3 * i`; delete every 7th row. + index.delete_entries(deleted); + check( + index, + [](size_t id) { return (id - 1000) / 3; }, + [](size_t row) { return row % 7 != 0; } + ); + + // The batch iterator forwards ``cancel`` too: a search cancelled before it starts + // is not topped up from the live IDs, while an uncancelled one fills the batch. + const size_t batch = 50; + auto query_datum = queries.get_datum(0); + auto query = std::span(query_datum.data(), query_datum.size()); + auto full = index.make_batch_iterator(query); + full.next(batch); + CATCH_REQUIRE(full.size() == batch); + auto cancelled = index.make_batch_iterator(query); + cancelled.next(batch, []() { return true; }); + CATCH_REQUIRE(cancelled.size() < batch); + } +}