From 1dda273187c6032b875e380e89663068f92777ef Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Tue, 24 Nov 2026 13:37:12 -0800 Subject: [PATCH 1/5] Return partial results when a Vamana search is cancelled On cancel, the batch search now writes the neighbors each query found so far, padded with the invalid-neighbor sentinel, instead of leaving stale or uninitialized entries. Dynamic indexes still translate IDs to external on cancel, the top-up of short search buffers is skipped after a cancel, and the single-query search overloads forward cancel to single_search. Non-cancelled searches are unchanged. --- include/svs/concurrent/dynamic_index.h | 16 +- include/svs/index/vamana/dynamic_index.h | 18 +- include/svs/index/vamana/extensions.h | 77 ++- include/svs/index/vamana/index.h | 16 +- include/svs/orchestrators/manager.h | 4 +- tests/CMakeLists.txt | 1 + tests/svs/index/vamana/search_cancel.cpp | 593 +++++++++++++++++++++++ 7 files changed, 693 insertions(+), 32 deletions(-) create mode 100644 tests/svs/index/vamana/search_cancel.cpp 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..93220e6fa 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,10 @@ 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 +/// If ``cancel`` returns ``true`` before the search starts, the search buffer is cleared +/// and nothing is searched. Otherwise ``search`` polls ``cancel`` itself and leaves the +/// candidates found so far in the buffer. Compressed datasets (LVQ, LeanVec) take the same +/// argument; they rerank those candidates even after a cancel. template < typename Data, typename SearchBuffer, @@ -474,6 +481,8 @@ SVS_FORCE_INLINE void svs_invoke( ) { // Check if request to cancel the search if (cancel()) { + // Nothing was searched: drop stale candidates from a previous query. + search_buffer.clear(); return; } // Perform graph search. @@ -481,7 +490,50 @@ 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); + check_and_supplement_search_buffer(index, search_buffer, query, cancel); + } +} + +/// +/// @brief Pad ``result[query, first:]`` with the invalid-neighbor marker. +/// +/// The marker is ``type_traits::sentinel_v, Cmp>``: the largest value of ``I`` +/// as the id and the worst possible distance with respect to ``Cmp``. It marks result +/// slots that were not filled because the search was cancelled. +/// +template +void pad_invalid_results(QueryResultView& result, size_t query, size_t first) { + constexpr auto marker = type_traits::sentinel_v, Cmp>; + for (size_t j = first, jmax = result.n_neighbors(); j < jmax; ++j) { + result.set(marker, query, j); + } +} + +/// +/// @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. +/// +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); + } + pad_invalid_results(result, query, found); + return; + } + for (size_t j = 0; j < num_neighbors; ++j) { + result.set(search_buffer[j], query, j); } } @@ -573,21 +625,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 (empty if the query never + // started) and ``copy_results`` pads the rest of the row with the marker. 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..7bbf2c1b3 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 never started hold only markers. 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/orchestrators/manager.h b/include/svs/orchestrators/manager.h index b3f4d33d2..fdccdf654 100644 --- a/include/svs/orchestrators/manager.h +++ b/include/svs/orchestrators/manager.h @@ -73,7 +73,9 @@ template class ManagerInterface : public IFace { 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 + // 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/CMakeLists.txt b/tests/CMakeLists.txt index 88a9ae412..dd24d9463 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -137,6 +137,7 @@ set(TEST_SOURCES ${TEST_DIR}/svs/index/vamana/index.cpp ${TEST_DIR}/svs/index/vamana/prune.cpp ${TEST_DIR}/svs/index/vamana/search_buffer.cpp + ${TEST_DIR}/svs/index/vamana/search_cancel.cpp ${TEST_DIR}/svs/index/vamana/search_parameters.cpp ${TEST_DIR}/svs/index/vamana/vamana_build.cpp #${TEST_DIR}/svs/index/vamana/iterator_schedule.cpp diff --git a/tests/svs/index/vamana/search_cancel.cpp b/tests/svs/index/vamana/search_cancel.cpp new file mode 100644 index 000000000..b18523f6f --- /dev/null +++ b/tests/svs/index/vamana/search_cancel.cpp @@ -0,0 +1,593 @@ +/* + * 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. + */ + +// Tests for the partial results returned by a cancelled Vamana search. + +// header under test +#include "svs/index/vamana/extensions.h" + +// svs +#include "svs/concurrent/dynamic_index.h" +#include "svs/core/distance.h" +#include "svs/index/vamana/dynamic_index.h" +#include "svs/orchestrators/vamana.h" + +// stl +#include +#include +#include +#include +#include +#include +#include +#include + +// catch2 +#include "catch2/catch_approx.hpp" +#include "catch2/catch_test_macros.hpp" + +// tests +#include "tests/utils/test_dataset.h" +#include "tests/utils/utils.h" +#include "tests/utils/vamana_reference.h" + +namespace { + +namespace cc = svs::index::vamana::concurrent; + +constexpr size_t NUM_NEIGHBORS = 10; +constexpr size_t SEARCH_WINDOW = 20; +constexpr size_t MARKER_ID = std::numeric_limits::max(); + +// External ID of the vector stored in row `i` of the base dataset. Deliberately +// non-contiguous so that internal and external IDs cannot be confused. +size_t external_id(size_t i) { return 1000 + 3 * i; } +size_t row_of(size_t external) { return (external - 1000) / 3; } + +// A predicate that returns `false` for the first `allowed` polls and `true` afterwards. +struct CountingCancel { + explicit CountingCancel(size_t allowed) + : allowed_{allowed} {} + bool operator()() { return polls_.fetch_add(1) >= allowed_; } + size_t allowed_; + std::atomic polls_{0}; +}; + +svs::index::vamana::VamanaSearchParameters search_parameters() { + svs::index::vamana::VamanaSearchParameters sp{}; + sp.buffer_config_ = svs::index::vamana::SearchBufferConfig{SEARCH_WINDOW}; + return sp; +} + +// Describes a metric: how to compute the exact distance of a result, the distance stored +// in the invalid-neighbor marker, and whether the best neighbor has the smallest distance. +struct Metric { + std::function, std::span)> distance; + float marker_distance; + bool smaller_is_better; +}; + +float dot(std::span a, std::span b) { + double sum = 0; + for (size_t i = 0; i < a.size(); ++i) { + sum += double(a[i]) * double(b[i]); + } + return float(sum); +} + +// The marker distance is the worst possible one: the largest float for L2 and the lowest +// float for similarity metrics. +Metric l2_metric() { + return Metric{ + [](auto a, auto b) { + double sum = 0; + for (size_t i = 0; i < a.size(); ++i) { + double d = double(a[i]) - double(b[i]); + sum += d * d; + } + return float(sum); + }, + std::numeric_limits::max(), + true}; +} + +Metric ip_metric() { return Metric{dot, std::numeric_limits::lowest(), false}; } + +Metric cosine_metric() { + return Metric{ + [](auto a, auto b) { return dot(a, b) / std::sqrt(dot(a, a) * dot(b, b)); }, + std::numeric_limits::lowest(), + false}; +} + +// Number of valid entries in row `q`: the length of the prefix without the marker. +// Requires that the marker only appears as a suffix. +size_t check_row( + const svs::QueryResult& results, + size_t q, + const svs::data::SimpleData& base, + const svs::data::SimpleData& queries, + const std::function& is_live, + const std::function& to_row, + const Metric& metric +) { + size_t valid = 0; + while (valid < results.n_neighbors() && results.index(q, valid) != MARKER_ID) { + ++valid; + } + float previous = metric.smaller_is_better ? -std::numeric_limits::infinity() + : std::numeric_limits::infinity(); + for (size_t j = 0; j < results.n_neighbors(); ++j) { + size_t id = results.index(q, j); + float distance = results.distance(q, j); + if (j < valid) { + // Valid entry: live ID, exact distance, sorted nearest first. + CATCH_REQUIRE(is_live(id)); + auto expected = + metric.distance(base.get_datum(to_row(id)), queries.get_datum(q)); + CATCH_REQUIRE(distance == Catch::Approx(expected).epsilon(1e-4)); + CATCH_REQUIRE( + (metric.smaller_is_better ? distance >= previous : distance <= previous) + ); + previous = distance; + } else { + // Marker entries only after the valid ones. + CATCH_REQUIRE(id == MARKER_ID); + CATCH_REQUIRE(distance == metric.marker_distance); + } + } + return valid; +} + +using SearchFn = + std::function, const svs::lib::DefaultPredicate&)>; + +// `search(results, cancel)` performs a batch search with the index under test, returning +// `k` neighbors per query. +void check_cancel_semantics( + const SearchFn& search, + const svs::data::SimpleData& base, + const svs::data::SimpleData& queries, + const std::function& is_live, + const std::function& to_row, + bool single_thread, + const Metric& metric = l2_metric(), + size_t k = NUM_NEIGHBORS +) { + auto make_results = [&]() { return svs::QueryResult(queries.size(), k); }; + auto check = [&](const svs::QueryResult& results, size_t q) { + return check_row(results, q, base, queries, is_live, to_row, metric); + }; + + // (d) A predicate that never fires: identical to searching without a predicate. + { + auto expected = make_results(); + search(expected.view(), svs::lib::Returns(svs::lib::Const())); + auto actual = make_results(); + CountingCancel never{std::numeric_limits::max()}; + search(actual.view(), std::ref(never)); + CATCH_REQUIRE(never.polls_.load() > 0); + for (size_t q = 0; q < queries.size(); ++q) { + for (size_t j = 0; j < k; ++j) { + CATCH_REQUIRE(actual.index(q, j) == expected.index(q, j)); + CATCH_REQUIRE(actual.distance(q, j) == expected.distance(q, j)); + } + } + } + + // (a) Cancelled before anything started: every slot of every row is the marker. + { + auto results = make_results(); + // Fill with junk to make sure the search overwrites everything. + std::fill(results.indices().begin(), results.indices().end(), size_t{7}); + std::fill(results.distances().begin(), results.distances().end(), -1.0f); + CountingCancel cancel{0}; + search(results.view(), std::ref(cancel)); + for (size_t q = 0; q < queries.size(); ++q) { + for (size_t j = 0; j < k; ++j) { + CATCH_REQUIRE(results.index(q, j) == MARKER_ID); + CATCH_REQUIRE(results.distance(q, j) == metric.marker_distance); + } + } + } + + // (b), (c) Cancelled at various points. Rows must be a sorted prefix of live, + // exactly-measured neighbors followed by markers. + size_t partial_rows = 0; + size_t rows_with_neighbors = 0; + for (size_t allowed : {1, 2, 3, 5, 20, 100, 400, 1500, 6000}) { + auto results = make_results(); + std::fill(results.indices().begin(), results.indices().end(), size_t{7}); + std::fill(results.distances().begin(), results.distances().end(), -1.0f); + CountingCancel cancel{allowed}; + search(results.view(), std::ref(cancel)); + for (size_t q = 0; q < queries.size(); ++q) { + size_t valid = check(results, q); + rows_with_neighbors += (valid > 0); + partial_rows += (valid > 0 && valid < k); + } + } + CATCH_REQUIRE(rows_with_neighbors > 0); + if (single_thread) { + // A deterministic interruption: with one thread, the first query's single_search + // poll passes and the first visited-node poll fires. The row then holds only what + // initialization put into the search buffer. Later queries never start. + auto results = make_results(); + CountingCancel cancel{1}; + search(results.view(), std::ref(cancel)); + size_t valid = check(results, 0); + CATCH_REQUIRE(valid >= 1); + CATCH_REQUIRE(valid < k); + for (size_t q = 1; q < queries.size(); ++q) { + CATCH_REQUIRE(check(results, q) == 0); + } + CATCH_REQUIRE(partial_rows > 0); + } +} + +// Delete every fourth vector. +std::vector ids_to_delete(size_t n) { + std::vector ids; + for (size_t i = 0; i < n; i += 4) { + ids.push_back(external_id(i)); + } + return ids; +} + +// Delete all but every twentieth vector, so that few live vectors remain (95% deleted). +std::vector ids_to_delete_most(size_t n) { + std::vector ids; + for (size_t i = 0; i < n; ++i) { + if (i % 20 != 0) { + ids.push_back(external_id(i)); + } + } + return ids; +} + +std::vector all_external_ids(size_t n) { + std::vector ids(n); + for (size_t i = 0; i < n; ++i) { + ids[i] = external_id(i); + } + return ids; +} + +// Whether `id` is an external ID of a live vector of the dynamic test indexes. +std::function +is_live_external(size_t n, const std::unordered_set& deleted) { + return [n, &deleted](size_t id) { + return id >= 1000 && (id - 1000) % 3 == 0 && row_of(id) < n && + !deleted.contains(id); + }; +} + +// Static index test for any distance functor. +template +void check_static(const Metric& metric, size_t k = NUM_NEIGHBORS) { + auto base = svs::data::SimpleData::load(test_dataset::data_svs_file()); + auto queries = test_dataset::queries(); + // MIP and cosine require alpha <= 1. + svs::index::vamana::VamanaBuildParameters parameters{ + metric.smaller_is_better ? 1.2f : 0.95f, 64, 10, 20, 10, true}; + + for (size_t num_threads : {1, 3}) { + CATCH_SECTION("Threads: " + std::to_string(num_threads)) { + auto index = svs::Vamana::build( + parameters, + svs::data::SimpleData::load(test_dataset::data_svs_file()), + Distance(), + num_threads + ); + auto sp = search_parameters(); + check_cancel_semantics( + [&](auto results, const auto& cancel) { + index.search(results, queries.cview(), sp, cancel); + }, + base, + queries, + [&](size_t id) { return id < base.size(); }, + [](size_t id) { return id; }, + num_threads == 1, + metric, + k + ); + } + } +} + +// Checks of a dynamic index in which 95% of the vectors have been deleted. The search +// buffer then often holds fewer candidates than the window, which is when an uncancelled +// search tops it up with live vectors found outside the graph traversal. A cancelled +// search must not do that. +void check_mostly_deleted( + const SearchFn& search, + const svs::data::SimpleData& base, + const svs::data::SimpleData& queries, + const std::function& is_live, + bool single_thread +) { + const Metric metric = l2_metric(); + auto make_results = [&]() { + return svs::QueryResult(queries.size(), NUM_NEIGHBORS); + }; + + // The uncancelled search returns a full row of live IDs (thanks to the top-up). + { + auto results = make_results(); + search(results.view(), svs::lib::Returns(svs::lib::Const())); + for (size_t q = 0; q < queries.size(); ++q) { + CATCH_REQUIRE( + check_row(results, q, base, queries, is_live, row_of, metric) == + NUM_NEIGHBORS + ); + } + } + + // Cancelled searches only ever return live IDs, and rows may be incomplete. + size_t incomplete_rows = 0; + for (size_t allowed : {1, 2, 3, 5, 20, 100, 400, 1500}) { + auto results = make_results(); + CountingCancel cancel{allowed}; + search(results.view(), std::ref(cancel)); + for (size_t q = 0; q < queries.size(); ++q) { + incomplete_rows += + (check_row(results, q, base, queries, is_live, row_of, metric) < + NUM_NEIGHBORS); + } + } + CATCH_REQUIRE(incomplete_rows > 0); + + if (single_thread) { + // Interrupted right after initialization. The buffer then holds at most the entry + // point, so a full row can only come from a top-up, which must not happen. + auto results = make_results(); + CountingCancel cancel{1}; + search(results.view(), std::ref(cancel)); + CATCH_REQUIRE( + check_row(results, 0, base, queries, is_live, row_of, metric) < NUM_NEIGHBORS + ); + for (size_t q = 1; q < queries.size(); ++q) { + CATCH_REQUIRE( + check_row(results, q, base, queries, is_live, row_of, metric) == 0 + ); + } + } +} + +// Single-query search with caller-provided scratch space. `external` converts an internal +// ID in the search buffer to the vector's row in the base dataset. +template +void check_single_query( + Index& index, + const svs::data::SimpleData& base, + const svs::data::SimpleData& queries, + const std::function&)>& is_live, + const std::function&)>& to_row +) { + auto sp = search_parameters(); + auto scratch = index.scratchspace(sp); + auto metric = l2_metric(); + auto query = queries.get_datum(0); + + // Uncancelled: a full window of live candidates. + index.search(query, scratch); + const size_t full_size = scratch.buffer.size(); + CATCH_REQUIRE(full_size >= NUM_NEIGHBORS); + + // A predicate that never fires leaves the same candidates. + { + std::vector> expected; + for (const auto& n : scratch.buffer) { + expected.emplace_back(n.id(), n.distance()); + } + CountingCancel never{std::numeric_limits::max()}; + index.search(query, scratch, std::ref(never)); + CATCH_REQUIRE(never.polls_.load() > 0); + CATCH_REQUIRE(scratch.buffer.size() == expected.size()); + for (size_t j = 0; j < expected.size(); ++j) { + CATCH_REQUIRE(scratch.buffer[j].id() == expected[j].first); + CATCH_REQUIRE(scratch.buffer[j].distance() == expected[j].second); + } + } + + // Cancelled before the search starts: stale candidates are dropped, nothing is added + // (in particular no top-up). + { + CountingCancel cancel{0}; + index.search(query, scratch, std::ref(cancel)); + CATCH_REQUIRE(scratch.buffer.size() == 0); + } + + // Cancelled right after initialization: a partial, valid buffer without top-up. + { + CountingCancel cancel{1}; + index.search(query, scratch, std::ref(cancel)); + CATCH_REQUIRE(scratch.buffer.size() >= 1); + CATCH_REQUIRE(scratch.buffer.size() < full_size); + CATCH_REQUIRE(scratch.buffer.size() < SEARCH_WINDOW); + for (const auto& n : scratch.buffer) { + CATCH_REQUIRE(is_live(n)); + auto expected = metric.distance(base.get_datum(to_row(n)), query); + CATCH_REQUIRE(n.distance() == Catch::Approx(expected).epsilon(1e-4)); + } + } +} + +} // namespace + +CATCH_TEST_CASE("Static Vamana Cancelled Search", "[vamana][cancel]") { + check_static(l2_metric()); +} + +CATCH_TEST_CASE("Static Vamana Cancelled Search IP", "[vamana][cancel]") { + check_static(ip_metric()); +} + +CATCH_TEST_CASE("Static Vamana Cancelled Search Cosine", "[vamana][cancel]") { + check_static(cosine_metric()); +} + +CATCH_TEST_CASE("Static Vamana Cancelled Search k > window", "[vamana][cancel]") { + // More neighbors than the search window: the buffer is enlarged to `k`. + static_assert(40 > SEARCH_WINDOW); + check_static(l2_metric(), 40); +} + +CATCH_TEST_CASE("Dynamic Vamana Cancelled Search", "[vamana][dynamic_index][cancel]") { + using Distance = svs::distance::DistanceL2; + auto base = svs::data::SimpleData::load(test_dataset::data_svs_file()); + auto queries = test_dataset::queries(); + auto ids = all_external_ids(base.size()); + svs::index::vamana::VamanaBuildParameters parameters{1.2, 64, 10, 20, 10, true}; + auto index = svs::index::vamana::MutableVamanaIndex( + parameters, test_dataset::data_blocked_f32(), ids, Distance(), 1 + ); + auto deleted = ids_to_delete(base.size()); + index.delete_entries(deleted); + std::unordered_set deleted_set(deleted.begin(), deleted.end()); + + auto sp = search_parameters(); + for (size_t num_threads : {1, 3}) { + CATCH_SECTION("Threads: " + std::to_string(num_threads)) { + index.set_threadpool(svs::threads::DefaultThreadPool(num_threads)); + auto search = [&](auto results, const auto& cancel) { + index.search(results, queries.cview(), sp, cancel); + }; + auto is_live = is_live_external(base.size(), deleted_set); + check_cancel_semantics( + search, base, queries, is_live, row_of, num_threads == 1 + ); + // k larger than the search window. + check_cancel_semantics( + search, base, queries, is_live, row_of, num_threads == 1, l2_metric(), 40 + ); + } + } +} + +CATCH_TEST_CASE( + "Dynamic Vamana Cancelled Search, Mostly Deleted", "[vamana][dynamic_index][cancel]" +) { + using Distance = svs::distance::DistanceL2; + auto base = svs::data::SimpleData::load(test_dataset::data_svs_file()); + auto queries = test_dataset::queries(); + auto ids = all_external_ids(base.size()); + svs::index::vamana::VamanaBuildParameters parameters{1.2, 64, 10, 20, 10, true}; + auto index = svs::index::vamana::MutableVamanaIndex( + parameters, test_dataset::data_blocked_f32(), ids, Distance(), 1 + ); + auto deleted = ids_to_delete_most(base.size()); + index.delete_entries(deleted); + std::unordered_set deleted_set(deleted.begin(), deleted.end()); + CATCH_REQUIRE(index.size() > 2 * SEARCH_WINDOW); + + auto sp = search_parameters(); + for (size_t num_threads : {1, 3}) { + CATCH_SECTION("Threads: " + std::to_string(num_threads)) { + index.set_threadpool(svs::threads::DefaultThreadPool(num_threads)); + check_mostly_deleted( + [&](auto results, const auto& cancel) { + index.search(results, queries.cview(), sp, cancel); + }, + base, + queries, + is_live_external(base.size(), deleted_set), + num_threads == 1 + ); + } + } +} + +CATCH_TEST_CASE("Single Query Cancelled Search", "[vamana][dynamic_index][cancel]") { + auto base = svs::data::SimpleData::load(test_dataset::data_svs_file()); + auto queries = test_dataset::queries(); + + CATCH_SECTION("Static") { + auto index = test_dataset::vamana::load_test_index(svs::distance::DistanceL2()); + check_single_query( + index, + base, + queries, + [&](const auto& n) { return n.id() < base.size(); }, + [](const auto& n) -> size_t { return n.id(); } + ); + } + + CATCH_SECTION("Dynamic") { + auto ids = all_external_ids(base.size()); + svs::index::vamana::VamanaBuildParameters parameters{1.2, 64, 10, 20, 10, true}; + auto index = svs::index::vamana::MutableVamanaIndex( + parameters, + test_dataset::data_blocked_f32(), + ids, + svs::distance::DistanceL2(), + 1 + ); + // A buffer holding only the entry point would be topped up if not cancelled. + auto deleted = ids_to_delete(base.size()); + index.delete_entries(deleted); + std::unordered_set deleted_set(deleted.begin(), deleted.end()); + auto is_live = is_live_external(base.size(), deleted_set); + // Buffer entries hold internal IDs. + check_single_query( + index, + base, + queries, + [&](const auto& n) { return is_live(index.translate_internal_id(n.id())); }, + [&](const auto& n) -> size_t { + return row_of(index.translate_internal_id(n.id())); + } + ); + } +} + +CATCH_TEST_CASE( + "Concurrent Vamana Cancelled Search", "[vamana][concurrent][dynamic_index][cancel]" +) { + using Distance = svs::distance::DistanceL2; + auto base = svs::data::SimpleData::load(test_dataset::data_svs_file()); + auto queries = test_dataset::queries(); + auto ids = all_external_ids(base.size()); + svs::index::vamana::VamanaBuildParameters parameters{1.2, 64, 10, 20, 10, true}; + auto index = cc::MutableVamanaIndex( + parameters, + cc::SegmentedBlockedData::load(test_dataset::data_svs_file()), + ids, + Distance(), + 1 + ); + auto deleted = ids_to_delete(base.size()); + index.delete_entries(deleted); + std::unordered_set deleted_set(deleted.begin(), deleted.end()); + + auto sp = search_parameters(); + for (size_t num_threads : {1, 3}) { + CATCH_SECTION("Threads: " + std::to_string(num_threads)) { + index.set_threadpool(svs::threads::DefaultThreadPool(num_threads)); + check_cancel_semantics( + [&](auto results, const auto& cancel) { + index.search(results, queries.cview(), sp, cancel); + }, + base, + queries, + is_live_external(base.size(), deleted_set), + row_of, + num_threads == 1 + ); + } + } +} From 7c47ef9bc1d58838d7f7916a34da30031ca7c99f Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Wed, 25 Nov 2026 14:30:05 -0800 Subject: [PATCH 2/5] Simplify cancel handling and move tests into existing files --- include/svs/index/vamana/extensions.h | 38 +- tests/CMakeLists.txt | 1 - tests/svs/index/vamana/dynamic_index.cpp | 93 ++++ tests/svs/index/vamana/search_cancel.cpp | 593 ----------------------- 4 files changed, 104 insertions(+), 621 deletions(-) delete mode 100644 tests/svs/index/vamana/search_cancel.cpp diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index 93220e6fa..f80878529 100644 --- a/include/svs/index/vamana/extensions.h +++ b/include/svs/index/vamana/extensions.h @@ -458,10 +458,9 @@ void check_and_supplement_search_buffer( /// Customization point object for processing single queries. inline constexpr VamanaSingleSearchType single_search{}; -/// If ``cancel`` returns ``true`` before the search starts, the search buffer is cleared -/// and nothing is searched. Otherwise ``search`` polls ``cancel`` itself and leaves the -/// candidates found so far in the buffer. Compressed datasets (LVQ, LeanVec) take the same -/// argument; they rerank those candidates even after a cancel. +/// ``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, @@ -479,12 +478,6 @@ 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()) { - // Nothing was searched: drop stale candidates from a previous query. - search_buffer.clear(); - return; - } // Perform graph search. auto accessor = data::GetDatumAccessor(); search(query, accessor, distance, search_buffer); @@ -494,27 +487,14 @@ SVS_FORCE_INLINE void svs_invoke( } } -/// -/// @brief Pad ``result[query, first:]`` with the invalid-neighbor marker. -/// -/// The marker is ``type_traits::sentinel_v, Cmp>``: the largest value of ``I`` -/// as the id and the worst possible distance with respect to ``Cmp``. It marks result -/// slots that were not filled because the search was cancelled. -/// -template -void pad_invalid_results(QueryResultView& result, size_t query, size_t first) { - constexpr auto marker = type_traits::sentinel_v, Cmp>; - for (size_t j = first, jmax = result.n_neighbors(); j < jmax; ++j) { - result.set(marker, query, j); - } -} - /// /// @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. +/// 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( @@ -529,7 +509,11 @@ void copy_results( for (size_t j = 0; j < found; ++j) { result.set(search_buffer[j], query, j); } - pad_invalid_results(result, query, found); + 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) { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index dd24d9463..88a9ae412 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -137,7 +137,6 @@ set(TEST_SOURCES ${TEST_DIR}/svs/index/vamana/index.cpp ${TEST_DIR}/svs/index/vamana/prune.cpp ${TEST_DIR}/svs/index/vamana/search_buffer.cpp - ${TEST_DIR}/svs/index/vamana/search_cancel.cpp ${TEST_DIR}/svs/index/vamana/search_parameters.cpp ${TEST_DIR}/svs/index/vamana/vamana_build.cpp #${TEST_DIR}/svs/index/vamana/iterator_schedule.cpp diff --git a/tests/svs/index/vamana/dynamic_index.cpp b/tests/svs/index/vamana/dynamic_index.cpp index 94daddcf1..6a5f81768 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,93 @@ 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. + auto reference = 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)))); + } + } + + // 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; } + ); + } +} diff --git a/tests/svs/index/vamana/search_cancel.cpp b/tests/svs/index/vamana/search_cancel.cpp deleted file mode 100644 index b18523f6f..000000000 --- a/tests/svs/index/vamana/search_cancel.cpp +++ /dev/null @@ -1,593 +0,0 @@ -/* - * 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. - */ - -// Tests for the partial results returned by a cancelled Vamana search. - -// header under test -#include "svs/index/vamana/extensions.h" - -// svs -#include "svs/concurrent/dynamic_index.h" -#include "svs/core/distance.h" -#include "svs/index/vamana/dynamic_index.h" -#include "svs/orchestrators/vamana.h" - -// stl -#include -#include -#include -#include -#include -#include -#include -#include - -// catch2 -#include "catch2/catch_approx.hpp" -#include "catch2/catch_test_macros.hpp" - -// tests -#include "tests/utils/test_dataset.h" -#include "tests/utils/utils.h" -#include "tests/utils/vamana_reference.h" - -namespace { - -namespace cc = svs::index::vamana::concurrent; - -constexpr size_t NUM_NEIGHBORS = 10; -constexpr size_t SEARCH_WINDOW = 20; -constexpr size_t MARKER_ID = std::numeric_limits::max(); - -// External ID of the vector stored in row `i` of the base dataset. Deliberately -// non-contiguous so that internal and external IDs cannot be confused. -size_t external_id(size_t i) { return 1000 + 3 * i; } -size_t row_of(size_t external) { return (external - 1000) / 3; } - -// A predicate that returns `false` for the first `allowed` polls and `true` afterwards. -struct CountingCancel { - explicit CountingCancel(size_t allowed) - : allowed_{allowed} {} - bool operator()() { return polls_.fetch_add(1) >= allowed_; } - size_t allowed_; - std::atomic polls_{0}; -}; - -svs::index::vamana::VamanaSearchParameters search_parameters() { - svs::index::vamana::VamanaSearchParameters sp{}; - sp.buffer_config_ = svs::index::vamana::SearchBufferConfig{SEARCH_WINDOW}; - return sp; -} - -// Describes a metric: how to compute the exact distance of a result, the distance stored -// in the invalid-neighbor marker, and whether the best neighbor has the smallest distance. -struct Metric { - std::function, std::span)> distance; - float marker_distance; - bool smaller_is_better; -}; - -float dot(std::span a, std::span b) { - double sum = 0; - for (size_t i = 0; i < a.size(); ++i) { - sum += double(a[i]) * double(b[i]); - } - return float(sum); -} - -// The marker distance is the worst possible one: the largest float for L2 and the lowest -// float for similarity metrics. -Metric l2_metric() { - return Metric{ - [](auto a, auto b) { - double sum = 0; - for (size_t i = 0; i < a.size(); ++i) { - double d = double(a[i]) - double(b[i]); - sum += d * d; - } - return float(sum); - }, - std::numeric_limits::max(), - true}; -} - -Metric ip_metric() { return Metric{dot, std::numeric_limits::lowest(), false}; } - -Metric cosine_metric() { - return Metric{ - [](auto a, auto b) { return dot(a, b) / std::sqrt(dot(a, a) * dot(b, b)); }, - std::numeric_limits::lowest(), - false}; -} - -// Number of valid entries in row `q`: the length of the prefix without the marker. -// Requires that the marker only appears as a suffix. -size_t check_row( - const svs::QueryResult& results, - size_t q, - const svs::data::SimpleData& base, - const svs::data::SimpleData& queries, - const std::function& is_live, - const std::function& to_row, - const Metric& metric -) { - size_t valid = 0; - while (valid < results.n_neighbors() && results.index(q, valid) != MARKER_ID) { - ++valid; - } - float previous = metric.smaller_is_better ? -std::numeric_limits::infinity() - : std::numeric_limits::infinity(); - for (size_t j = 0; j < results.n_neighbors(); ++j) { - size_t id = results.index(q, j); - float distance = results.distance(q, j); - if (j < valid) { - // Valid entry: live ID, exact distance, sorted nearest first. - CATCH_REQUIRE(is_live(id)); - auto expected = - metric.distance(base.get_datum(to_row(id)), queries.get_datum(q)); - CATCH_REQUIRE(distance == Catch::Approx(expected).epsilon(1e-4)); - CATCH_REQUIRE( - (metric.smaller_is_better ? distance >= previous : distance <= previous) - ); - previous = distance; - } else { - // Marker entries only after the valid ones. - CATCH_REQUIRE(id == MARKER_ID); - CATCH_REQUIRE(distance == metric.marker_distance); - } - } - return valid; -} - -using SearchFn = - std::function, const svs::lib::DefaultPredicate&)>; - -// `search(results, cancel)` performs a batch search with the index under test, returning -// `k` neighbors per query. -void check_cancel_semantics( - const SearchFn& search, - const svs::data::SimpleData& base, - const svs::data::SimpleData& queries, - const std::function& is_live, - const std::function& to_row, - bool single_thread, - const Metric& metric = l2_metric(), - size_t k = NUM_NEIGHBORS -) { - auto make_results = [&]() { return svs::QueryResult(queries.size(), k); }; - auto check = [&](const svs::QueryResult& results, size_t q) { - return check_row(results, q, base, queries, is_live, to_row, metric); - }; - - // (d) A predicate that never fires: identical to searching without a predicate. - { - auto expected = make_results(); - search(expected.view(), svs::lib::Returns(svs::lib::Const())); - auto actual = make_results(); - CountingCancel never{std::numeric_limits::max()}; - search(actual.view(), std::ref(never)); - CATCH_REQUIRE(never.polls_.load() > 0); - for (size_t q = 0; q < queries.size(); ++q) { - for (size_t j = 0; j < k; ++j) { - CATCH_REQUIRE(actual.index(q, j) == expected.index(q, j)); - CATCH_REQUIRE(actual.distance(q, j) == expected.distance(q, j)); - } - } - } - - // (a) Cancelled before anything started: every slot of every row is the marker. - { - auto results = make_results(); - // Fill with junk to make sure the search overwrites everything. - std::fill(results.indices().begin(), results.indices().end(), size_t{7}); - std::fill(results.distances().begin(), results.distances().end(), -1.0f); - CountingCancel cancel{0}; - search(results.view(), std::ref(cancel)); - for (size_t q = 0; q < queries.size(); ++q) { - for (size_t j = 0; j < k; ++j) { - CATCH_REQUIRE(results.index(q, j) == MARKER_ID); - CATCH_REQUIRE(results.distance(q, j) == metric.marker_distance); - } - } - } - - // (b), (c) Cancelled at various points. Rows must be a sorted prefix of live, - // exactly-measured neighbors followed by markers. - size_t partial_rows = 0; - size_t rows_with_neighbors = 0; - for (size_t allowed : {1, 2, 3, 5, 20, 100, 400, 1500, 6000}) { - auto results = make_results(); - std::fill(results.indices().begin(), results.indices().end(), size_t{7}); - std::fill(results.distances().begin(), results.distances().end(), -1.0f); - CountingCancel cancel{allowed}; - search(results.view(), std::ref(cancel)); - for (size_t q = 0; q < queries.size(); ++q) { - size_t valid = check(results, q); - rows_with_neighbors += (valid > 0); - partial_rows += (valid > 0 && valid < k); - } - } - CATCH_REQUIRE(rows_with_neighbors > 0); - if (single_thread) { - // A deterministic interruption: with one thread, the first query's single_search - // poll passes and the first visited-node poll fires. The row then holds only what - // initialization put into the search buffer. Later queries never start. - auto results = make_results(); - CountingCancel cancel{1}; - search(results.view(), std::ref(cancel)); - size_t valid = check(results, 0); - CATCH_REQUIRE(valid >= 1); - CATCH_REQUIRE(valid < k); - for (size_t q = 1; q < queries.size(); ++q) { - CATCH_REQUIRE(check(results, q) == 0); - } - CATCH_REQUIRE(partial_rows > 0); - } -} - -// Delete every fourth vector. -std::vector ids_to_delete(size_t n) { - std::vector ids; - for (size_t i = 0; i < n; i += 4) { - ids.push_back(external_id(i)); - } - return ids; -} - -// Delete all but every twentieth vector, so that few live vectors remain (95% deleted). -std::vector ids_to_delete_most(size_t n) { - std::vector ids; - for (size_t i = 0; i < n; ++i) { - if (i % 20 != 0) { - ids.push_back(external_id(i)); - } - } - return ids; -} - -std::vector all_external_ids(size_t n) { - std::vector ids(n); - for (size_t i = 0; i < n; ++i) { - ids[i] = external_id(i); - } - return ids; -} - -// Whether `id` is an external ID of a live vector of the dynamic test indexes. -std::function -is_live_external(size_t n, const std::unordered_set& deleted) { - return [n, &deleted](size_t id) { - return id >= 1000 && (id - 1000) % 3 == 0 && row_of(id) < n && - !deleted.contains(id); - }; -} - -// Static index test for any distance functor. -template -void check_static(const Metric& metric, size_t k = NUM_NEIGHBORS) { - auto base = svs::data::SimpleData::load(test_dataset::data_svs_file()); - auto queries = test_dataset::queries(); - // MIP and cosine require alpha <= 1. - svs::index::vamana::VamanaBuildParameters parameters{ - metric.smaller_is_better ? 1.2f : 0.95f, 64, 10, 20, 10, true}; - - for (size_t num_threads : {1, 3}) { - CATCH_SECTION("Threads: " + std::to_string(num_threads)) { - auto index = svs::Vamana::build( - parameters, - svs::data::SimpleData::load(test_dataset::data_svs_file()), - Distance(), - num_threads - ); - auto sp = search_parameters(); - check_cancel_semantics( - [&](auto results, const auto& cancel) { - index.search(results, queries.cview(), sp, cancel); - }, - base, - queries, - [&](size_t id) { return id < base.size(); }, - [](size_t id) { return id; }, - num_threads == 1, - metric, - k - ); - } - } -} - -// Checks of a dynamic index in which 95% of the vectors have been deleted. The search -// buffer then often holds fewer candidates than the window, which is when an uncancelled -// search tops it up with live vectors found outside the graph traversal. A cancelled -// search must not do that. -void check_mostly_deleted( - const SearchFn& search, - const svs::data::SimpleData& base, - const svs::data::SimpleData& queries, - const std::function& is_live, - bool single_thread -) { - const Metric metric = l2_metric(); - auto make_results = [&]() { - return svs::QueryResult(queries.size(), NUM_NEIGHBORS); - }; - - // The uncancelled search returns a full row of live IDs (thanks to the top-up). - { - auto results = make_results(); - search(results.view(), svs::lib::Returns(svs::lib::Const())); - for (size_t q = 0; q < queries.size(); ++q) { - CATCH_REQUIRE( - check_row(results, q, base, queries, is_live, row_of, metric) == - NUM_NEIGHBORS - ); - } - } - - // Cancelled searches only ever return live IDs, and rows may be incomplete. - size_t incomplete_rows = 0; - for (size_t allowed : {1, 2, 3, 5, 20, 100, 400, 1500}) { - auto results = make_results(); - CountingCancel cancel{allowed}; - search(results.view(), std::ref(cancel)); - for (size_t q = 0; q < queries.size(); ++q) { - incomplete_rows += - (check_row(results, q, base, queries, is_live, row_of, metric) < - NUM_NEIGHBORS); - } - } - CATCH_REQUIRE(incomplete_rows > 0); - - if (single_thread) { - // Interrupted right after initialization. The buffer then holds at most the entry - // point, so a full row can only come from a top-up, which must not happen. - auto results = make_results(); - CountingCancel cancel{1}; - search(results.view(), std::ref(cancel)); - CATCH_REQUIRE( - check_row(results, 0, base, queries, is_live, row_of, metric) < NUM_NEIGHBORS - ); - for (size_t q = 1; q < queries.size(); ++q) { - CATCH_REQUIRE( - check_row(results, q, base, queries, is_live, row_of, metric) == 0 - ); - } - } -} - -// Single-query search with caller-provided scratch space. `external` converts an internal -// ID in the search buffer to the vector's row in the base dataset. -template -void check_single_query( - Index& index, - const svs::data::SimpleData& base, - const svs::data::SimpleData& queries, - const std::function&)>& is_live, - const std::function&)>& to_row -) { - auto sp = search_parameters(); - auto scratch = index.scratchspace(sp); - auto metric = l2_metric(); - auto query = queries.get_datum(0); - - // Uncancelled: a full window of live candidates. - index.search(query, scratch); - const size_t full_size = scratch.buffer.size(); - CATCH_REQUIRE(full_size >= NUM_NEIGHBORS); - - // A predicate that never fires leaves the same candidates. - { - std::vector> expected; - for (const auto& n : scratch.buffer) { - expected.emplace_back(n.id(), n.distance()); - } - CountingCancel never{std::numeric_limits::max()}; - index.search(query, scratch, std::ref(never)); - CATCH_REQUIRE(never.polls_.load() > 0); - CATCH_REQUIRE(scratch.buffer.size() == expected.size()); - for (size_t j = 0; j < expected.size(); ++j) { - CATCH_REQUIRE(scratch.buffer[j].id() == expected[j].first); - CATCH_REQUIRE(scratch.buffer[j].distance() == expected[j].second); - } - } - - // Cancelled before the search starts: stale candidates are dropped, nothing is added - // (in particular no top-up). - { - CountingCancel cancel{0}; - index.search(query, scratch, std::ref(cancel)); - CATCH_REQUIRE(scratch.buffer.size() == 0); - } - - // Cancelled right after initialization: a partial, valid buffer without top-up. - { - CountingCancel cancel{1}; - index.search(query, scratch, std::ref(cancel)); - CATCH_REQUIRE(scratch.buffer.size() >= 1); - CATCH_REQUIRE(scratch.buffer.size() < full_size); - CATCH_REQUIRE(scratch.buffer.size() < SEARCH_WINDOW); - for (const auto& n : scratch.buffer) { - CATCH_REQUIRE(is_live(n)); - auto expected = metric.distance(base.get_datum(to_row(n)), query); - CATCH_REQUIRE(n.distance() == Catch::Approx(expected).epsilon(1e-4)); - } - } -} - -} // namespace - -CATCH_TEST_CASE("Static Vamana Cancelled Search", "[vamana][cancel]") { - check_static(l2_metric()); -} - -CATCH_TEST_CASE("Static Vamana Cancelled Search IP", "[vamana][cancel]") { - check_static(ip_metric()); -} - -CATCH_TEST_CASE("Static Vamana Cancelled Search Cosine", "[vamana][cancel]") { - check_static(cosine_metric()); -} - -CATCH_TEST_CASE("Static Vamana Cancelled Search k > window", "[vamana][cancel]") { - // More neighbors than the search window: the buffer is enlarged to `k`. - static_assert(40 > SEARCH_WINDOW); - check_static(l2_metric(), 40); -} - -CATCH_TEST_CASE("Dynamic Vamana Cancelled Search", "[vamana][dynamic_index][cancel]") { - using Distance = svs::distance::DistanceL2; - auto base = svs::data::SimpleData::load(test_dataset::data_svs_file()); - auto queries = test_dataset::queries(); - auto ids = all_external_ids(base.size()); - svs::index::vamana::VamanaBuildParameters parameters{1.2, 64, 10, 20, 10, true}; - auto index = svs::index::vamana::MutableVamanaIndex( - parameters, test_dataset::data_blocked_f32(), ids, Distance(), 1 - ); - auto deleted = ids_to_delete(base.size()); - index.delete_entries(deleted); - std::unordered_set deleted_set(deleted.begin(), deleted.end()); - - auto sp = search_parameters(); - for (size_t num_threads : {1, 3}) { - CATCH_SECTION("Threads: " + std::to_string(num_threads)) { - index.set_threadpool(svs::threads::DefaultThreadPool(num_threads)); - auto search = [&](auto results, const auto& cancel) { - index.search(results, queries.cview(), sp, cancel); - }; - auto is_live = is_live_external(base.size(), deleted_set); - check_cancel_semantics( - search, base, queries, is_live, row_of, num_threads == 1 - ); - // k larger than the search window. - check_cancel_semantics( - search, base, queries, is_live, row_of, num_threads == 1, l2_metric(), 40 - ); - } - } -} - -CATCH_TEST_CASE( - "Dynamic Vamana Cancelled Search, Mostly Deleted", "[vamana][dynamic_index][cancel]" -) { - using Distance = svs::distance::DistanceL2; - auto base = svs::data::SimpleData::load(test_dataset::data_svs_file()); - auto queries = test_dataset::queries(); - auto ids = all_external_ids(base.size()); - svs::index::vamana::VamanaBuildParameters parameters{1.2, 64, 10, 20, 10, true}; - auto index = svs::index::vamana::MutableVamanaIndex( - parameters, test_dataset::data_blocked_f32(), ids, Distance(), 1 - ); - auto deleted = ids_to_delete_most(base.size()); - index.delete_entries(deleted); - std::unordered_set deleted_set(deleted.begin(), deleted.end()); - CATCH_REQUIRE(index.size() > 2 * SEARCH_WINDOW); - - auto sp = search_parameters(); - for (size_t num_threads : {1, 3}) { - CATCH_SECTION("Threads: " + std::to_string(num_threads)) { - index.set_threadpool(svs::threads::DefaultThreadPool(num_threads)); - check_mostly_deleted( - [&](auto results, const auto& cancel) { - index.search(results, queries.cview(), sp, cancel); - }, - base, - queries, - is_live_external(base.size(), deleted_set), - num_threads == 1 - ); - } - } -} - -CATCH_TEST_CASE("Single Query Cancelled Search", "[vamana][dynamic_index][cancel]") { - auto base = svs::data::SimpleData::load(test_dataset::data_svs_file()); - auto queries = test_dataset::queries(); - - CATCH_SECTION("Static") { - auto index = test_dataset::vamana::load_test_index(svs::distance::DistanceL2()); - check_single_query( - index, - base, - queries, - [&](const auto& n) { return n.id() < base.size(); }, - [](const auto& n) -> size_t { return n.id(); } - ); - } - - CATCH_SECTION("Dynamic") { - auto ids = all_external_ids(base.size()); - svs::index::vamana::VamanaBuildParameters parameters{1.2, 64, 10, 20, 10, true}; - auto index = svs::index::vamana::MutableVamanaIndex( - parameters, - test_dataset::data_blocked_f32(), - ids, - svs::distance::DistanceL2(), - 1 - ); - // A buffer holding only the entry point would be topped up if not cancelled. - auto deleted = ids_to_delete(base.size()); - index.delete_entries(deleted); - std::unordered_set deleted_set(deleted.begin(), deleted.end()); - auto is_live = is_live_external(base.size(), deleted_set); - // Buffer entries hold internal IDs. - check_single_query( - index, - base, - queries, - [&](const auto& n) { return is_live(index.translate_internal_id(n.id())); }, - [&](const auto& n) -> size_t { - return row_of(index.translate_internal_id(n.id())); - } - ); - } -} - -CATCH_TEST_CASE( - "Concurrent Vamana Cancelled Search", "[vamana][concurrent][dynamic_index][cancel]" -) { - using Distance = svs::distance::DistanceL2; - auto base = svs::data::SimpleData::load(test_dataset::data_svs_file()); - auto queries = test_dataset::queries(); - auto ids = all_external_ids(base.size()); - svs::index::vamana::VamanaBuildParameters parameters{1.2, 64, 10, 20, 10, true}; - auto index = cc::MutableVamanaIndex( - parameters, - cc::SegmentedBlockedData::load(test_dataset::data_svs_file()), - ids, - Distance(), - 1 - ); - auto deleted = ids_to_delete(base.size()); - index.delete_entries(deleted); - std::unordered_set deleted_set(deleted.begin(), deleted.end()); - - auto sp = search_parameters(); - for (size_t num_threads : {1, 3}) { - CATCH_SECTION("Threads: " + std::to_string(num_threads)) { - index.set_threadpool(svs::threads::DefaultThreadPool(num_threads)); - check_cancel_semantics( - [&](auto results, const auto& cancel) { - index.search(results, queries.cview(), sp, cancel); - }, - base, - queries, - is_live_external(base.size(), deleted_set), - row_of, - num_threads == 1 - ); - } - } -} From c651a5cb59954754d2fdac7fbc2a01f5fa39a0cd Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Wed, 25 Nov 2026 14:30:15 -0800 Subject: [PATCH 3/5] Document that unstarted queries may hold entry points on cancel --- include/svs/index/vamana/index.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/include/svs/index/vamana/index.h b/include/svs/index/vamana/index.h index 7bbf2c1b3..b129aa7b8 100644 --- a/include/svs/index/vamana/index.h +++ b/include/svs/index/vamana/index.h @@ -560,9 +560,9 @@ class VamanaIndex { /// 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 never started hold only markers. Treat every slot whose ID is - /// the marker as empty: in the concurrent index a marker can also appear - /// mid-row. + /// 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. From ec23d9df1cb4e93bd0bead78df16255bdae31e3b Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Wed, 25 Nov 2026 15:17:11 -0800 Subject: [PATCH 4/5] Fix stale comment in the fallback batch search loop --- include/svs/index/vamana/extensions.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/svs/index/vamana/extensions.h b/include/svs/index/vamana/extensions.h index f80878529..ece65b474 100644 --- a/include/svs/index/vamana/extensions.h +++ b/include/svs/index/vamana/extensions.h @@ -611,8 +611,8 @@ void svs_invoke( // Fallback implementation for (auto i : thread_indices) { // Perform search - results will be queued in the search buffer. If ``cancel`` - // fires, the buffer holds what was found so far (empty if the query never - // started) and ``copy_results`` pads the rest of the row with the marker. + // 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 ); From 31d165cf5608edc161f24eeff83874e8a8dd9410 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Wed, 25 Nov 2026 15:40:06 -0800 Subject: [PATCH 5/5] Forward cancel in the batch iterator's single_search; strengthen cancel test --- include/svs/index/vamana/iterator.h | 3 ++- include/svs/orchestrators/manager.h | 2 +- tests/svs/index/vamana/dynamic_index.cpp | 18 +++++++++++++++++- 3 files changed, 20 insertions(+), 3 deletions(-) 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 fdccdf654..5aeb533ff 100644 --- a/include/svs/orchestrators/manager.h +++ b/include/svs/orchestrators/manager.h @@ -72,7 +72,7 @@ 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 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. diff --git a/tests/svs/index/vamana/dynamic_index.cpp b/tests/svs/index/vamana/dynamic_index.cpp index 6a5f81768..ca5e70cc5 100644 --- a/tests/svs/index/vamana/dynamic_index.cpp +++ b/tests/svs/index/vamana/dynamic_index.cpp @@ -496,11 +496,15 @@ CATCH_TEST_CASE("Vamana Cancelled Search", "[graph_index][dynamic_index][cancel] }; // A predicate that never fires gives the same results as no predicate. - auto reference = search(svs::lib::Returns(svs::lib::Const())); + 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)); } } @@ -555,5 +559,17 @@ CATCH_TEST_CASE("Vamana Cancelled Search", "[graph_index][dynamic_index][cancel] [](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); } }