Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions bindings/c/include/svs/c/svs_c.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
};

Expand Down Expand Up @@ -933,6 +936,37 @@ 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 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
/// 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
Expand Down Expand Up @@ -1513,6 +1547,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,
Expand Down
3 changes: 3 additions & 0 deletions bindings/c/src/algorithm.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
15 changes: 13 additions & 2 deletions bindings/c/src/filtered_search.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -152,14 +152,17 @@ inline void set_empty_result(svs::QueryResult<size_t>& 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 <typename IndexType>
std::vector<size_t> filtered_topk_search(
IndexType& index,
svs::QueryResult<size_t>& results,
svs::data::ConstSimpleDataView<float> queries,
size_t initial_batch_hint,
const IDFilterInterface* id_filter,
const std::function<size_t()>& sample_generator
const std::function<size_t()>& 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
Expand Down Expand Up @@ -193,6 +196,9 @@ std::vector<size_t> 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;
Expand All @@ -202,7 +208,9 @@ std::vector<size_t> 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())) {
Expand All @@ -213,6 +221,9 @@ std::vector<size_t> 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 &&
Expand Down
3 changes: 2 additions & 1 deletion bindings/c/src/index.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ struct Index {
svs::data::ConstSimpleDataView<float> queries,
size_t num_neighbors,
const std::shared_ptr<Algorithm::SearchParams>& search_params,
const IDFilterInterface* id_filter = nullptr
const IDFilterInterface* id_filter = nullptr,
const lib::DefaultPredicate& cancel = lib::Returns(lib::Const<false>())
) = 0;
virtual void save(const std::filesystem::path& directory) = 0;
virtual void save(std::ostream& stream) = 0;
Expand Down
76 changes: 48 additions & 28 deletions bindings/c/src/index_vamana.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<size_t>& results, std::vector<size_t>& 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<svs::QueryResult<size_t>, std::vector<size_t>> IndexVamana::search(
svs::data::ConstSimpleDataView<float> queries,
size_t num_neighbors,
const std::shared_ptr<Algorithm::SearchParams>& search_params,
const IDFilterInterface* id_filter
const IDFilterInterface* id_filter,
const lib::DefaultPredicate& cancel
) {
auto vamana_search_params =
std::static_pointer_cast<AlgorithmVamana::SearchParams>(search_params);
Expand All @@ -71,9 +98,13 @@ std::pair<svs::QueryResult<size_t>, std::vector<size_t>> IndexVamana::search(
}

if (id_filter == nullptr) {
index.search(results.view(), queries, params);
// assuming all neighbors found
return {results, std::vector<size_t>(queries.size(), num_neighbors)};
index.search(results.view(), queries, params, cancel);
auto found_neighbors_per_query = std::vector<size_t>(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);
Expand All @@ -84,7 +115,7 @@ std::pair<svs::QueryResult<size_t>, std::vector<size_t>> 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};
}
Expand Down Expand Up @@ -119,7 +150,8 @@ std::pair<svs::QueryResult<size_t>, std::vector<size_t>> DynamicIndexVamana::sea
svs::data::ConstSimpleDataView<float> queries,
size_t num_neighbors,
const std::shared_ptr<Algorithm::SearchParams>& search_params,
const IDFilterInterface* id_filter
const IDFilterInterface* id_filter,
const lib::DefaultPredicate& cancel
) {
auto lock = read_lock();
auto vamana_search_params =
Expand All @@ -132,26 +164,11 @@ std::pair<svs::QueryResult<size_t>, std::vector<size_t>> 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<size_t>(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)};
}
Expand Down Expand Up @@ -186,7 +203,7 @@ std::pair<svs::QueryResult<size_t>, std::vector<size_t>> 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};
}
Expand Down Expand Up @@ -281,15 +298,18 @@ std::pair<svs::QueryResult<size_t>, std::vector<size_t>> ConcurrentIndexVamana::
svs::data::ConstSimpleDataView<float> queries,
size_t num_neighbors,
const std::shared_ptr<Algorithm::SearchParams>& 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) {
throw not_implemented(
"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(
Expand Down
9 changes: 6 additions & 3 deletions bindings/c/src/index_vamana.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ struct IndexVamana : public Index {
svs::data::ConstSimpleDataView<float> queries,
size_t num_neighbors,
const std::shared_ptr<Algorithm::SearchParams>& search_params,
const IDFilterInterface* id_filter
const IDFilterInterface* id_filter,
const lib::DefaultPredicate& cancel
) override;

void save(const std::filesystem::path& directory) override {
Expand Down Expand Up @@ -93,7 +94,8 @@ struct DynamicIndexVamana : public DynamicIndex {
svs::data::ConstSimpleDataView<float> queries,
size_t num_neighbors,
const std::shared_ptr<Algorithm::SearchParams>& search_params,
const IDFilterInterface* id_filter
const IDFilterInterface* id_filter,
const lib::DefaultPredicate& cancel
) override;

void save(const std::filesystem::path& directory) override;
Expand Down Expand Up @@ -170,7 +172,8 @@ struct ConcurrentIndexVamana : public DynamicIndexVamana {
svs::data::ConstSimpleDataView<float> queries,
size_t num_neighbors,
const std::shared_ptr<Algorithm::SearchParams>& search_params,
const IDFilterInterface* id_filter
const IDFilterInterface* id_filter,
const lib::DefaultPredicate& cancel
) override;

size_t add_points(
Expand Down
49 changes: 48 additions & 1 deletion bindings/c/src/svs_c.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
#include "threadpool.hpp"
#include "types_support.hpp"

#include <algorithm>
#include <atomic>
#include <bit>
#include <cstddef>
#include <filesystem>
Expand Down Expand Up @@ -370,6 +372,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;
Expand Down Expand Up @@ -1478,11 +1495,38 @@ 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<bool> fired{false};
svs::lib::DefaultPredicate cancel = svs::lib::Returns(svs::lib::Const<false>());
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;
};
}

// 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,
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;
Expand All @@ -1503,6 +1547,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
Expand Down
Loading
Loading