Skip to content

[C API] Implement range search using batch iterator - #480

Open
rfsaliev wants to merge 4 commits into
mainfrom
dev/filtered-range-search
Open

rfsaliev wants to merge 4 commits into
mainfrom
dev/filtered-range-search

Conversation

@rfsaliev

Copy link
Copy Markdown
Member

[C API] Add range search with optional ID filter and result limit (using batch iterator)

Summary

Adds svs_index_search_range() to the C API. It returns, for each query, the neighbors strictly closer than a radius, with an optional ID filter and an optional per-query result limit. It works for static Vamana indexes and for dynamic indexes with every sync kind (NONE, GLOBAL, FINE_GRAIN).

This PR also wraps svs_search_results_t management into an internal SearchResults class that top-K search and range search share.

API

SVS_API bool svs_index_search_range(
    svs_index_h index,
    const float* queries,
    size_t num_queries,
    float radius,
    size_t max_results /*=0*/,
    svs_search_results_t* out_results,
    svs_search_params_h search_params /*=NULL*/,
    svs_id_filter_i id_filter /*=NULL*/,
    svs_error_h out_err /*=NULL*/
);
  • Radius is in the units of the index metric and is exclusive:
    • Euclidean returns squared L2 distances < radius.
    • Dot product and cosine return similarities > radius.
  • Rows vary in length, can be empty, and are ordered from closest to farthest. They are written in the existing CSR layout and can be read with svs_search_results_row().
  • max_results caps each row; 0 means no limit. A capped row holds the closest in-range neighbors, and the search for that query stops once the row is full.
  • search_params may be NULL, in which case the index defaults are used. The search window size also sets the batch size used to walk the graph.
  • id_filter works the same way as in svs_index_search_topk(). If filter_rate > 0 and the observed hit rate is lower, the affected rows come back empty: every row when the pre-search sampling detects it, otherwise only the row being searched.
  • Errors:
    • SVS_ERROR_INVALID_ARGUMENT for bad arguments (num_queries == 0, NULL handles or pointers, an incompatible results struct). It is also returned when caller-owned buffers are too small; in that case out_results is left unchanged.
    • SVS_ERROR_NOT_IMPLEMENTED for more than one query on a SVS_SYNC_KIND_FINE_GRAIN index, matching top-K.

Implementation

  • filtered_range_search() (filtered_search.hpp) walks each query's batch iterator in parallel. It stops at the first candidate outside the radius, or when the row reaches max_results. The distance direction comes from the index metric through DistanceDispatcher.

  • Index::search_range() now writes into a SearchResults&. Implementations:

    • IndexVamana (static).
    • DynamicIndexVamana, which takes the shared lock, so NONE and GLOBAL are covered.
    • ConcurrentIndexVamana (FINE_GRAIN), limited to one query per call. Deleted and concurrently consolidated IDs are already skipped by the batch iterators.
  • DynamicIndexVamana::make_sample_generator() now holds the ID-sampling code used for filter-rate estimation. Filtered top-K and range search share it.

  • SearchResults (search_results.hpp) is a non-owning wrapper over svs_search_results_t. It provides:

    • validate(): version and struct_size checks.
    • reserve(): grows buffers the library owns; caller-owned buffers that are too small are rejected. It allocates the new buffer before freeing the old one, so a failed allocation leaves the existing buffer in place.
    • assign(): writes results from a QueryResult plus per-query counts, or from per-query neighbor lists.
    • reset(): the logic behind svs_search_results_free().

    It replaces the former ensure_search_results_capacity() helper in svs_c.cpp.

Documentation

  • svs_c.h: full description of range search, a new SVS_ERROR_INVALID_ARGUMENT case for svs_index_search_topk() when caller-owned buffers are too small, and the fine-grain one-query limit now listing range search.
  • docs/C_API_Design.md: range search moved from "Future Extensions" to current capabilities, with a usage example, notes on radius, limit and buffer behaviour, and an updated function overview.
  • README.md: mentions range search.

Testing

New file tests/c_api_search_results.cpp:

  • Search results buffers:
    • library-owned buffers reused across searches and grown when needed;
    • svs_search_results_free() safe to call twice and on NULL;
    • caller-owned buffers, including ones that are too small;
    • results structs with an incompatible version or struct_size rejected;
    • the svs_search_results_row() accessor, including out-of-range rows.
  • Range search for L2, dot product and cosine, checked against brute force: results within the radius, sorted, unique, distances matching, and at least 90% of the expected neighbors found. Also covers:
    • explicit search parameters;
    • the ID filter, and a filter_rate set too high (empty rows);
    • a radius that excludes everything;
    • caller-owned buffers that are exactly big enough, one result short, or short on offsets;
    • max_results: each capped row matches the start of the uncapped row, and buffers sized num_queries * max_results are enough;
    • max_results combined with the ID filter.
  • Argument validation.
  • Dynamic range search for each sync kind: deleted IDs are skipped, the ID filter works, the result limit holds, and fine-grain rejects multi-query batches.

tests/c_api_dynamic_index_sync.cpp now also calls range search in the sequential test and in the concurrent reader threads.

closes #425

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Range-search batching can omit closer in-range neighbors or return unsorted results, and uncaught worker exceptions can terminate the process instead of returning a C API error.

5 open issues
What changed in this PR

Adds approximate range search to the C API, allowing C and FFI consumers to query Vamana indexes by a metric-specific threshold rather than approximating range queries with large top-K requests.

Changes:

  • Adds range search with optional ID filtering and per-query limits across static and dynamic indexes.
  • Centralizes search-result buffer management for top-K and range search.
  • Documents the API and adds coverage for metrics, buffers, filtering, limits, and synchronization modes.
File Description
bindings/​c/​tests/​CMakeLists.txt Registers the new search-results tests.
bindings/​c/​tests/​c_api_search_results.cpp Tests result buffers and range-search behavior.
bindings/​c/​tests/​c_api_dynamic_index_sync.cpp Exercises range search in synchronization workloads.
bindings/​c/​src/​svs_c.cpp Exposes range search and adopts shared result handling.
bindings/​c/​src/​search_results.hpp Adds the internal result-buffer wrapper.
bindings/​c/​src/​index.hpp Adds the virtual range-search interface.
bindings/​c/​src/​index_vamana.hpp Declares Vamana implementations and shared sampling helper.
bindings/​c/​src/​index_vamana.cpp Implements static and dynamic range-search dispatch.
bindings/​c/​src/​filtered_search.hpp Collects range results through batch iterators.
bindings/​c/​README.md Lists range search among supported operations.
bindings/​c/​include/​svs/​c/​svs_c.h Declares and documents the public API.
bindings/​c/​docs/​C_API_Design.md Adds range-search usage and contract details.
bindings/​c/​CMakeLists.txt Registers the result-wrapper header.

Review effort: Balanced

Comment thread bindings/c/src/filtered_search.hpp Resolved
Comment on lines +307 to +311
svs::threads::parallel_for(
index.get_threadpool_handle(),
svs::threads::StaticPartition{queries.size()},
search_closure
);
Comment thread bindings/c/include/svs/c/svs_c.h Resolved
Comment thread bindings/c/src/search_results.hpp Resolved
Comment thread bindings/c/src/search_results.hpp Resolved
@rfsaliev
rfsaliev force-pushed the dev/filtered-range-search branch from f3fd772 to 630c422 Compare November 23, 2026 16:33
do {
iterator.next(batch_size);
for (const auto& neighbor : iterator.results()) {
// Batches are ordered by distance: the first miss ends the range.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each batch is sorted, but a later batch can return closer points, so stopping when a candidate not in range might miss points in later batches. The impact could be larger for range search, current design batch size = search window size, so a radius holds more points than window needs many batches. Maybe have the same stop rule as in #472, which my understanding is look at closest points to expand out of radius instead of iterator result and sort each row before write in result

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, we cannot apply #472 rule here, because iterator's search buffer is private.
Making changes in the code SVS code is out of scope for this PR.
The only we can do - try to call iterator.next() one more time to ensure if there are no more closer neigbors in next batch, but one more iteration negatively affects performance.
Anyway, this PR is made to implement functionality for range searching using batch iterator and is going to be replaced by direct VamanaIndex::range_search call soon.
P.S. The search logic has been taken from svs::runtime::VamanaIndexImpl::range_search() defined in /bindings/cpp/src/vamana_index_impl.h

Comment thread bindings/c/src/filtered_search.hpp Outdated

// A zero estimate means the sampled hit rate is below the filter rate.
if (id_filter != nullptr &&
estimate_initial_batch_size(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we are fixing batch size to be search window size in range search, pre sampling is not needed, it is only used now to get batch size adaptively

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree. Removing.

@rfsaliev
rfsaliev force-pushed the dev/filtered-range-search branch from 630c422 to 20c7f59 Compare December 1, 2026 13:36
@rfsaliev
rfsaliev requested a review from yuejiaointel December 1, 2026 15:04
@rfsaliev
rfsaliev force-pushed the dev/filtered-range-search branch from 7de931d to 382cde6 Compare December 1, 2026 15:47

@yuejiaointel yuejiaointel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, just some minor doc change

Comment thread bindings/c/include/svs/c/svs_c.h Resolved
@rfsaliev
rfsaliev force-pushed the dev/filtered-range-search branch from 382cde6 to 2b66cb4 Compare December 2, 2026 12:49
@rfsaliev
rfsaliev force-pushed the dev/filtered-range-search branch from b109144 to 77aba3d Compare December 3, 2026 14:46

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[C API] Add svs_index_search_range (radius search)

3 participants