From b6210bc0a6a0b7060d3c08d65fe395cde4186bb8 Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Tue, 24 Nov 2026 15:01:05 -0800 Subject: [PATCH 1/3] [C API] Add cancellation callback to search parameters Add svs_search_params_set_cancel_callback() and SVS_ERROR_CANCELLED. The callback is polled during svs_index_search_topk() (per visited node, before each query, and per filtered batch). When it returns true the search stops, returns false with SVS_ERROR_CANCELLED, and out_results holds the neighbors found so far for each query. Without a callback, behavior is unchanged. --- bindings/c/include/svs/c/svs_c.h | 34 ++ bindings/c/src/algorithm.hpp | 3 + bindings/c/src/filtered_search.hpp | 15 +- bindings/c/src/index.hpp | 3 +- bindings/c/src/index_vamana.cpp | 76 +++-- bindings/c/src/index_vamana.hpp | 9 +- bindings/c/src/svs_c.cpp | 40 ++- bindings/c/tests/CMakeLists.txt | 1 + bindings/c/tests/README.md | 1 + bindings/c/tests/c_api_search_cancel.cpp | 382 +++++++++++++++++++++++ 10 files changed, 529 insertions(+), 35 deletions(-) create mode 100644 bindings/c/tests/c_api_search_cancel.cpp diff --git a/bindings/c/include/svs/c/svs_c.h b/bindings/c/include/svs/c/svs_c.h index e8b69c30d..5f377dee2 100644 --- a/bindings/c/include/svs/c/svs_c.h +++ b/bindings/c/include/svs/c/svs_c.h @@ -55,6 +55,9 @@ enum svs_error_code { SVS_ERROR_UNSUPPORTED_HW = 6, SVS_ERROR_RUNTIME = 7, SVS_ERROR_INVALID_OPERATION = 8, + /// A search was stopped by the callback set with + /// svs_search_params_set_cancel_callback(). + SVS_ERROR_CANCELLED = 9, SVS_ERROR_UNKNOWN = 1000 }; @@ -933,6 +936,35 @@ SVS_API svs_search_params_h svs_search_params_create_vamana( /// @param params The search parameters handle to free SVS_API void svs_search_params_free(svs_search_params_h params); +/// @brief Cancellation predicate for searches. +/// @param userdata The opaque pointer given to svs_search_params_set_cancel_callback() +/// @return true to ask the search to stop, false to let it continue +/// @remarks The callback must not throw or longjmp out of the library, and must not call +/// back into the SVS C API. +typedef bool (*svs_is_cancelled_fn)(void* userdata); + +/// @brief Set a callback that lets the caller interrupt searches that use @p params +/// @details Used by svs_index_search_topk() (also filtered). It is polled once per visited +/// node, before each query, and per filtered batch. It may be called concurrently from +/// several threads, so it must be thread-safe and cheap. After it returns true, other +/// threads may still call it a few more times before they stop. The search then returns +/// false with SVS_ERROR_CANCELLED and @c out_results holds, per query, the neighbors found +/// so far (possibly fewer than k or none; queries that never started have none). A call +/// can be reported cancelled even if it had finished. +/// @param params The search parameters handle +/// @param fn The cancellation predicate, or NULL to remove a previously set callback +/// @param userdata Opaque pointer passed to @p fn on every call; the caller owns it and +/// it must stay valid for every search that uses @p params while the callback is set +/// @param out_err An optional error handle to capture errors +/// @return true on success, false on failure +/// @error SVS_ERROR_INVALID_ARGUMENT if @p params is NULL +SVS_API bool svs_search_params_set_cancel_callback( + svs_search_params_h params, + svs_is_cancelled_fn fn, + void* userdata, + svs_error_h out_err /*=NULL*/ +); + /// @brief Create a simple storage configuration /// @param data_type The data type of the vectors /// @param out_err An optional error handle to capture errors @@ -1513,6 +1545,8 @@ SVS_API bool svs_index_get_size( /// @return true on success, false on failure /// @error SVS_ERROR_NOT_IMPLEMENTED if @p index is a dynamic index with /// SVS_SYNC_KIND_FINE_GRAIN and @p num_queries is greater than 1 +/// @error SVS_ERROR_CANCELLED if the cancel callback of @p search_params returned true; +/// @p out_results then holds partial results (see svs_search_params_set_cancel_callback()) SVS_API bool svs_index_search_topk( svs_index_h index, const float* queries, diff --git a/bindings/c/src/algorithm.hpp b/bindings/c/src/algorithm.hpp index ca0de8b2d..1c852001c 100644 --- a/bindings/c/src/algorithm.hpp +++ b/bindings/c/src/algorithm.hpp @@ -28,6 +28,9 @@ namespace svs::c_runtime { struct Algorithm { struct SearchParams { svs_algorithm_type type; + // Set by svs_search_params_set_cancel_callback(); polled by searches. + svs_is_cancelled_fn cancel_fn = nullptr; + void* cancel_userdata = nullptr; SearchParams(svs_algorithm_type type) : type(type) {} virtual ~SearchParams() = default; diff --git a/bindings/c/src/filtered_search.hpp b/bindings/c/src/filtered_search.hpp index 8e45ac691..15e8b9349 100644 --- a/bindings/c/src/filtered_search.hpp +++ b/bindings/c/src/filtered_search.hpp @@ -152,6 +152,8 @@ inline void set_empty_result(svs::QueryResult& result) { // keeping only those that pass the filter. The batch size is estimated adaptively based on // the observed hit rate. Results are written into `results`. // returns a vector containing the number of neighbors found for each query. +// Once `cancel` returns true the search stops. Each row then holds the neighbors accepted +// so far (the returned count), followed by padding; queries that never started have 0. template std::vector filtered_topk_search( IndexType& index, @@ -159,7 +161,8 @@ std::vector filtered_topk_search( svs::data::ConstSimpleDataView queries, size_t initial_batch_hint, const IDFilterInterface* id_filter, - const std::function& sample_generator + const std::function& sample_generator, + const svs::lib::DefaultPredicate& cancel ) { // Minimum number of samples to estimate the filter hit rate. This is a trade-off // between accuracy and performance. A larger sample size gives a more accurate @@ -193,6 +196,9 @@ std::vector filtered_topk_search( auto search_closure = [&](const auto& range, uint64_t SVS_UNUSED(tid)) { for (auto i : range) { + if (cancel()) { + return; + } auto query = queries.get_datum(i); auto iterator = index.batch_iterator(query); size_t found = 0; @@ -202,7 +208,9 @@ std::vector filtered_topk_search( batch_size = estimate_batch_size( total_checked, found, num_neighbors, batch_size, index_size ); - iterator.next(batch_size); + iterator.next(batch_size, cancel); + // After a cancel, results() still holds the valid prefix of the batch + // with external IDs; keep what passes the filter and stop below. total_checked += iterator.size(); for (auto& neighbor : iterator.results()) { if (id_filter->is_member(neighbor.id())) { @@ -213,6 +221,9 @@ std::vector filtered_topk_search( } } } + if (found < num_neighbors && cancel()) { + break; + } // TODO: clarify the contract here - should we return partial or no // result if the hit rate is too low if (found < num_neighbors && diff --git a/bindings/c/src/index.hpp b/bindings/c/src/index.hpp index 577520780..70e2aecb8 100644 --- a/bindings/c/src/index.hpp +++ b/bindings/c/src/index.hpp @@ -49,7 +49,8 @@ struct Index { svs::data::ConstSimpleDataView queries, size_t num_neighbors, const std::shared_ptr& search_params, - const IDFilterInterface* id_filter = nullptr + const IDFilterInterface* id_filter = nullptr, + const lib::DefaultPredicate& cancel = lib::Returns(lib::Const()) ) = 0; virtual void save(const std::filesystem::path& directory) = 0; virtual void save(std::ostream& stream) = 0; diff --git a/bindings/c/src/index_vamana.cpp b/bindings/c/src/index_vamana.cpp index addc5eb34..2f4872e15 100644 --- a/bindings/c/src/index_vamana.cpp +++ b/bindings/c/src/index_vamana.cpp @@ -55,11 +55,38 @@ IndexVamana::IndexVamana(const IndexBuilder& builder, svs::Vamana&& index) this->index.set_search_parameters(params); } +namespace { +// Move the entries that hold a real ID to the front of each row (IDs and distances +// together, as the CSR exporter consumes each row's counted prefix) and set the per-row +// found counts. Slots left empty by a concurrent consolidation or by a cancelled search +// hold `no_external_id`. +void compact_found( + svs::QueryResult& results, std::vector& found_per_query +) { + for (size_t i = 0; i < results.n_queries(); ++i) { + size_t found = 0; + for (size_t j = 0; j < results.n_neighbors(); ++j) { + const auto id = results.index(i, j); + if (id == svs::index::vamana::concurrent::no_external_id) { + continue; + } + if (found != j) { + results.index(i, found) = id; + results.distance(i, found) = results.distance(i, j); + } + ++found; + } + found_per_query[i] = found; + } +} +} // namespace + std::pair, std::vector> IndexVamana::search( svs::data::ConstSimpleDataView queries, size_t num_neighbors, const std::shared_ptr& search_params, - const IDFilterInterface* id_filter + const IDFilterInterface* id_filter, + const lib::DefaultPredicate& cancel ) { auto vamana_search_params = std::static_pointer_cast(search_params); @@ -71,9 +98,13 @@ std::pair, std::vector> IndexVamana::search( } if (id_filter == nullptr) { - index.search(results.view(), queries, params); - // assuming all neighbors found - return {results, std::vector(queries.size(), num_neighbors)}; + index.search(results.view(), queries, params, cancel); + auto found_neighbors_per_query = std::vector(queries.size(), num_neighbors); + if (cancel()) { + // Cancelled slots hold no_external_id. + compact_found(results, found_neighbors_per_query); + } + return {results, std::move(found_neighbors_per_query)}; } std::mt19937 rng(42); @@ -84,7 +115,7 @@ std::pair, std::vector> IndexVamana::search( std::max(num_neighbors, params.buffer_config_.get_search_window_size()); auto found_neighbors_per_query = filtered_topk_search( - index, results, queries, batch_hint, id_filter, sample_generator + index, results, queries, batch_hint, id_filter, sample_generator, cancel ); return {results, found_neighbors_per_query}; } @@ -119,7 +150,8 @@ std::pair, std::vector> DynamicIndexVamana::sea svs::data::ConstSimpleDataView queries, size_t num_neighbors, const std::shared_ptr& search_params, - const IDFilterInterface* id_filter + const IDFilterInterface* id_filter, + const lib::DefaultPredicate& cancel ) { auto lock = read_lock(); auto vamana_search_params = @@ -132,26 +164,11 @@ std::pair, std::vector> DynamicIndexVamana::sea } if (id_filter == nullptr) { - index.search(results.view(), queries, params); + index.search(results.view(), queries, params, cancel); auto found_neighbors_per_query = std::vector(queries.size(), num_neighbors); - if (sync_kind == SVS_SYNC_KIND_FINE_GRAIN) { - // Consolidation can erase buffered IDs before translation. The CSR exporter - // consumes each row's counted prefix, so move IDs and distances together. - for (size_t i = 0; i < results.n_queries(); ++i) { - size_t found = 0; - for (size_t j = 0; j < results.n_neighbors(); ++j) { - const auto id = results.index(i, j); - if (id == svs::index::vamana::concurrent::no_external_id) { - continue; - } - if (found != j) { - results.index(i, found) = id; - results.distance(i, found) = results.distance(i, j); - } - ++found; - } - found_neighbors_per_query[i] = found; - } + if (sync_kind == SVS_SYNC_KIND_FINE_GRAIN || cancel()) { + // Erased IDs (consolidation) and cancelled slots hold no_external_id. + compact_found(results, found_neighbors_per_query); } return {std::move(results), std::move(found_neighbors_per_query)}; } @@ -186,7 +203,7 @@ std::pair, std::vector> DynamicIndexVamana::sea std::max(num_neighbors, params.buffer_config_.get_search_window_size()); auto found_neighbors_per_query = filtered_topk_search( - index, results, queries, batch_hint, id_filter, sample_generator + index, results, queries, batch_hint, id_filter, sample_generator, cancel ); return {results, found_neighbors_per_query}; } @@ -281,7 +298,8 @@ std::pair, std::vector> ConcurrentIndexVamana:: svs::data::ConstSimpleDataView queries, size_t num_neighbors, const std::shared_ptr& search_params, - const IDFilterInterface* id_filter + const IDFilterInterface* id_filter, + const lib::DefaultPredicate& cancel ) { assert(sync_kind == SVS_SYNC_KIND_FINE_GRAIN); if (queries.size() > 1) { @@ -289,7 +307,9 @@ std::pair, std::vector> ConcurrentIndexVamana:: "FINE GRAIN dynamic index only supports searching one query at a time." ); } - return DynamicIndexVamana::search(queries, num_neighbors, search_params, id_filter); + return DynamicIndexVamana::search( + queries, num_neighbors, search_params, id_filter, cancel + ); } size_t ConcurrentIndexVamana::add_points( diff --git a/bindings/c/src/index_vamana.hpp b/bindings/c/src/index_vamana.hpp index 2a193981e..65888fa42 100644 --- a/bindings/c/src/index_vamana.hpp +++ b/bindings/c/src/index_vamana.hpp @@ -44,7 +44,8 @@ struct IndexVamana : public Index { svs::data::ConstSimpleDataView queries, size_t num_neighbors, const std::shared_ptr& search_params, - const IDFilterInterface* id_filter + const IDFilterInterface* id_filter, + const lib::DefaultPredicate& cancel ) override; void save(const std::filesystem::path& directory) override { @@ -93,7 +94,8 @@ struct DynamicIndexVamana : public DynamicIndex { svs::data::ConstSimpleDataView queries, size_t num_neighbors, const std::shared_ptr& search_params, - const IDFilterInterface* id_filter + const IDFilterInterface* id_filter, + const lib::DefaultPredicate& cancel ) override; void save(const std::filesystem::path& directory) override; @@ -170,7 +172,8 @@ struct ConcurrentIndexVamana : public DynamicIndexVamana { svs::data::ConstSimpleDataView queries, size_t num_neighbors, const std::shared_ptr& search_params, - const IDFilterInterface* id_filter + const IDFilterInterface* id_filter, + const lib::DefaultPredicate& cancel ) override; size_t add_points( diff --git a/bindings/c/src/svs_c.cpp b/bindings/c/src/svs_c.cpp index 5a549b3c4..0abe06619 100644 --- a/bindings/c/src/svs_c.cpp +++ b/bindings/c/src/svs_c.cpp @@ -28,6 +28,7 @@ #include "threadpool.hpp" #include "types_support.hpp" +#include #include #include #include @@ -370,6 +371,21 @@ svs_search_params_create_vamana(size_t search_window_size, svs_error_h out_err) extern "C" void svs_search_params_free(svs_search_params_h params) { delete params; } +extern "C" bool svs_search_params_set_cancel_callback( + svs_search_params_h params, svs_is_cancelled_fn fn, void* userdata, svs_error_h out_err +) { + using namespace svs::c_runtime; + return wrap_exceptions( + [&]() { + EXPECT_ARG_NOT_NULL(params); + params->impl->cancel_fn = fn; + params->impl->cancel_userdata = fn == nullptr ? nullptr : userdata; + return true; + }, + out_err + ); +} + extern "C" svs_storage_h svs_storage_create_simple(svs_data_type_t data_type, svs_error_h out_err) { using namespace svs::c_runtime; @@ -1478,11 +1494,30 @@ extern "C" bool svs_index_search_topk( IDFilterAdapter id_filter_adapter(id_filter); + // Latch the first `true` so every thread stops and we can report it below. + std::atomic fired{false}; + svs::lib::DefaultPredicate cancel = svs::lib::Returns(svs::lib::Const()); + if (search_params != nullptr && search_params->impl->cancel_fn != nullptr) { + cancel = [&, + fn = search_params->impl->cancel_fn, + ud = search_params->impl->cancel_userdata]() { + if (fired.load(std::memory_order_relaxed)) { + return true; + } + if (fn(ud)) { + fired.store(true, std::memory_order_relaxed); + return true; + } + return false; + }; + } + auto [search_results, found_neighbors_per_query] = index_ptr->search( queries_view, k, search_params == nullptr ? nullptr : search_params->impl, - id_filter == nullptr ? nullptr : &id_filter_adapter + id_filter == nullptr ? nullptr : &id_filter_adapter, + cancel ); out_results->num_queries = num_queries; @@ -1503,6 +1538,9 @@ extern "C" bool svs_index_search_topk( } out_results->offsets[num_queries] = result_index; // sentinel + if (cancel()) { + throw coded_error(SVS_ERROR_CANCELLED, "Search cancelled by callback"); + } return true; }, out_err diff --git a/bindings/c/tests/CMakeLists.txt b/bindings/c/tests/CMakeLists.txt index f9abb9f3a..163133e35 100644 --- a/bindings/c/tests/CMakeLists.txt +++ b/bindings/c/tests/CMakeLists.txt @@ -50,6 +50,7 @@ set(C_API_TEST_SOURCES c_api_algorithm.cpp c_api_storage.cpp c_api_search_params.cpp + c_api_search_cancel.cpp c_api_index_builder.cpp c_api_index.cpp c_api_index_convert.cpp diff --git a/bindings/c/tests/README.md b/bindings/c/tests/README.md index c351a7527..01439f81d 100644 --- a/bindings/c/tests/README.md +++ b/bindings/c/tests/README.md @@ -26,6 +26,7 @@ The tests are organized into separate files by functionality: - **c_api_algorithm.cpp**: Tests for algorithm creation and configuration (Vamana) - **c_api_storage.cpp**: Tests for storage configurations (Simple, LeanVec, LVQ, SQ) - **c_api_search_params.cpp**: Tests for search parameter creation and configuration +- **c_api_search_cancel.cpp**: Tests for the search cancellation callback (poll counts, partial-result semantics, static/dynamic/filtered/multi-threaded searches) - **c_api_index_builder.cpp**: Tests for index builder creation and configuration - **c_api_index.cpp**: Tests for index building, searching, and basic operations - **c_api_dynamic_index.cpp**: Tests for dynamic index operations (add, delete, consolidate, compact) diff --git a/bindings/c/tests/c_api_search_cancel.cpp b/bindings/c/tests/c_api_search_cancel.cpp new file mode 100644 index 000000000..792fd890b --- /dev/null +++ b/bindings/c/tests/c_api_search_cancel.cpp @@ -0,0 +1,382 @@ +/* + * 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. + */ + +// C API +#include "svs/c/svs_c.h" + +// catch2 +#include "catch2/catch_test_macros.hpp" +#include "catch2/generators/catch_generators.hpp" + +// Test utilities +#include "c_api_test_utils.h" + +// Standard library +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr size_t DIMENSION = 32; +constexpr size_t NUM_VECTORS = 1000; +constexpr size_t NUM_QUERIES = 5; +constexpr size_t K = 10; +constexpr size_t SEARCH_WINDOW = 100; +constexpr size_t NUM_THREADS = 4; +constexpr size_t INVALID_ID = std::numeric_limits::max(); + +enum class IndexKind { Static, DynamicNone, DynamicGlobal, DynamicFineGrain }; + +// Counts every poll. Returns true from poll number `cancel_after + 1` on. +struct CountingCancel { + std::atomic calls{0}; + size_t cancel_after = static_cast(-1); +}; + +bool counting_is_cancelled(void* userdata) { + auto* state = static_cast(userdata); + return state->calls.fetch_add(1, std::memory_order_relaxed) >= state->cancel_after; +} + +bool filter_is_odd(void* /*self*/, size_t id) { return (id % 2) == 1; } +float filter_rate_odd(void* /*self*/) { return 0.5f; } + +// Random data: the periodic generate_test_data() pattern repeats every few rows, which +// starves the filtered search (all top neighbors share a parity) and makes it flaky. +std::vector random_vectors(size_t count, unsigned seed) { + std::mt19937 rng(seed); + std::uniform_real_distribution dist(-1.0f, 1.0f); + std::vector out(count * DIMENSION); + for (auto& x : out) { + x = dist(rng); + } + return out; +} + +struct CancelFixture { + svs_error_h error = svs_error_create(); + svs_algorithm_h algorithm = nullptr; + svs_index_builder_h builder = nullptr; + svs_index_h index = nullptr; + svs_search_params_h params = nullptr; + svs_distance_metric_t metric; + std::vector data; + std::vector queries = random_vectors(NUM_QUERIES, 2); + // External ID -> row in `data` for every vector that is live in the index. + std::unordered_map live; + size_t num_queries; + + // `scattered`: dynamic indexes get non-contiguous external IDs and every fifth + // vector is deleted after the build. + CancelFixture( + IndexKind kind, svs_distance_metric_t metric, size_t num_threads, bool scattered + ) + // FINE_GRAIN dynamic indexes only search one query at a time. + : metric(metric) + , data(random_vectors(NUM_VECTORS, 1)) + , num_queries(kind == IndexKind::DynamicFineGrain ? 1 : NUM_QUERIES) { + algorithm = svs_algorithm_create_vamana(16, 32, SEARCH_WINDOW, error); + builder = svs_index_builder_create(metric, DIMENSION, algorithm, error); + svs_index_builder_set_threadpool( + builder, SVS_THREADPOOL_KIND_NATIVE, num_threads, error + ); + if (kind == IndexKind::Static) { + index = svs_index_build(builder, data.data(), NUM_VECTORS, error); + for (size_t i = 0; i < NUM_VECTORS; ++i) { + live[i] = i; + } + } else { + std::vector ids(NUM_VECTORS); + for (size_t i = 0; i < NUM_VECTORS; ++i) { + ids[i] = scattered ? 5001 + i + i / 3 : i; // a gap every third ID + live[ids[i]] = i; + } + svs_dynamic_index_params_t dyn_params = SVS_INIT_DYNAMIC_INDEX_PARAMS(); + dyn_params.blocksize_bytes = 1 << 20; + dyn_params.sync_kind = kind == IndexKind::DynamicNone ? SVS_SYNC_KIND_NONE + : kind == IndexKind::DynamicGlobal + ? SVS_SYNC_KIND_GLOBAL + : SVS_SYNC_KIND_FINE_GRAIN; + index = svs_index_build_dynamic_ex( + builder, data.data(), ids.data(), NUM_VECTORS, &dyn_params, error + ); + if (scattered) { + // One at a time: FINE_GRAIN only supports single-ID deletes. + for (size_t i = 0; i < NUM_VECTORS; i += 5) { + svs_index_dynamic_delete_points(index, &ids[i], 1, nullptr, error); + live.erase(ids[i]); + } + } + } + params = svs_search_params_create_vamana(SEARCH_WINDOW, error); + } + + ~CancelFixture() { + svs_search_params_free(params); + svs_index_free(index); + svs_index_builder_free(builder); + svs_algorithm_free(algorithm); + svs_error_free(error); + } + + CancelFixture(const CancelFixture&) = delete; + CancelFixture& operator=(const CancelFixture&) = delete; + + bool search(svs_search_results_t* results, bool filtered) { + svs_id_filter_interface_ops ops = + SVS_INIT_ID_FILTER_OPS(filter_is_odd, filter_rate_odd); + svs_id_filter_interface filter = SVS_MAKE_INTERFACE(nullptr, ops); + return svs_index_search_topk( + index, + queries.data(), + num_queries, + K, + results, + params, + filtered ? &filter : nullptr, + error + ); + } + + bool set_callback(CountingCancel* state) { + return svs_search_params_set_cancel_callback( + params, state ? counting_is_cancelled : nullptr, state, error + ); + } + + float distance(size_t query, size_t id) const { + const float* q = queries.data() + query * DIMENSION; + const float* x = data.data() + live.at(id) * DIMENSION; + return metric == SVS_DISTANCE_METRIC_EUCLIDEAN + ? euclidean_distance(q, x, DIMENSION) + : inner_product_distance(q, x, DIMENSION); + } + + // Every returned entry must be a live external ID with its true distance, rows must + // be nearest first, and the library's invalid-neighbor marker must never leak out. + void + require_valid_partial_rows(const svs_search_results_t& results, bool filtered) const { + CATCH_REQUIRE(results.num_queries == num_queries); + CATCH_REQUIRE(results.offsets[0] == 0); + CATCH_REQUIRE(results.offsets[num_queries] == results.total_results); + for (size_t q = 0; q < num_queries; ++q) { + const size_t begin = results.offsets[q]; + const size_t end = results.offsets[q + 1]; + CATCH_REQUIRE(begin <= end); + CATCH_REQUIRE(end - begin <= K); + std::unordered_set seen; + for (size_t i = begin; i < end; ++i) { + const size_t id = results.indices[i]; + CATCH_REQUIRE(id != INVALID_ID); + CATCH_REQUIRE(live.count(id) == 1); + CATCH_REQUIRE(seen.insert(id).second); + if (filtered) { + CATCH_REQUIRE(filter_is_odd(nullptr, id)); + } + const float expected = distance(q, id); + CATCH_REQUIRE( + std::abs(results.distances[i] - expected) <= + 1e-4f + 1e-3f * std::abs(expected) + ); + // Filtered rows are concatenated iterator batches and are only ordered + // within a batch (also when not cancelled), so check order unfiltered. + if (i > begin && !filtered) { + if (metric == SVS_DISTANCE_METRIC_EUCLIDEAN) { + CATCH_REQUIRE(results.distances[i - 1] <= results.distances[i]); + } else { + CATCH_REQUIRE(results.distances[i - 1] >= results.distances[i]); + } + } + } + } + } +}; + +void require_same_results( + const svs_search_results_t& actual, const svs_search_results_t& expected +) { + CATCH_REQUIRE(actual.num_queries == expected.num_queries); + CATCH_REQUIRE(actual.total_results == expected.total_results); + for (size_t q = 0; q <= expected.num_queries; ++q) { + CATCH_REQUIRE(actual.offsets[q] == expected.offsets[q]); + } + for (size_t i = 0; i < expected.total_results; ++i) { + CATCH_REQUIRE(actual.indices[i] == expected.indices[i]); + CATCH_REQUIRE(actual.distances[i] == expected.distances[i]); + } +} + +void require_cancelled(CancelFixture& fx, bool success) { + CATCH_REQUIRE_FALSE(success); + CATCH_REQUIRE(svs_error_get_code(fx.error) == SVS_ERROR_CANCELLED); +} + +} // namespace + +CATCH_TEST_CASE("C API Search Cancel Callback", "[c_api][index][search][cancel]") { + const auto kind = GENERATE( + IndexKind::Static, + IndexKind::DynamicNone, + IndexKind::DynamicGlobal, + IndexKind::DynamicFineGrain + ); + const auto metric = + GENERATE(SVS_DISTANCE_METRIC_EUCLIDEAN, SVS_DISTANCE_METRIC_DOT_PRODUCT); + const bool filtered = GENERATE(false, true); + const size_t num_threads = GENERATE(size_t{1}, NUM_THREADS); + // Non-contiguous IDs plus deletions (dynamic indexes only). + const bool scattered = GENERATE(false, true); + if (kind == IndexKind::Static && scattered) { + return; // scattered IDs and deletions only apply to dynamic indexes + } + CancelFixture fx{kind, metric, num_threads, scattered}; + CATCH_REQUIRE(fx.index != nullptr); + CATCH_REQUIRE(fx.params != nullptr); + // With several threads concurrent polls can overshoot the cancel point. + const size_t max_overshoot = num_threads - 1; + + svs_search_results_t baseline = SVS_INIT_SEARCH_RESULTS(); + CATCH_REQUIRE(fx.search(&baseline, filtered)); + CATCH_REQUIRE(svs_error_ok(fx.error)); + CATCH_INFO( + "kind=" << int(kind) << " metric=" << int(metric) << " filtered=" << filtered + << " threads=" << num_threads << " scattered=" << scattered + ); + CATCH_REQUIRE(baseline.total_results > 0); + fx.require_valid_partial_rows(baseline, filtered); + + // Number of polls a complete, uncancelled search makes. + CountingCancel never; + CATCH_REQUIRE(fx.set_callback(&never)); + svs_search_results_t results = SVS_INIT_SEARCH_RESULTS(); + CATCH_REQUIRE(fx.search(&results, filtered)); + CATCH_REQUIRE(svs_error_ok(fx.error)); + const size_t uncancelled_calls = never.calls.load(); + CATCH_REQUIRE(uncancelled_calls > 0); + + CATCH_SECTION("Callback that never cancels returns the baseline results") { + require_same_results(results, baseline); + } + + CATCH_SECTION("NULL callback is identical to no callback") { + CATCH_REQUIRE(fx.set_callback(nullptr)); + CATCH_REQUIRE(fx.search(&results, filtered)); + CATCH_REQUIRE(svs_error_ok(fx.error)); + require_same_results(results, baseline); + CATCH_REQUIRE(never.calls.load() == uncancelled_calls); + } + + CATCH_SECTION("Set then unset") { + CountingCancel always; + always.cancel_after = 0; + CATCH_REQUIRE(fx.set_callback(&always)); + CATCH_REQUIRE(fx.set_callback(nullptr)); + CATCH_REQUIRE(fx.search(&results, filtered)); + CATCH_REQUIRE(svs_error_ok(fx.error)); + require_same_results(results, baseline); + CATCH_REQUIRE(always.calls.load() == 0); + } + + CATCH_SECTION("Cancel before the search starts returns no results") { + CountingCancel always; + always.cancel_after = 0; + CATCH_REQUIRE(fx.set_callback(&always)); + require_cancelled(fx, fx.search(&results, filtered)); + CATCH_REQUIRE(results.num_queries == fx.num_queries); + CATCH_REQUIRE(results.total_results == 0); + for (size_t q = 0; q <= fx.num_queries; ++q) { + CATCH_REQUIRE(results.offsets[q] == 0); + } + // The first poll latches the request, so the callback is not consulted again + // (at most one concurrent first poll per thread). + CATCH_REQUIRE(always.calls.load() >= 1); + CATCH_REQUIRE(always.calls.load() <= 1 + max_overshoot); + } + + CATCH_SECTION("Cancel in the middle of the search returns the neighbors found so far") { + size_t partial_total = 0; + bool any_fewer = false; + // Poll counts the counting callback lets through before it asks to cancel. + const size_t cancel_points[] = {1, 5, uncancelled_calls / 2, uncancelled_calls - 1}; + for (size_t cancel_after : cancel_points) { + CountingCancel mid; + mid.cancel_after = cancel_after; + CATCH_REQUIRE(fx.set_callback(&mid)); + svs_search_results_free(&results); + results = SVS_INIT_SEARCH_RESULTS(); + bool ok = fx.search(&results, filtered); + CATCH_INFO("cancel_after=" << cancel_after << " calls=" << mid.calls.load()); + require_cancelled(fx, ok); + fx.require_valid_partial_rows(results, filtered); + // A row may already be full when the cancel arrives. + CATCH_REQUIRE(results.total_results <= baseline.total_results); + CATCH_REQUIRE(mid.calls.load() >= cancel_after + 1); + CATCH_REQUIRE(mid.calls.load() <= cancel_after + 1 + max_overshoot); + CATCH_REQUIRE(mid.calls.load() <= uncancelled_calls + max_overshoot); + partial_total += results.total_results; + any_fewer |= results.total_results < baseline.total_results; + } + // At least one cancel point must have left some neighbors behind. + CATCH_REQUIRE(partial_total > 0); + // With several queries, the ones that never started return nothing. + CATCH_REQUIRE((fx.num_queries == 1 || any_fewer)); + } + + CATCH_SECTION("A search after a cancelled one is unaffected") { + CountingCancel mid; + mid.cancel_after = uncancelled_calls / 2; + CATCH_REQUIRE(fx.set_callback(&mid)); + require_cancelled(fx, fx.search(&results, filtered)); + CATCH_REQUIRE(fx.set_callback(nullptr)); + CATCH_REQUIRE(fx.search(&results, filtered)); + CATCH_REQUIRE(svs_error_ok(fx.error)); + require_same_results(results, baseline); + } + + svs_search_results_free(&results); + svs_search_results_free(&baseline); +} + +CATCH_TEST_CASE( + "C API Search Cancel Callback argument validation", "[c_api][search_params][cancel]" +) { + svs_error_h error = svs_error_create(); + + CATCH_SECTION("NULL params") { + CATCH_REQUIRE_FALSE(svs_search_params_set_cancel_callback( + nullptr, counting_is_cancelled, nullptr, error + )); + CATCH_REQUIRE(svs_error_get_code(error) == SVS_ERROR_INVALID_ARGUMENT); + } + + CATCH_SECTION("NULL error handle") { + svs_search_params_h params = svs_search_params_create_vamana(100, nullptr); + CATCH_REQUIRE(params != nullptr); + CATCH_REQUIRE(svs_search_params_set_cancel_callback( + params, counting_is_cancelled, nullptr, nullptr + )); + svs_search_params_free(params); + } + + svs_error_free(error); +} From 85270d1d4b89b7b6e583a164870628afd4bca2bc Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Wed, 25 Nov 2026 14:40:14 -0800 Subject: [PATCH 2/3] Simplify C API cancel tests and report cancel before the search starts --- bindings/c/include/svs/c/svs_c.h | 6 +- bindings/c/src/svs_c.cpp | 9 + bindings/c/tests/CMakeLists.txt | 1 - bindings/c/tests/README.md | 1 - bindings/c/tests/c_api_index.cpp | 150 +++++++++ bindings/c/tests/c_api_search_cancel.cpp | 382 ----------------------- bindings/c/tests/c_api_search_params.cpp | 21 ++ 7 files changed, 184 insertions(+), 386 deletions(-) delete mode 100644 bindings/c/tests/c_api_search_cancel.cpp diff --git a/bindings/c/include/svs/c/svs_c.h b/bindings/c/include/svs/c/svs_c.h index 5f377dee2..ad96f728e 100644 --- a/bindings/c/include/svs/c/svs_c.h +++ b/bindings/c/include/svs/c/svs_c.h @@ -949,8 +949,10 @@ typedef bool (*svs_is_cancelled_fn)(void* userdata); /// several threads, so it must be thread-safe and cheap. After it returns true, other /// threads may still call it a few more times before they stop. The search then returns /// false with SVS_ERROR_CANCELLED and @c out_results holds, per query, the neighbors found -/// so far (possibly fewer than k or none; queries that never started have none). A call -/// can be reported cancelled even if it had finished. +/// so far (possibly fewer than k; queries that had not started when the cancel fired may +/// hold a few candidates). If the callback already returns true when the call starts, no +/// search is run and @c out_results holds no results. A call can be reported cancelled even +/// if it had finished. /// @param params The search parameters handle /// @param fn The cancellation predicate, or NULL to remove a previously set callback /// @param userdata Opaque pointer passed to @p fn on every call; the caller owns it and diff --git a/bindings/c/src/svs_c.cpp b/bindings/c/src/svs_c.cpp index 0abe06619..28be866f6 100644 --- a/bindings/c/src/svs_c.cpp +++ b/bindings/c/src/svs_c.cpp @@ -28,6 +28,7 @@ #include "threadpool.hpp" #include "types_support.hpp" +#include #include #include #include @@ -1512,6 +1513,14 @@ extern "C" bool svs_index_search_topk( }; } + // Cancelled before the search starts: report no results, search nothing. + if (cancel()) { + out_results->num_queries = num_queries; + out_results->total_results = 0; + std::fill_n(out_results->offsets, num_queries + 1, size_t{0}); + throw coded_error(SVS_ERROR_CANCELLED, "Search cancelled by callback"); + } + auto [search_results, found_neighbors_per_query] = index_ptr->search( queries_view, k, diff --git a/bindings/c/tests/CMakeLists.txt b/bindings/c/tests/CMakeLists.txt index 163133e35..f9abb9f3a 100644 --- a/bindings/c/tests/CMakeLists.txt +++ b/bindings/c/tests/CMakeLists.txt @@ -50,7 +50,6 @@ set(C_API_TEST_SOURCES c_api_algorithm.cpp c_api_storage.cpp c_api_search_params.cpp - c_api_search_cancel.cpp c_api_index_builder.cpp c_api_index.cpp c_api_index_convert.cpp diff --git a/bindings/c/tests/README.md b/bindings/c/tests/README.md index 01439f81d..c351a7527 100644 --- a/bindings/c/tests/README.md +++ b/bindings/c/tests/README.md @@ -26,7 +26,6 @@ The tests are organized into separate files by functionality: - **c_api_algorithm.cpp**: Tests for algorithm creation and configuration (Vamana) - **c_api_storage.cpp**: Tests for storage configurations (Simple, LeanVec, LVQ, SQ) - **c_api_search_params.cpp**: Tests for search parameter creation and configuration -- **c_api_search_cancel.cpp**: Tests for the search cancellation callback (poll counts, partial-result semantics, static/dynamic/filtered/multi-threaded searches) - **c_api_index_builder.cpp**: Tests for index builder creation and configuration - **c_api_index.cpp**: Tests for index building, searching, and basic operations - **c_api_dynamic_index.cpp**: Tests for dynamic index operations (add, delete, consolidate, compact) diff --git a/bindings/c/tests/c_api_index.cpp b/bindings/c/tests/c_api_index.cpp index 46fd1215c..aa15ea4ac 100644 --- a/bindings/c/tests/c_api_index.cpp +++ b/bindings/c/tests/c_api_index.cpp @@ -25,7 +25,10 @@ // Standard library #include +#include #include +#include +#include #include CATCH_TEST_CASE("C API Index Build and Search", "[c_api][index][build][search]") { @@ -1548,3 +1551,150 @@ CATCH_TEST_CASE("C API Filtered Search topK", "[c_api][index][search][filter]") svs_error_free(error); } } + +namespace { +// Cancel callback: counts its polls and returns true from poll number `cancel_after` + 1. +struct CancelState { + std::atomic calls{0}; + size_t cancel_after = static_cast(-1); +}; + +bool cancel_after_polls(void* userdata) { + auto* state = static_cast(userdata); + return state->calls.fetch_add(1) >= state->cancel_after; +} +} // namespace + +CATCH_TEST_CASE("C API Search Cancel Callback", "[c_api][index][search][cancel]") { + const size_t NUM_VECTORS = 1000; + const size_t NUM_QUERIES = 5; + const size_t DIMENSION = 32; + const size_t K = 10; + const size_t INVALID_ID = static_cast(-1); + + // Random data: the periodic generate_test_data() pattern has duplicate vectors, which + // starves a filtered search. + std::mt19937 rng(1); + std::uniform_real_distribution uniform(-1.0f, 1.0f); + std::vector data(NUM_VECTORS * DIMENSION); + std::vector queries(NUM_QUERIES * DIMENSION); + for (auto& x : data) { + x = uniform(rng); + } + for (auto& x : queries) { + x = uniform(rng); + } + + svs_error_h error = svs_error_create(); + svs_algorithm_h algorithm = svs_algorithm_create_vamana(16, 32, 100, error); + svs_index_builder_h builder = svs_index_builder_create( + SVS_DISTANCE_METRIC_EUCLIDEAN, DIMENSION, algorithm, error + ); + CATCH_REQUIRE( + svs_index_builder_set_threadpool(builder, SVS_THREADPOOL_KIND_NATIVE, 4, error) + ); + svs_search_params_h params = svs_search_params_create_vamana(100, error); + svs_id_filter_interface_ops odd_ops = + SVS_INIT_ID_FILTER_OPS(filter_is_odd, filter_rate_odd); + svs_id_filter_interface odd_filter = SVS_MAKE_INTERFACE(nullptr, odd_ops); + + // Runs the cancel checks on `index`; `live(id)` says whether `id` may be returned. + auto check = [&](svs_index_h index, svs_id_filter_i filter, auto live) { + auto search = [&](svs_search_results_t* results) { + return svs_index_search_topk( + index, queries.data(), NUM_QUERIES, K, results, params, filter, error + ); + }; + auto set_callback = [&](CancelState* state) { + CATCH_REQUIRE(svs_search_params_set_cancel_callback( + params, state ? cancel_after_polls : nullptr, state, error + )); + }; + + svs_search_results_t expected = SVS_INIT_SEARCH_RESULTS(); + CATCH_REQUIRE(search(&expected)); + CATCH_REQUIRE(expected.total_results > 0); + + // A callback that never fires, or no callback, gives the same results. + CancelState never; + for (CancelState* state : {&never, static_cast(nullptr)}) { + set_callback(state); + svs_search_results_t results = SVS_INIT_SEARCH_RESULTS(); + CATCH_REQUIRE(search(&results)); + CATCH_REQUIRE(results.total_results == expected.total_results); + for (size_t i = 0; i < expected.total_results; ++i) { + CATCH_REQUIRE(results.indices[i] == expected.indices[i]); + CATCH_REQUIRE(results.distances[i] == expected.distances[i]); + } + svs_search_results_free(&results); + } + CATCH_REQUIRE(never.calls.load() > 0); + + // Cancelled before the search starts: no results. + CancelState always; + always.cancel_after = 0; + set_callback(&always); + svs_search_results_t results = SVS_INIT_SEARCH_RESULTS(); + CATCH_REQUIRE_FALSE(search(&results)); + CATCH_REQUIRE(svs_error_get_code(error) == SVS_ERROR_CANCELLED); + CATCH_REQUIRE(results.total_results == 0); + svs_search_results_free(&results); + + // Cancelled in the middle: only live IDs, never the invalid-neighbor marker. + CancelState mid; + mid.cancel_after = never.calls.load() / 2; + set_callback(&mid); + results = SVS_INIT_SEARCH_RESULTS(); + CATCH_REQUIRE_FALSE(search(&results)); + CATCH_REQUIRE(svs_error_get_code(error) == SVS_ERROR_CANCELLED); + CATCH_REQUIRE(results.total_results > 0); + CATCH_REQUIRE(results.offsets[NUM_QUERIES] == results.total_results); + for (size_t i = 0; i < results.total_results; ++i) { + CATCH_REQUIRE(results.indices[i] != INVALID_ID); + CATCH_REQUIRE(live(results.indices[i])); + } + svs_search_results_free(&results); + svs_search_results_free(&expected); + set_callback(nullptr); + }; + + CATCH_SECTION("Static index") { + svs_index_h index = svs_index_build(builder, data.data(), NUM_VECTORS, error); + CATCH_REQUIRE(index != nullptr); + check(index, nullptr, [&](size_t id) { return id < NUM_VECTORS; }); + svs_index_free(index); + } + + CATCH_SECTION("Static index, filtered") { + svs_index_h index = svs_index_build(builder, data.data(), NUM_VECTORS, error); + CATCH_REQUIRE(index != nullptr); + check(index, &odd_filter, [&](size_t id) { return id < NUM_VECTORS && id % 2; }); + svs_index_free(index); + } + + CATCH_SECTION("Dynamic index with deletions") { + // Row i has external ID 5000 + i; every 5th vector is deleted. + std::vector ids(NUM_VECTORS); + std::iota(ids.begin(), ids.end(), size_t{5000}); + svs_index_h index = svs_index_build_dynamic( + builder, data.data(), ids.data(), NUM_VECTORS, 1024 * 1024, error + ); + CATCH_REQUIRE(index != nullptr); + std::vector deleted; + for (size_t i = 0; i < NUM_VECTORS; i += 5) { + deleted.push_back(ids[i]); + } + CATCH_REQUIRE(svs_index_dynamic_delete_points( + index, deleted.data(), deleted.size(), nullptr, error + )); + check(index, nullptr, [&](size_t id) { + return id >= 5000 && id < 5000 + NUM_VECTORS && (id - 5000) % 5 != 0; + }); + svs_index_free(index); + } + + svs_search_params_free(params); + svs_index_builder_free(builder); + svs_algorithm_free(algorithm); + svs_error_free(error); +} diff --git a/bindings/c/tests/c_api_search_cancel.cpp b/bindings/c/tests/c_api_search_cancel.cpp deleted file mode 100644 index 792fd890b..000000000 --- a/bindings/c/tests/c_api_search_cancel.cpp +++ /dev/null @@ -1,382 +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. - */ - -// C API -#include "svs/c/svs_c.h" - -// catch2 -#include "catch2/catch_test_macros.hpp" -#include "catch2/generators/catch_generators.hpp" - -// Test utilities -#include "c_api_test_utils.h" - -// Standard library -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -constexpr size_t DIMENSION = 32; -constexpr size_t NUM_VECTORS = 1000; -constexpr size_t NUM_QUERIES = 5; -constexpr size_t K = 10; -constexpr size_t SEARCH_WINDOW = 100; -constexpr size_t NUM_THREADS = 4; -constexpr size_t INVALID_ID = std::numeric_limits::max(); - -enum class IndexKind { Static, DynamicNone, DynamicGlobal, DynamicFineGrain }; - -// Counts every poll. Returns true from poll number `cancel_after + 1` on. -struct CountingCancel { - std::atomic calls{0}; - size_t cancel_after = static_cast(-1); -}; - -bool counting_is_cancelled(void* userdata) { - auto* state = static_cast(userdata); - return state->calls.fetch_add(1, std::memory_order_relaxed) >= state->cancel_after; -} - -bool filter_is_odd(void* /*self*/, size_t id) { return (id % 2) == 1; } -float filter_rate_odd(void* /*self*/) { return 0.5f; } - -// Random data: the periodic generate_test_data() pattern repeats every few rows, which -// starves the filtered search (all top neighbors share a parity) and makes it flaky. -std::vector random_vectors(size_t count, unsigned seed) { - std::mt19937 rng(seed); - std::uniform_real_distribution dist(-1.0f, 1.0f); - std::vector out(count * DIMENSION); - for (auto& x : out) { - x = dist(rng); - } - return out; -} - -struct CancelFixture { - svs_error_h error = svs_error_create(); - svs_algorithm_h algorithm = nullptr; - svs_index_builder_h builder = nullptr; - svs_index_h index = nullptr; - svs_search_params_h params = nullptr; - svs_distance_metric_t metric; - std::vector data; - std::vector queries = random_vectors(NUM_QUERIES, 2); - // External ID -> row in `data` for every vector that is live in the index. - std::unordered_map live; - size_t num_queries; - - // `scattered`: dynamic indexes get non-contiguous external IDs and every fifth - // vector is deleted after the build. - CancelFixture( - IndexKind kind, svs_distance_metric_t metric, size_t num_threads, bool scattered - ) - // FINE_GRAIN dynamic indexes only search one query at a time. - : metric(metric) - , data(random_vectors(NUM_VECTORS, 1)) - , num_queries(kind == IndexKind::DynamicFineGrain ? 1 : NUM_QUERIES) { - algorithm = svs_algorithm_create_vamana(16, 32, SEARCH_WINDOW, error); - builder = svs_index_builder_create(metric, DIMENSION, algorithm, error); - svs_index_builder_set_threadpool( - builder, SVS_THREADPOOL_KIND_NATIVE, num_threads, error - ); - if (kind == IndexKind::Static) { - index = svs_index_build(builder, data.data(), NUM_VECTORS, error); - for (size_t i = 0; i < NUM_VECTORS; ++i) { - live[i] = i; - } - } else { - std::vector ids(NUM_VECTORS); - for (size_t i = 0; i < NUM_VECTORS; ++i) { - ids[i] = scattered ? 5001 + i + i / 3 : i; // a gap every third ID - live[ids[i]] = i; - } - svs_dynamic_index_params_t dyn_params = SVS_INIT_DYNAMIC_INDEX_PARAMS(); - dyn_params.blocksize_bytes = 1 << 20; - dyn_params.sync_kind = kind == IndexKind::DynamicNone ? SVS_SYNC_KIND_NONE - : kind == IndexKind::DynamicGlobal - ? SVS_SYNC_KIND_GLOBAL - : SVS_SYNC_KIND_FINE_GRAIN; - index = svs_index_build_dynamic_ex( - builder, data.data(), ids.data(), NUM_VECTORS, &dyn_params, error - ); - if (scattered) { - // One at a time: FINE_GRAIN only supports single-ID deletes. - for (size_t i = 0; i < NUM_VECTORS; i += 5) { - svs_index_dynamic_delete_points(index, &ids[i], 1, nullptr, error); - live.erase(ids[i]); - } - } - } - params = svs_search_params_create_vamana(SEARCH_WINDOW, error); - } - - ~CancelFixture() { - svs_search_params_free(params); - svs_index_free(index); - svs_index_builder_free(builder); - svs_algorithm_free(algorithm); - svs_error_free(error); - } - - CancelFixture(const CancelFixture&) = delete; - CancelFixture& operator=(const CancelFixture&) = delete; - - bool search(svs_search_results_t* results, bool filtered) { - svs_id_filter_interface_ops ops = - SVS_INIT_ID_FILTER_OPS(filter_is_odd, filter_rate_odd); - svs_id_filter_interface filter = SVS_MAKE_INTERFACE(nullptr, ops); - return svs_index_search_topk( - index, - queries.data(), - num_queries, - K, - results, - params, - filtered ? &filter : nullptr, - error - ); - } - - bool set_callback(CountingCancel* state) { - return svs_search_params_set_cancel_callback( - params, state ? counting_is_cancelled : nullptr, state, error - ); - } - - float distance(size_t query, size_t id) const { - const float* q = queries.data() + query * DIMENSION; - const float* x = data.data() + live.at(id) * DIMENSION; - return metric == SVS_DISTANCE_METRIC_EUCLIDEAN - ? euclidean_distance(q, x, DIMENSION) - : inner_product_distance(q, x, DIMENSION); - } - - // Every returned entry must be a live external ID with its true distance, rows must - // be nearest first, and the library's invalid-neighbor marker must never leak out. - void - require_valid_partial_rows(const svs_search_results_t& results, bool filtered) const { - CATCH_REQUIRE(results.num_queries == num_queries); - CATCH_REQUIRE(results.offsets[0] == 0); - CATCH_REQUIRE(results.offsets[num_queries] == results.total_results); - for (size_t q = 0; q < num_queries; ++q) { - const size_t begin = results.offsets[q]; - const size_t end = results.offsets[q + 1]; - CATCH_REQUIRE(begin <= end); - CATCH_REQUIRE(end - begin <= K); - std::unordered_set seen; - for (size_t i = begin; i < end; ++i) { - const size_t id = results.indices[i]; - CATCH_REQUIRE(id != INVALID_ID); - CATCH_REQUIRE(live.count(id) == 1); - CATCH_REQUIRE(seen.insert(id).second); - if (filtered) { - CATCH_REQUIRE(filter_is_odd(nullptr, id)); - } - const float expected = distance(q, id); - CATCH_REQUIRE( - std::abs(results.distances[i] - expected) <= - 1e-4f + 1e-3f * std::abs(expected) - ); - // Filtered rows are concatenated iterator batches and are only ordered - // within a batch (also when not cancelled), so check order unfiltered. - if (i > begin && !filtered) { - if (metric == SVS_DISTANCE_METRIC_EUCLIDEAN) { - CATCH_REQUIRE(results.distances[i - 1] <= results.distances[i]); - } else { - CATCH_REQUIRE(results.distances[i - 1] >= results.distances[i]); - } - } - } - } - } -}; - -void require_same_results( - const svs_search_results_t& actual, const svs_search_results_t& expected -) { - CATCH_REQUIRE(actual.num_queries == expected.num_queries); - CATCH_REQUIRE(actual.total_results == expected.total_results); - for (size_t q = 0; q <= expected.num_queries; ++q) { - CATCH_REQUIRE(actual.offsets[q] == expected.offsets[q]); - } - for (size_t i = 0; i < expected.total_results; ++i) { - CATCH_REQUIRE(actual.indices[i] == expected.indices[i]); - CATCH_REQUIRE(actual.distances[i] == expected.distances[i]); - } -} - -void require_cancelled(CancelFixture& fx, bool success) { - CATCH_REQUIRE_FALSE(success); - CATCH_REQUIRE(svs_error_get_code(fx.error) == SVS_ERROR_CANCELLED); -} - -} // namespace - -CATCH_TEST_CASE("C API Search Cancel Callback", "[c_api][index][search][cancel]") { - const auto kind = GENERATE( - IndexKind::Static, - IndexKind::DynamicNone, - IndexKind::DynamicGlobal, - IndexKind::DynamicFineGrain - ); - const auto metric = - GENERATE(SVS_DISTANCE_METRIC_EUCLIDEAN, SVS_DISTANCE_METRIC_DOT_PRODUCT); - const bool filtered = GENERATE(false, true); - const size_t num_threads = GENERATE(size_t{1}, NUM_THREADS); - // Non-contiguous IDs plus deletions (dynamic indexes only). - const bool scattered = GENERATE(false, true); - if (kind == IndexKind::Static && scattered) { - return; // scattered IDs and deletions only apply to dynamic indexes - } - CancelFixture fx{kind, metric, num_threads, scattered}; - CATCH_REQUIRE(fx.index != nullptr); - CATCH_REQUIRE(fx.params != nullptr); - // With several threads concurrent polls can overshoot the cancel point. - const size_t max_overshoot = num_threads - 1; - - svs_search_results_t baseline = SVS_INIT_SEARCH_RESULTS(); - CATCH_REQUIRE(fx.search(&baseline, filtered)); - CATCH_REQUIRE(svs_error_ok(fx.error)); - CATCH_INFO( - "kind=" << int(kind) << " metric=" << int(metric) << " filtered=" << filtered - << " threads=" << num_threads << " scattered=" << scattered - ); - CATCH_REQUIRE(baseline.total_results > 0); - fx.require_valid_partial_rows(baseline, filtered); - - // Number of polls a complete, uncancelled search makes. - CountingCancel never; - CATCH_REQUIRE(fx.set_callback(&never)); - svs_search_results_t results = SVS_INIT_SEARCH_RESULTS(); - CATCH_REQUIRE(fx.search(&results, filtered)); - CATCH_REQUIRE(svs_error_ok(fx.error)); - const size_t uncancelled_calls = never.calls.load(); - CATCH_REQUIRE(uncancelled_calls > 0); - - CATCH_SECTION("Callback that never cancels returns the baseline results") { - require_same_results(results, baseline); - } - - CATCH_SECTION("NULL callback is identical to no callback") { - CATCH_REQUIRE(fx.set_callback(nullptr)); - CATCH_REQUIRE(fx.search(&results, filtered)); - CATCH_REQUIRE(svs_error_ok(fx.error)); - require_same_results(results, baseline); - CATCH_REQUIRE(never.calls.load() == uncancelled_calls); - } - - CATCH_SECTION("Set then unset") { - CountingCancel always; - always.cancel_after = 0; - CATCH_REQUIRE(fx.set_callback(&always)); - CATCH_REQUIRE(fx.set_callback(nullptr)); - CATCH_REQUIRE(fx.search(&results, filtered)); - CATCH_REQUIRE(svs_error_ok(fx.error)); - require_same_results(results, baseline); - CATCH_REQUIRE(always.calls.load() == 0); - } - - CATCH_SECTION("Cancel before the search starts returns no results") { - CountingCancel always; - always.cancel_after = 0; - CATCH_REQUIRE(fx.set_callback(&always)); - require_cancelled(fx, fx.search(&results, filtered)); - CATCH_REQUIRE(results.num_queries == fx.num_queries); - CATCH_REQUIRE(results.total_results == 0); - for (size_t q = 0; q <= fx.num_queries; ++q) { - CATCH_REQUIRE(results.offsets[q] == 0); - } - // The first poll latches the request, so the callback is not consulted again - // (at most one concurrent first poll per thread). - CATCH_REQUIRE(always.calls.load() >= 1); - CATCH_REQUIRE(always.calls.load() <= 1 + max_overshoot); - } - - CATCH_SECTION("Cancel in the middle of the search returns the neighbors found so far") { - size_t partial_total = 0; - bool any_fewer = false; - // Poll counts the counting callback lets through before it asks to cancel. - const size_t cancel_points[] = {1, 5, uncancelled_calls / 2, uncancelled_calls - 1}; - for (size_t cancel_after : cancel_points) { - CountingCancel mid; - mid.cancel_after = cancel_after; - CATCH_REQUIRE(fx.set_callback(&mid)); - svs_search_results_free(&results); - results = SVS_INIT_SEARCH_RESULTS(); - bool ok = fx.search(&results, filtered); - CATCH_INFO("cancel_after=" << cancel_after << " calls=" << mid.calls.load()); - require_cancelled(fx, ok); - fx.require_valid_partial_rows(results, filtered); - // A row may already be full when the cancel arrives. - CATCH_REQUIRE(results.total_results <= baseline.total_results); - CATCH_REQUIRE(mid.calls.load() >= cancel_after + 1); - CATCH_REQUIRE(mid.calls.load() <= cancel_after + 1 + max_overshoot); - CATCH_REQUIRE(mid.calls.load() <= uncancelled_calls + max_overshoot); - partial_total += results.total_results; - any_fewer |= results.total_results < baseline.total_results; - } - // At least one cancel point must have left some neighbors behind. - CATCH_REQUIRE(partial_total > 0); - // With several queries, the ones that never started return nothing. - CATCH_REQUIRE((fx.num_queries == 1 || any_fewer)); - } - - CATCH_SECTION("A search after a cancelled one is unaffected") { - CountingCancel mid; - mid.cancel_after = uncancelled_calls / 2; - CATCH_REQUIRE(fx.set_callback(&mid)); - require_cancelled(fx, fx.search(&results, filtered)); - CATCH_REQUIRE(fx.set_callback(nullptr)); - CATCH_REQUIRE(fx.search(&results, filtered)); - CATCH_REQUIRE(svs_error_ok(fx.error)); - require_same_results(results, baseline); - } - - svs_search_results_free(&results); - svs_search_results_free(&baseline); -} - -CATCH_TEST_CASE( - "C API Search Cancel Callback argument validation", "[c_api][search_params][cancel]" -) { - svs_error_h error = svs_error_create(); - - CATCH_SECTION("NULL params") { - CATCH_REQUIRE_FALSE(svs_search_params_set_cancel_callback( - nullptr, counting_is_cancelled, nullptr, error - )); - CATCH_REQUIRE(svs_error_get_code(error) == SVS_ERROR_INVALID_ARGUMENT); - } - - CATCH_SECTION("NULL error handle") { - svs_search_params_h params = svs_search_params_create_vamana(100, nullptr); - CATCH_REQUIRE(params != nullptr); - CATCH_REQUIRE(svs_search_params_set_cancel_callback( - params, counting_is_cancelled, nullptr, nullptr - )); - svs_search_params_free(params); - } - - svs_error_free(error); -} diff --git a/bindings/c/tests/c_api_search_params.cpp b/bindings/c/tests/c_api_search_params.cpp index 1d3daa174..7c02d7afa 100644 --- a/bindings/c/tests/c_api_search_params.cpp +++ b/bindings/c/tests/c_api_search_params.cpp @@ -89,3 +89,24 @@ CATCH_TEST_CASE("C API Search Parameters", "[c_api][search_params]") { svs_error_free(error); } } + +CATCH_TEST_CASE( + "C API Search Cancel Callback arguments", "[c_api][search_params][cancel]" +) { + svs_error_h error = svs_error_create(); + svs_is_cancelled_fn never = [](void*) { return false; }; + + CATCH_REQUIRE_FALSE( + svs_search_params_set_cancel_callback(nullptr, never, nullptr, error) + ); + CATCH_REQUIRE(svs_error_get_code(error) == SVS_ERROR_INVALID_ARGUMENT); + + svs_search_params_h params = svs_search_params_create_vamana(100, nullptr); + CATCH_REQUIRE(params != nullptr); + // A NULL error handle is allowed, and a NULL callback removes the callback. + CATCH_REQUIRE(svs_search_params_set_cancel_callback(params, never, nullptr, nullptr)); + CATCH_REQUIRE(svs_search_params_set_cancel_callback(params, nullptr, nullptr, nullptr)); + + svs_search_params_free(params); + svs_error_free(error); +} From ffbc86e7c87000162d99e36e3109af093bbbe2cc Mon Sep 17 00:00:00 2001 From: yuejiaointel Date: Wed, 25 Nov 2026 15:46:02 -0800 Subject: [PATCH 3/3] Document cancel polling points; test cancel on a filtered dynamic index --- bindings/c/include/svs/c/svs_c.h | 18 +++++++++--------- bindings/c/tests/c_api_index.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/bindings/c/include/svs/c/svs_c.h b/bindings/c/include/svs/c/svs_c.h index ad96f728e..2b337a7e9 100644 --- a/bindings/c/include/svs/c/svs_c.h +++ b/bindings/c/include/svs/c/svs_c.h @@ -944,15 +944,15 @@ SVS_API void svs_search_params_free(svs_search_params_h params); typedef bool (*svs_is_cancelled_fn)(void* userdata); /// @brief Set a callback that lets the caller interrupt searches that use @p params -/// @details Used by svs_index_search_topk() (also filtered). It is polled once per visited -/// node, before each query, and per filtered batch. It may be called concurrently from -/// several threads, so it must be thread-safe and cheap. After it returns true, other -/// threads may still call it a few more times before they stop. The search then returns -/// false with SVS_ERROR_CANCELLED and @c out_results holds, per query, the neighbors found -/// so far (possibly fewer than k; queries that had not started when the cancel fired may -/// hold a few candidates). If the callback already returns true when the call starts, no -/// search is run and @c out_results holds no results. A call can be reported cancelled even -/// if it had finished. +/// @details Used by svs_index_search_topk() (also filtered). It is polled once at call +/// start, once per visited node, and per query and per batch for filtered search. It may be +/// called concurrently from several threads, so it must be thread-safe and cheap. After it +/// returns true, other threads may still call it a few more times before they stop. The +/// search then returns false with SVS_ERROR_CANCELLED and @c out_results holds, per query, +/// the neighbors found so far (possibly fewer than k; queries that had not started when the +/// cancel fired may hold a few candidates). If the callback already returns true when the +/// call starts, no search is run and @c out_results holds no results. A call can be +/// reported cancelled even if it had finished. /// @param params The search parameters handle /// @param fn The cancellation predicate, or NULL to remove a previously set callback /// @param userdata Opaque pointer passed to @p fn on every call; the caller owns it and diff --git a/bindings/c/tests/c_api_index.cpp b/bindings/c/tests/c_api_index.cpp index aa15ea4ac..dced37d72 100644 --- a/bindings/c/tests/c_api_index.cpp +++ b/bindings/c/tests/c_api_index.cpp @@ -1649,6 +1649,9 @@ CATCH_TEST_CASE("C API Search Cancel Callback", "[c_api][index][search][cancel]" CATCH_REQUIRE(svs_error_get_code(error) == SVS_ERROR_CANCELLED); CATCH_REQUIRE(results.total_results > 0); CATCH_REQUIRE(results.offsets[NUM_QUERIES] == results.total_results); + for (size_t q = 0; q < NUM_QUERIES; ++q) { + CATCH_REQUIRE(results.offsets[q + 1] - results.offsets[q] <= K); + } for (size_t i = 0; i < results.total_results; ++i) { CATCH_REQUIRE(results.indices[i] != INVALID_ID); CATCH_REQUIRE(live(results.indices[i])); @@ -1693,6 +1696,27 @@ CATCH_TEST_CASE("C API Search Cancel Callback", "[c_api][index][search][cancel]" svs_index_free(index); } + CATCH_SECTION("Dynamic index with deletions, filtered") { + // Row i has external ID 5000 + i; every 5th vector is deleted, odd IDs pass. + std::vector ids(NUM_VECTORS); + std::iota(ids.begin(), ids.end(), size_t{5000}); + svs_index_h index = svs_index_build_dynamic( + builder, data.data(), ids.data(), NUM_VECTORS, 1024 * 1024, error + ); + CATCH_REQUIRE(index != nullptr); + std::vector deleted; + for (size_t i = 0; i < NUM_VECTORS; i += 5) { + deleted.push_back(ids[i]); + } + CATCH_REQUIRE(svs_index_dynamic_delete_points( + index, deleted.data(), deleted.size(), nullptr, error + )); + check(index, &odd_filter, [&](size_t id) { + return id >= 5000 && id < 5000 + NUM_VECTORS && (id - 5000) % 5 != 0 && id % 2; + }); + svs_index_free(index); + } + svs_search_params_free(params); svs_index_builder_free(builder); svs_algorithm_free(algorithm);