Skip to content

feat(filtered_search): Cancel predicate and completion flag for filtered Vamana search - #502

Open
rfsaliev wants to merge 1 commit into
rfsaliev/filtered-searchfrom
rfsaliev/predicated-search
Open

rfsaliev wants to merge 1 commit into
rfsaliev/filtered-searchfrom
rfsaliev/predicated-search

Conversation

@rfsaliev

@rfsaliev rfsaliev commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

Cancel predicate and completion flag for Vamana search

Summary

Lets a caller end a Vamana search early and learn that it happened. The C API uses this to enforce the filter hit rate inside the graph search, so filtered top-k search no longer needs the batch iterator.

Stacked on #489 (filtered search in the graph), which must merge first. This PR adds one commit on top of it.

Behaviour

  • cancel is called before each query and before each graph hop of a query.
  • A query that cancel ends keeps the results it found so far.
  • A query that starts while cancel holds returns an empty row. Before this PR it returned its entry points.
  • search() and filtered_search() return true if every query ran to completion and false if any ended early.

API

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

template <typename Query, typename Cancel = lib::ReturnsFalseType>
bool search(const Query& query, scratchspace_type& scratch, const Cancel& cancel = Cancel{}) const;

template <typename I, data::ImmutableMemoryDataset Queries,
          typename Cancel = lib::ReturnsFalseType, typename Filter = AcceptAll>
bool search(
    QueryResultView<I> result, const Queries& queries, const search_parameters_type& sp,
    const Cancel& cancel = Cancel{}, const Filter& filter = AcceptAll{}
);

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

template <typename QueryType>
bool filtered_search(
    QueryResultView<size_t> results, data::ConstSimpleDataView<QueryType> queries,
    const VamanaSearchParameters& search_parameters,
    const lib::DefaultPredicate& cancel, const std::function<bool(size_t)>& filter
);

New helper, svs::HitRateFilter (include/svs/core/filter.h):

const auto hit_rate = svs::HitRateFilter{filter, min_rate, min_calls};
const bool completed =
    index.filtered_search(results, queries, params, hit_rate.cancel(), hit_rate.filter());
  • filter() is the wrapped filter, counting each check and whether it passed.
  • cancel() holds once min_calls checks were made and less than min_rate of them passed.
  • The counts are shared by all queries and threads searching with it.

Changes

  • Search loop (greedy_search.h, both variants): greedy_search() takes the termination rule in place of cancel. DefaultStop is buffer.done(); EarlyStop{base, early} adds a no-argument early-stop predicate. The loop is while (!stop(search_buffer)).
  • Index search closures (index.h, dynamic_index.h, concurrent/dynamic_index.h): greedy_search_closure() takes the early-stop and completion predicates, checks the early one before starting a query, and records whether the query ran to completion.
  • Extension points (extensions.h): single_search() and per_thread_batch_search() lose their index and cancel parameters. Overloads of these extension points must drop them too.
  • Buffer top-up: moved from the search extension points to BatchIteratorBase::next(), its only user. This part is already on main (refactor(search): Top-up search-buffer for BatchIterator only #498) and leaves the diff after a rebase.
  • Orchestrators (vamana.h, dynamic_vamana.h): filtered_search() takes cancel before filter and returns the completion flag.
  • lib::ReturnsFalseType (lib/misc.h), next to ReturnsTrueType.
  • C API (bindings/c/src/filtered_search.hpp): filtered top-k search always filters inside the graph search.
    • Without a filter_rate estimate, nothing is enforced.
    • With an estimate, the hit rate is checked on a sample of IDs before the search, as before, and by HitRateFilter during it. A rate below the estimate returns no results for the whole call.
    • The minimum number of checks scales with the number of queries running side by side, because they all start with the same IDs around the entry points.

Compatibility

Testing

  • tests/utils/filtered_search.h: check_cancelled_search() is shared by the three indices and their orchestrators. It checks:
    • a predicate that never fires leaves recall and the completion flag untouched;
    • a predicate following a filter that passes nothing ends the search long before the graph is traversed;
    • cancelling at once leaves every row empty;
    • cancelling mid-call keeps valid results for queries in flight and leaves later rows empty.
  • tests/svs/core/filter.cpp: unit test for HitRateFilter, including counting from several threads.
  • tests/svs/index/vamana/search_buffer.cpp: DefaultStop and EarlyStop on a plain buffer.
  • C API tests: the filtered top-k cases use distinct random vectors, and a new section covers a filter_rate above the hit rate seen during the search.

Passing: [filter], [filtered], [cancel], [iterator], [search_buffer] and the C API suite (30 consecutive runs).

Performance

Not measured yet on this commit. The change touches the greedy_search loop condition, so static and dynamic search QPS and the batch iterator need an A/B run against the base before merge.

Notes for reviewers

  • The early-stop predicate takes no arguments on purpose: only the completion rule needs the buffer. A range search can then reuse the same closure with its own completion rule.
  • The hit-rate counts include repeated checks of an ID and are shared by all queries of a call. That is accurate enough to detect an overestimated filter_rate, which is all the C API contract needs.
  • The memory estimator comments in bindings/c/src/index_builder.cpp still describe the iterator path; they are left for a follow-up.

🤖 Generated with Claude Code

if (!completed) {
// TODO: clarify the contract here - should we return partial or no
// result if the hit rate is too low
set_empty_result(results);

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.

This would clear results for entire batch, if one query got cancelled. Previous design which only empty the cancelled query make more sense. Maybe either have a for loop to empty queries that have less than k results here or check inside the search per query by passing a checker to search per query

// C API: pass a factory instead of one shared HitRateFilter
auto make_hit_rate = [&] { return svs::HitRateFilter{*id_filter, filter_rate, sample_size}; };
index.filtered_search(results.view(), queries, params, make_hit_rate);

// index.h, inside greedy_search_closure (runs once per query):
auto hr = make_hit_rate();                                  // this query's own counters
greedy_search(..., internal_search_builder(hr.filter()), prefetch,
              EarlyStop{done, hr.cancel()});
if (hr.cancel()) { buffer.clear(); }                        // gave up → empty only this row

@rfsaliev rfsaliev Dec 4, 2026 •

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.

Imho, the contract have to be changed to return all available results even if search was cancelled or stopped due filter hit rate - let user decide if a result to be ignored if it's size is less than K.
I think it should be common for both TopK and Range searches (where results.apply() is called) and I want to apply such change in next steps after range search optimization.
For now - just keeping the change as simple as possible.

@rfsaliev
rfsaliev force-pushed the rfsaliev/predicated-search branch 2 times, most recently from c16212d to 7df64de Compare December 4, 2026 17:55
Let a caller end a Vamana search early and learn that it happened, and
use that to enforce the filter hit rate in the C API without the batch
iterator.

Index search (static, dynamic, concurrent):
- `cancel` is a template parameter (default: never) called before each
  query and before each graph hop of a query. A query it ends keeps the
  results found so far; a query starting while it holds gets an empty
  row instead of its entry points.
- `search()` returns `true` if every query ran to completion and
  `false` if any ended early.
- `greedy_search()` takes the termination rule (`DefaultStop`,
  `EarlyStop`) in place of `cancel`.
- `single_search()` and `per_thread_batch_search()` lose their `index`
  and `cancel` parameters; overloads of these extension points must
  drop them too. The buffer top-up moves to `BatchIteratorBase::next()`,
  its only user.

Orchestrators:
- `filtered_search(results, queries, params, cancel, filter)` on
  `svs::Vamana` and `svs::DynamicVamana` takes the predicate and
  returns the completion flag.

Helpers:
- `svs::HitRateFilter` (core/filter.h) wraps an ID filter, counts its
  checks and hits across threads, and provides the matching cancel
  predicate.
- `lib::ReturnsFalseType`.

C API:
- Filtered top-k search always filters inside the graph search. With a
  `filter_rate` estimate, the search is cancelled once the observed hit
  rate falls below it, and the call then returns no results, as before.

Tests: shared `check_cancelled_search()` for the three indices and both
orchestrators, a unit test for `HitRateFilter`, and C API tests on
distinct random vectors with a case for an overestimated filter rate.

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.

2 participants