Skip to content

feat(search): Implement range search in core Vamana index classes - #507

Open
rfsaliev wants to merge 2 commits into
rfsaliev/predicated-searchfrom
rfsaliev/range-search-internally
Open

rfsaliev wants to merge 2 commits into
rfsaliev/predicated-searchfrom
rfsaliev/range-search-internally

Conversation

@rfsaliev

@rfsaliev rfsaliev commented Dec 4, 2026

Copy link
Copy Markdown
Member

feat(search): Implement range search in core Vamana index classes

Summary

Adds range_search(): for each query, return the neighbors strictly closer than a radius instead of a fixed number of them. It is available on the three Vamana indices, on their orchestrators and, through them, in the C API, where it replaces the batch-iterator loop behind svs_index_search_range() (#480). Results come back in a new CSR container, svs::RangeQueryResult, and a new extension point, per_thread_range_search, lets a dataset that searches on approximate distances run the search its own way.

Stacked on #502 (cancel predicate and completion flag), which must merge first.

Behaviour

  • A neighbor is within the radius when compare(distance, radius) holds: distance < radius for L2, similarity > radius for inner product and cosine. A neighbor at exactly the radius is not returned. This is the rule of the published runtime bindings.
  • The search window sets the effort, as in top-k search: the search visits the window, then goes on for as long as an unvisited candidate lies within the radius.
  • The total buffer capacity limits a row to the nearest neighbors found. svs::index::vamana::no_result_limit returns all of them. Reaching the limit is a completed search.
  • Rows are sorted from the nearest neighbor to the furthest.
  • cancel and filter work as in search() (feat(filtered_search): Cancel predicate and completion flag for filtered Vamana search #502): a cancelled query keeps what it found, a query that starts while cancel holds has an empty row, and the call returns false.
  • Dynamic indices never return deleted points. The concurrent index drops a neighbor consolidated while the search ran and checks the filter again on the final IDs.
  • A search window of zero throws ANNException.

API

Index level (VamanaIndex, MutableVamanaIndex, concurrent::MutableVamanaIndex):

template <data::ImmutableMemoryDataset Queries,
          typename Cancel = lib::ReturnsFalseType, typename Filter = AcceptAll>
bool range_search(
    RangeQueryResult<size_t>& results,
    const Queries& queries, float radius, const search_parameters_type& sp,
    const Cancel& cancel = Cancel{}, const Filter& filter = AcceptAll{}
);

Orchestrators (svs::Vamana, svs::DynamicVamana, svs::ConcurrentDynamicVamana):

template <typename QueryType>
bool range_search(
    RangeQueryResult<size_t>& results,
    data::ConstSimpleDataView<QueryType> queries, float radius,
    const VamanaSearchParameters& search_parameters,
    const lib::DefaultPredicate& cancel = lib::ReturnsFalseType{},
    const std::function<bool(size_t)>& filter = {}
);

VamanaInterface gains range_search() as its last virtual.

Results: RangeQueryResult

include/svs/core/query_result.h adds the counterpart of QueryResult for rows of
unequal length, in compressed-row form: offsets(), indices(), distances() over all
results, and indices(query) / distances(query) / index(q, j) / distance(q, j) per
query. One allocation per array instead of one std::vector per query, and the arrays can
be handed to a C caller as they are.

Each thread of a call collects into its own RangeQueryRows<Idx>, a staging block for the
contiguous range of queries that thread owns; assign(n_queries, blocks) turns the blocks
into the prefix sum and moves the single-block case instead of copying it.

Extension point: per_thread_range_search

extensions::per_thread_range_search(data, buffer, scratch, queries, thread_indices, search, collect) is to range search what per_thread_batch_search is to top-k: it owns
the loop over the queries of one thread and calls collect() after each query, with the
buffer holding the final sorted candidates. The default implementation loops
single_search + collect(), so a dataset that needs nothing special gets the previous
behaviour. Scratch comes from per_thread_batch_search_setup.

A dataset that searches on approximate distances and reranks them needs this hook: the
radius it has to follow during the search is not the radius of the results. RangeBuffer
therefore keeps the two apart - radius() for what is returned, search_radius() (with
set_search_radius()) for how far the search goes - and result_limit() is applied after
reranking.

Design

include/svs/index/vamana/range_search.h adds RangeBuffer<Idx, Cmp>, derived from MutableBuffer. It shadows four members and leaves the base class untouched:

  • done(): the search window was visited and no unvisited candidate is within the radius.
  • next() and sort(): look for the best unvisited candidate in the whole buffer. The base class stops at the end of the search window.
  • can_skip(): a candidate outside of the search radius is kept only if it enters the search window.

Why a buffer and not a stop predicate for greedy_search():

  • The top-k path does not change. MutableBuffer, SearchBuffer, the greedy search and the batch iterator compile to the same code as before.
  • A predicate cannot decide what to keep. With no result limit, a plain buffer keeps every candidate it is offered, in sorted order: it grows to the whole neighborhood the search touched and pays a memmove per insertion. can_skip() keeps the buffer at the neighbors within the radius plus the search window.

The search itself is the existing one: greedy_search_closure() and the single_search extension point are called with the new buffer type, so storage extensions that are generic over the buffer work without changes. The Done parameter that #502 added to greedy_search_closure() for this purpose is not used and can be dropped there.

"No limit" is the capacity no_result_limit (INT64_MAX), because MutableBuffer computes its slack as a signed number. The buffer allocates for the search window only.

Known cost: with no result limit and a radius that covers a large part of the index, the buffer holds all of those neighbors in sorted order, so insertion is linear in their number. max_results bounds it.

Changes

  • include/svs/index/vamana/range_search.h (new): no_result_limit, check_range_search_config(), RangeBuffer.
  • include/svs/core/query_result.h: RangeQueryResult, RangeQueryRows.
  • include/svs/index/vamana/extensions.h: per_thread_range_search and its default implementation.
  • index.h, dynamic_index.h, concurrent/dynamic_index.h: range_search(). In the concurrent index, the filter re-check of search() moved to a helper, recheck_filter(), now that it has two callers.
  • orchestrators/vamana.h, dynamic_vamana.h: interface, implementation and wrappers. An empty filter calls the unfiltered overload.
  • C API: see below.

C API

svs_index_search_range() now calls range_search(). Its contract changes from the batch-iterator version of #480 in these points to match CPP Runtime rules:

Before (#480) Now
Radius inclusive exclusive
radius <= 0 or NaN accepted SVS_ERROR_INVALID_ARGUMENT, for every metric
Row order not guaranteed closest first
Search window batch size of the iterator search effort
Hit rate below filter_rate success, affected rows empty SVS_ERROR_FILTER_TOO_STRICT, rows keep the neighbors found so far
  • max_results (0 = no limit) limits the rows. The search buffer capacity of the search parameters is not used.
  • New error codes: SVS_ERROR_FILTER_TOO_STRICT = 10, and SVS_ERROR_CANCELLED = 9, which is only reserved here for the cancel interface of [C API] Add cancellation callback to search parameters #484.
  • The hit rate is checked as in top-k search: on a sample of IDs before the search, then on the filter checks of all queries of the call (svs::HitRateFilter).
    • Before the search: max(200, 1 / filter_rate) IDs, and the check is skipped when that exceeds 1000, i.e. for a filter_rate below 0.001. An index worth a range search holds far more than 1000 vectors, so a sample of 1000 is enough to tell a filter that passes one ID in a thousand from one that passes none; paying more filter calls up front than the search itself would is not.
    • During the search: a verdict after max(max_results, 200, 1 / filter_rate) checks per query being searched at a time. The result limit belongs here, not in the sample: it says how many IDs the caller is willing to have checked.
  • Top-k search is not changed: a hit rate below the estimate still returns success with empty rows there. Aligning the two is a separate change.
  • The radius rule means that similarity thresholds of zero and below are not available for inner product and cosine. It follows the runtime bindings and is documented in the header and in C_API_Design.md.

Testing

  • tests/svs/core/query_result.cpp (new): RangeQueryResult and RangeQueryRows - empty rows, one block, several blocks, the prefix sum, per-query views.
  • tests/svs/index/vamana/search_buffer.cpp: "RangeBuffer" covers each rule on hand-made candidates, including a search radius and a result limit of their own. "Fuzzing Range" replays random interleavings of insertions and visits, for less and greater and for several windows and limits, checking the invariants after every step and the final rows against the best in-radius candidates offered.
  • tests/utils/filtered_search.h: check_range_search(), shared by the three indices and their orchestrators, checks every row against an exhaustive scan: recall, exclusive radius, filter, limit, empty radius, fewer passing labels than the search window, cancellation at once and mid-call, zero window.
  • Dynamic and concurrent index: relabeled entries, deleted entries before and after consolidation.
  • tests/svs/concurrent/concurrency.cpp: range search while writers add, delete and relabel.
  • C API: exclusive radius, invalid radii for each metric, limit below and above the search window, both hit-rate failures (on the sample, with empty rows; during the search, with partial rows), for the static index and the three sync kinds of the dynamic one.

The range tests build their indices with a larger window than the filtered tests (range_build_parameters()): a range search returns most of what it visits, so the quick build gives recall around 0.8 where this one gives 0.9 and more.

Run on this branch, on top of the head of #502:

  • [range],[query_result],[search_buffer],[translation],[cancel],[filtered],[filter]: 29 test cases pass;
  • [concurrent]: 33 test cases pass;
  • the C API suite: 32 test cases pass;
  • pre-commit is clean.

The full public suite passed (227 test cases) before the last round of changes, which added RangeQueryResult, per_thread_range_search and the sample cap; it was not rerun since.

🤖 Generated with Claude Code

rfsaliev and others added 2 commits December 4, 2026 19:31
Add range_search() to VamanaIndex, MutableVamanaIndex and
concurrent::MutableVamanaIndex, and to their orchestrators: for each
query, return the neighbors strictly within a radius, closest first.

- RangeBuffer: a MutableBuffer that searches past the window while
  candidates are within the radius, with separate result and search
  radii and a result limit.
- RangeQueryResult/RangeQueryRows: CSR results for rows of any length.
- per_thread_range_search: new extension point; default loops
  single_search().
- C API: svs_index_search_range() uses range_search() instead of the
  batch iterator; exclusive radius, radius > 0, sorted rows, new
  SVS_ERROR_FILTER_TOO_STRICT and reserved SVS_ERROR_CANCELLED.
Follows the lock-free internal->external translation in
concurrent::MutableVamanaIndex: collecting a range search row no longer takes
translator_mutex_.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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.

1 participant