(RFC) Refactor search interface with unified SearchDispatch trait#773
(RFC) Refactor search interface with unified SearchDispatch trait#773narendatha wants to merge 9 commits intomainfrom
Conversation
- Add SearchDispatch trait for unified search entry point - Split search types into separate files (graph_search, range_search, multihop_search, diverse_search) - Rename execute_search to search, parameters to search_params - Rename search_recorded to debug_search to signal debug-only intent - Move internal implementations to respective search type files - Add From impls for SearchParams/RangeSearchParams to new types - Add test helper functions in test modules for backwards compat - Bump version to 0.46.0
There was a problem hiding this comment.
Pull request overview
This PR refactors the search interface in the diskann crate to provide a unified entry point via the SearchDispatch trait. The refactoring improves code organization by moving search implementations to dedicated files and consolidates the API around a single index.search() method that dispatches to type-specific implementations.
Changes:
- Introduces
SearchDispatchtrait as the unified search interface, with separate implementations for standard graph search, range search, multihop (label-filtered) search, and diversity-aware search - Replaces multiple search methods (
execute_search,multihop_search,range_search) with a singlesearch()method that delegates toSearchDispatch::dispatch() - Renames
search_recordedtodebug_searchto clearly signal debug-only intent - Maintains backward compatibility by implementing
SearchDispatchfor the legacySearchParamstype
Reviewed changes
Copilot reviewed 16 out of 17 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
diskann/src/graph/search/dispatch.rs |
Core SearchDispatch trait definition |
diskann/src/graph/search/graph_search.rs |
Standard k-NN graph search implementation (GraphSearch, RecordedGraphSearch) |
diskann/src/graph/search/range_search.rs |
Range-based search implementation and range_search_internal helper |
diskann/src/graph/search/multihop_search.rs |
Label-filtered search and multihop_search_internal helper, includes NotInMutWithLabelCheck predicate |
diskann/src/graph/search/diverse_search.rs |
Feature-gated diversity-aware search implementation |
diskann/src/graph/search/mod.rs |
Module organization with public re-exports |
diskann/src/graph/mod.rs |
Top-level re-exports of search types |
diskann/src/graph/index.rs |
New unified search() method, renamed debug_search(), removed old search methods, made internal helpers pub(crate) |
diskann/src/graph/test/cases/grid.rs |
Updated to use GraphSearch::new() and params.k |
diskann-providers/src/index/diskann_async.rs |
Test helper functions for backward-compatible multihop and range search calls |
diskann-providers/src/index/wrapped_async.rs |
Converts SearchParams to GraphSearch for unified API |
diskann-disk/src/search/provider/disk_provider.rs |
Updated to use GraphSearch and renamed debug_search |
diskann-benchmark-core/src/search/graph/*.rs |
Updated benchmark code to use new search dispatch API |
Cargo.toml, Cargo.lock |
Version bump to 0.46.0 across all workspace crates |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This enables RecordedGraphSearch to implement SearchDispatch properly, since it holds &mut recorder which requires mutable access. - Change dispatch signature from &self to &mut self - Update index.search to take &mut P for search params - Implement SearchDispatch for RecordedGraphSearch - Remove apologetic comment about trait limitations - Update all callers to use &mut params
- RecordedGraphSearch in graph_search.rs - MultihopSearch in multihop_search.rs
|
@microsoft-github-policy-service agree [company="Microsoft"]
From: microsoft-github-policy-service[bot] ***@***.***>
Sent: 12 February 2026 22:27
To: microsoft/DiskANN ***@***.***>
Cc: Naren Datha ***@***.***>; Mention ***@***.***>
Subject: Re: [microsoft/DiskANN] (RFC) Refactor search interface with unified SearchDispatch trait (PR #773)
[https://avatars.githubusercontent.com/in/95686?s=20&v=4]microsoft-github-policy-service[bot] left a comment (microsoft/DiskANN#773)<#773 (comment)>
@narendatha<https://github.com/narendatha> please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.
@microsoft-github-policy-service agree [company="{your company}"]
Options:
* (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
* (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term "You" includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement
Contribution License Agreement
This Contribution License Agreement ("Agreement") is agreed to by the party signing below ("You"),
and conveys certain license rights to Microsoft Corporation and its affiliates ("Microsoft") for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.
1. Definitions.
"Code" means the computer software code, whether in human-readable or machine-executable form,
that is delivered by You to Microsoft under this Agreement.
"Project" means any of the projects owned or managed by Microsoft and offered under a license
approved by the Open Source Initiative (www.opensource.org<http://www.opensource.org/>).
"Submit" is the act of uploading, submitting, transmitting, or distributing code or other content to any
Project, including but not limited to communication on electronic mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
discussing and improving that Project, but excluding communication that is conspicuously marked or
otherwise designated in writing by You as "Not a Submission."
"Submission" means the Code and any other copyrightable material Submitted by You, including any
associated comments and documentation.
2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
Project. This Agreement covers any and all Submissions that You, now or in the future (except as
described in Section 4 below), Submit to any Project.
3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
Should You wish to Submit materials that are not Your original work, You may Submit them separately
to the Project if You (a) retain all copyright and license information that was in the materials as You
received them, (b) in the description accompanying Your Submission, include the phrase "Submission
containing materials of a third party:" followed by the names of the third party and any licenses or other
restrictions of which You are aware, and (c) follow any other instructions in the Project's written
guidelines concerning Submissions.
4. Your Employer. References to "employer" in this Agreement include Your employer or anyone else
for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
Submission is made in the course of Your work for an employer or Your employer has intellectual
property rights in Your Submission by contract or applicable law, You must secure permission from Your
employer to make the Submission before signing this Agreement. In that case, the term "You" in this
Agreement will refer to You and the employer collectively. If You change employers in the future and
desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
and secure permission from the new employer before Submitting those Submissions.
5. Licenses.
* Copyright License. You grant Microsoft, and those who receive the Submission directly or
indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
parties.
* Patent License. You grant Microsoft, and those who receive the Submission directly or
indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
Your patent claims that are necessarily infringed by the Submission or the combination of the
Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
import or otherwise dispose of the Submission alone or with the Project.
* Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
granted by implication, exhaustion, estoppel or otherwise.
1. Representations and Warranties. You represent that You are legally entitled to grant the above
licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
have disclosed under Section 3). You represent that You have secured permission from Your employer to
make the Submission in cases where Your Submission is made in the course of Your work for Your
employer or Your employer has intellectual property rights in Your Submission by contract or applicable
law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
You later become aware that would make Your representations in this Agreement inaccurate in any
respect.
3. Information about Submissions. You agree that contributions to Projects and information about
contributions may be maintained indefinitely and disclosed publicly, including Your name and other
information that You submit with Your Submission.
4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
defenses of lack of personal jurisdiction and forum non-conveniens.
5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
supersedes any and all prior agreements, understandings or communications, written or oral, between
the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.
-
Reply to this email directly, view it on GitHub<#773 (comment)>, or unsubscribe<https://github.com/notifications/unsubscribe-auth/BHEGNRFCSW65WVLE4ABQKE34LSWEHAVCNFSM6AAAAACU5OD4WWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZTQOJSGEZDCMJSGU>.
You are receiving this because you were mentioned.Message ID: ***@***.******@***.***>>
|
hildebrandmw
left a comment
There was a problem hiding this comment.
Thanks @narendatha! I think this does a good job of tying together the disparate APIs we've gathered. I'm pretty strongly in favor of getting rid of the legacy SearchParams and RangeSearchParams to avoid clutter, and updating the structs defined in this PR to not expose all the methods as public and therefore render the constructor invariant checks invalid.
- Rename SearchDispatch trait to Search and move to mod.rs - Remove unnecessary doc comment about &mut self (can be inferred) - Remove 'feature-gated' mention from diverse_search.rs module doc - Fix banner styles to use ///// format instead of //=== - Make create_diverse_scratch an inherent method on DiverseSearch - Remove flat_search mention from index.search docs - Redirect debug_search to use RecordedGraphSearch internally - Revert version bump (0.46.0 -> 0.45.0) Co-authored-by: hildebrandmw <hildebrandmw@users.noreply.github.com>
|
@microsoft-github-policy-service agree company="Microsoft" |
…roUsize - Rename GraphSearch to KnnSearch for clarity (k-NN search) - Change k_value and l_value from usize to NonZeroUsize (compile-time zero check) - Rename RecordedGraphSearch to RecordedKnnSearch - Move RangeSearch validation from misc.rs to range_search.rs - Remove deprecated SearchParams, SearchParamsError, RangeSearchParams, RangeSearchParamsError - Update all callers across diskann, diskann-providers, diskann-disk, diskann-benchmark crates - Remove ensure_positive helper (no longer needed with NonZeroUsize) - Fix duplicated cfg attribute in diverse_search.rs
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #773 +/- ##
==========================================
- Coverage 90.29% 89.00% -1.30%
==========================================
Files 428 431 +3
Lines 78420 78496 +76
==========================================
- Hits 70809 69865 -944
- Misses 7611 8631 +1020
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
…e diverse_search_experimental, use DiverseSearch + search() directly
hildebrandmw
left a comment
There was a problem hiding this comment.
Thanks @narendatha, I'm really liking how this is coming together!
| /// - [`search::KnnSearch`]: Standard k-NN graph-based search | ||
| /// - [`search::MultihopSearch`]: Label-filtered search with multi-hop expansion | ||
| /// - [`search::RangeSearch`]: Range-based search within a distance radius | ||
| /// - [`search::DiverseSearch`]: Diversity-aware search (feature-gated) |
There was a problem hiding this comment.
Quick naming/export observation, I'd like to hear your thoughts. The links here scope the search parameters to the search module, but they are also re-exported through graph.
There is a world where we structure it like
diskann::graph::search::KNN;
diskann::graph::search::MultiHop;
diskann::graph::search::Range;
diskann::graph::search::Diverse;
That is, we can drop the Search suffixes, use the module for namespacing, and do not reexport through graph (the Search trait itself should probably be reexported though).
What do you think?
| /// let result = index.search(&strategy, &context, &query, &mut params, &mut ()).await?; | ||
| /// // result.ids and result.distances contain the matches | ||
| /// ``` | ||
| pub fn search<'a, S, T, O: 'a, OB, P>( |
There was a problem hiding this comment.
IMO, search_params should probably come first now since it's the most important argument at this level for determining what kind of search is about to get run.
| strategy: &'a S, | ||
| context: &'a DP::Context, | ||
| query: &'a T, | ||
| search_params: &'a mut P, |
There was a problem hiding this comment.
Taking search_params by mutable reference is a bit unfortunate for the caller. I know why we did this, but it has an unfortunate side-effect of making it harder to work with in cases where mutability is not needed.
To that end, what if we do this:
- Take
search_paramsby value. - Implement
Searchfor bothKnnSearchand&KnnSearch- making sure thatKnnSearchby value simply delegates to the&KnnSearchimplementation.
It does make generic plumbing when mutability is required more tricky (i.e., we'd need HRTB all over the place), but I think that might be preferable to always forcing mutability?
| /// # Errors | ||
| /// | ||
| /// Returns an error if there is a failure accessing elements or computing distances. | ||
| fn dispatch<'a>( |
There was a problem hiding this comment.
You can drop the explicit lifetime 'a here. Additionally, when you drop the lifetime, you will be able to get rid of the explicit lifetime in DiskANNIndex::search as well.
| /// # Errors | ||
| /// | ||
| /// Returns an error if there is a failure accessing elements or computing distances. | ||
| fn dispatch<'a>( |
There was a problem hiding this comment.
Small preference for calling this method search, following the convention of traits having a single method named after themselves.
| /// | ||
| /// let mut params = KnnSearch::new(10, 100, None)?; | ||
| /// let stats = index.search(&strategy, &context, &query, &mut params, &mut output).await?; | ||
| /// ``` |
There was a problem hiding this comment.
I'd say that 90% of the time, I'm a fan of attaching documentation to the trait implementations and allowing that to be discovered while perusing rustdoc.
However, this feels like a situation where the algorithmic level documentation would be more discoverable if attached to the KnnSearch struct (and other searchers) themselves or as module-level documentation. The trait-impl can then include a cross-reference to the struct level documentation.
Basically - these structs exist almost exclusively to implement Search. So struct-level documentation feels appropriate.
Thinking of how this would look for users of the docs, I think it's cleaner. What do you think?
| } | ||
|
|
||
| impl From<KnnSearchError> for ANNError { | ||
| fn from(err: KnnSearchError) -> Self { |
There was a problem hiding this comment.
Recommend attaching #[track_caller] to all conversions to ANNError as it will improve the quality of the error message if backtraces are not collected.
| /// Search list size - controls accuracy vs speed tradeoff. | ||
| l_value: NonZeroUsize, | ||
| /// Optional beam width for parallel graph exploration. | ||
| beam_width: Option<usize>, |
There was a problem hiding this comment.
Since beam_width cannot be zero, we can embed it in an Option<NonZeroUsize> to formalize the guarantee.
| diskann::graph::SearchParams::new(run.search_n, *search_l, None).unwrap(); | ||
| let k = NonZeroUsize::new(run.search_n).expect("search_n must be non-zero"); | ||
| let l = NonZeroUsize::new(*search_l).expect("search_l must be non-zero"); | ||
| let search_params = diskann::graph::KnnSearch::new(k, l, None).unwrap(); |
There was a problem hiding this comment.
One small thing I noticed: since KnnSearch::new already checks the k <= l invariant, we could also check for non-zero there and simplify the caller's life.
This is especially relevant because I'm seeing expect being applied to the NonZeroUsize constructors where-as before those paths wouldn't necessarily panic.
Refactor search interface with unified SearchDispatch trait
Summary
This PR refactors the search interface in
diskannto provide a unified entry point via theSearchDispatchtrait, improving code organization and API clarity. This also removes (un)popular SearchParams and search specific structs. This PR also removes (un)popular SearchParamsand replaces with search specific structs, so it is clear what params are used and which ones are ignored.Changes
New Architecture
SearchDispatchtrait - A unified dispatch interface that all search types implement, enabling a singleindex.search()entry pointdispatch.rs- Core trait definitiongraph_search.rs- Standard k-NN graph search (GraphSearch,RecordedGraphSearch)range_search.rs- Range-based search (RangeSearch,RangeSearchOutput)multihop_search.rs- Label-filtered search (MultihopSearch)diverse_search.rs- Diversity-aware search (DiverseSearch, feature-gated)API Changes
index.execute_search(..., parameters, ...)index.search(..., search_params, ...)index.search_recorded(...)index.debug_search(...)search()with dispatchCode Organization
range_search_internal,multihop_search_internal) to their respective search type filesNotInMutWithLabelCheckhelper tomultihop_search.rsFromimpls forSearchParams->GraphSearchandRangeSearchParams->RangeSearchgraph_search,multihop_search,range_search) fromDiskANNIndexto avoid encouraging direct useOther
search_recorded->debug_searchto clearly signal debug-only intentUsage Example
Why flat_search is not included
flat_searchremains a separate method because it has unique constraints incompatible withSearchDispatch: (1) it requires an additional generic boundSearchAccessor<'a>: IdIterator<I>that forces the strategy's accessor to support iteration over all IDs - a capability not all strategies provide, and (2) it takes an extravector_filterclosure parameter that other search types don't need. Sinceflat_searchis fundamentally a linear scan with filtering rather than a graph traversal, keeping it as a distinct method with its own signature is cleaner than complicating the trait to accommodate it.Testing
cargo build --workspacecargo test -p diskann -p diskann-providers -p diskann-disk