Repository navigation
fix(search): embed search queries with Voyage input_type="query" - #469
Conversation
The Voyage provider sent input_type="document" for every embed, including the search query, so semantic search ranked a document-vs-document match. voyage-code-* models embed queries and documents asymmetrically. Measured on a 14k-chunk index of a TypeScript repo, 15 queries that each describe one known function without naming it, ranked by the exact cosine the search SQL computes: query embedded as top-1 top-10 top-90 median rank "query" 11/15 14/15 14/15 1 "document" 0/15 2/15 5/15 355 Through SingleHopStrategy with the real provider the fix reproduces the "query" row exactly (14/15 in the first 90 results, 11/15 first). - interfaces: embed_queries(provider, texts) uses the provider's embed_query when its class defines one, else embed (unchanged behaviour for every other provider; a MagicMock provider keeps its embed). - Voyage: embed_query sends input_type="query"; embed still sends "document" for everything that gets indexed. - EmbeddingManager.embed_query_texts mirrors embed_texts. - Query call sites: SingleHopStrategy (and so multi-hop), the regex-result scoring in SearchService and the research unified search, and DiffAwareSearchService. Gap-query clustering compares queries with each other and is left as is. Tests: provider input_type per path (incl. sub-batching), the helper's fallback, the manager, and that single-hop embeds the query as a query; mutating the call site or the provider back fails them. The related test set (search/research/diff/embed/voyage/rerank/mcp) fails the same 64 tests before and after; the diff-search mocks gained embed_query_texts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@ofriw This PR looks good to me but you probably know voyageAI better than I do... |
ofriw
left a comment
There was a problem hiding this comment.
Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!
PR #469: Voyage query embedding
Verdict: Approve with changes. Six changes remain. Two of them stop the fix from reverting without a test failure.
Line numbers refer to PR head 6c41f2a.
Required changes
1. Make query embedding part of the provider contract
Owner: Embedding interface and concrete providers
Now: embed_queries finds embed_query with getattr(type(provider), ...) and falls back to embed. Mypy cannot see the capability. A reader of EmbeddingProvider cannot see it. A provider that puts embed_query on the instance falls back to embed with no error and no log. That fallback restores the ranking bug.
Change: Add embed_query to EmbeddingProvider next to embed. Follow the supports_reranking and rerank pattern for optional capabilities. Implement it in OpenAIEmbeddingProvider (delegate to embed) and VoyageAIEmbeddingProvider (send input_type="query"). Remove embed_queries and call provider.embed_query at each query site. Keep EmbeddingManager.embed_query_texts as the batch wrapper. The concrete providers do not inherit the protocol, so each one needs the method. Only two concrete providers exist, so a required method costs little. Delete test_embed_queries_ignores_attributes_a_mock_invents with the dispatch. The test asserts MagicMock behavior and pins the type() lookup. The project testing rules forbid that coupling.
Done when: A provider without embed_query fails type checking at the call site. No getattr or type() lookup remains.
Files: chunkhound/interfaces/embedding_provider.py:403, chunkhound/providers/embeddings/openai_provider.py:1021, chunkhound/providers/embeddings/openai_provider.py:1065, chunkhound/embeddings.py:133, chunkhound/services/search/single_hop_strategy.py:64, chunkhound/services/search_service.py:259, chunkhound/services/research/shared/unified_search.py:597, tests/unit/test_query_embedding.py:72
2. Pin each query call site with an asymmetric provider
Owner: Search services and test suite
Now: Only single-hop search asserts the query path. SearchService.search_regex_async, search_by_symbols in the research unified search, and DiffAwareSearchService._search_diff have no such assertion. The suite uses symmetric fakes and MagicMock providers. A revert to embed returns the same vectors, so CI stays green and the ranking bug returns.
Change: Add one test per site with an asymmetric provider. Give the provider different query and document vectors. Assert that the query vector reaches the similarity score. Keep the existing single-hop test.
Done when: Changing any of the four call sites to embed fails a test.
Files: chunkhound/services/search_service.py:259, chunkhound/services/research/shared/unified_search.py:597, chunkhound/services/diff_aware_search_service.py:158, tests/unit/test_query_embedding.py:100
3. Make the Voyage batch input mode required and typed
Owner: Voyage provider
Now: _embed_single_batch and _embed_single_batch_locked default input_type to "document". _embed_as is the only production caller and always passes the mode. The defaults serve tests and let a future caller forget the mode. A query then goes to the API as a document with no error. The "document" literal also has three owners.
Change: Make input_type required on both batch methods. Type _embed_as and both batch methods as Literal["query", "document"]. Keep one "document" literal in embed and one "query" literal in embed_query.
Done when: A missing or invalid input_type fails type checking. Tests pass the mode explicitly.
Files: chunkhound/providers/embeddings/voyageai_provider.py:521, chunkhound/providers/embeddings/voyageai_provider.py:533, chunkhound/providers/embeddings/voyageai_provider.py:554, chunkhound/providers/embeddings/voyageai_provider.py:632
4. Remove the duplicated EmbeddingManager body
Owner: Embedding manager
Now: embed_query_texts repeats embed_texts line for line except for the provider call. This breaks the two-line reuse rule and gives LocalEmbeddingResult two owners.
Change: Extract one private helper that accepts the embed callable. Both public methods pass their provider method and the texts. The helper builds LocalEmbeddingResult once. After change 1, the provider method is embed or embed_query.
Done when: One code path builds LocalEmbeddingResult. The public methods differ only by the provider method they pass.
Files: chunkhound/embeddings.py:97, chunkhound/embeddings.py:122
5. Correct the mypy ignore codes in the diff-research fixture
Owner: Integration test fixture
Now: _embed_texts omits the provider_name parameter. The assignment to embed_query_texts raises mypy [assignment], not [method-assign]. The adjacent embed_texts assignment has the same mismatch. The current ignore code does not cover the error.
Change: Add provider_name: str | None = None to _embed_texts. Keep [method-assign] on both lines, because a matching signature still triggers that error. A plain # type: ignore on both lines is also acceptable.
Done when: uv run mypy reports no error and no unused ignore in this file.
Files: tests/integration/test_deep_research_with_diff.py:81, tests/integration/test_deep_research_with_diff.py:82
6. Document the search-quality fix
Owner: Release notes
Now: The PR changes user-visible search quality and has no changelog entry.
Change: Add one Fixed entry under [Unreleased] in CHANGELOG.md. State that Voyage searches embed queries with input_type="query" and rank better. State that no re-index is needed.
Done when: The entry describes the fix for a user.
Files: CHANGELOG.md:7
Review follow-up for chunkhound#469. - EmbeddingProvider declares embed_query next to embed. The OpenAI provider delegates it to embed; Voyage sends input_type="query". Every query call site calls provider.embed_query, and the getattr/type() dispatch helper embed_queries is gone, so a provider without the method fails type checking instead of silently falling back to document embeddings. - One test per query call site (single-hop, regex scoring, research symbol search, diff search) with a provider whose query and document vectors differ. Reverting any of the four sites to embed fails its test. - Voyage's input_type is a required VoyageInputType Literal on _embed_as and both batch methods; the "document" and "query" literals live only in embed and embed_query. - EmbeddingManager builds LocalEmbeddingResult in one helper. - The diff-research fixture's _embed_texts takes provider_name, so the method-assign ignores cover the real error. - CHANGELOG entry under [Unreleased]. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for the review. All six changes are in 4ffe520, on top of the reviewed head, so nothing was rebased.
On "a provider without Checks, on Windows: |
Search queries go through provider.embed_query once chunkhound#469 lands. The test's Mock provider only had embed as an AsyncMock, so on a tree with both PRs the query embedding raised and the test failed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-up for chunkhound#469. - EmbeddingProvider declares embed_query next to embed. The OpenAI provider delegates it to embed; Voyage sends input_type="query". Every query call site calls provider.embed_query, and the getattr/type() dispatch helper embed_queries is gone, so a provider without the method fails type checking instead of silently falling back to document embeddings. - One test per query call site (single-hop, regex scoring, research symbol search, diff search) with a provider whose query and document vectors differ. Reverting any of the four sites to embed fails its test. - Voyage's input_type is a required VoyageInputType Literal on _embed_as and both batch methods; the "document" and "query" literals live only in embed and embed_query. - EmbeddingManager builds LocalEmbeddingResult in one helper. - The diff-research fixture's _embed_texts takes provider_name, so the method-assign ignores cover the real error. - CHANGELOG entry under [Unreleased]. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Search queries go through provider.embed_query once chunkhound#469 lands. The test's Mock provider only had embed as an AsyncMock, so on a tree with both PRs the query embedding raised and the test failed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ofriw
left a comment
There was a problem hiding this comment.
LGTM. Thank you for this valuable contribution!
Brings in the 21 PRs merged to main since this branch was cut (chunkhound#469 through chunkhound#534). No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in the 21 PRs merged to main since this branch was cut (chunkhound#469 through chunkhound#534). No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two tests mocked interfaces that main has since changed. _inject_diff_service now returns the services alone (chunkhound#407), so the commit-diff test's mock returns services instead of a (services, None) tuple. Semantic search now embeds the query with embed_query (chunkhound#469), so the no-warning test's provider mocks embed_query instead of embed. Both assertions are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
* feat(mcp): add strategy parameter to the search tool Semantic search picks multi-hop whenever the provider can rerank, and the VoyageAI provider always can (rerank-2.5 is the default model). Multi-hop reranks the initial pool, then expands and reranks again until its time limit (5 s by default). MCP callers that rerank results themselves had no way to ask for the plain vector search the CLI exposes as --single-hop. strategy: 'auto' (default, unchanged), 'single_hop', or 'multi_hop', passed through as force_strategy. * fix(mcp): two strategy values, rejected where they cannot apply Review follow-up for chunkhound#462. - Drop "auto". strategy is Literal["single_hop", "multi_hop"] | None and defaults to None, which is forwarded as force_strategy=None, so omitting it keeps choosing by provider capability (multi-hop when the provider can rerank) and a non-reranking provider searches with no warning. - A semantic search that sets strategy together with commit_range, commit_hash or last_n_commits raises ValueError unless vector_source="db". The diff path has no strategies, so the value used to be dropped silently. Same rule as the CLI's --single-hop/--multi-hop. - An unknown strategy raises ValueError naming the valid values, before any service work. The Literal stays for the schema. - Tests cover the two-value schema, forwarding of both values and of an omitted one, regex ignoring strategy, the unknown value, each commit argument with vector_source diff and both, the db exception, and the no-warning default. The docstring states the single-hop fallback instead of "requires". Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(mcp): give the no-warning test's provider an awaitable embed_query Search queries go through provider.embed_query once chunkhound#469 lands. The test's Mock provider only had embed as an AsyncMock, so on a tree with both PRs the query embedding raised and the test failed. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(mcp): describe the search strategy parameter where clients read it Name `strategy` in both search tool descriptions, state the real regex rule (a valid value has no effect, an invalid one raises), list every ValueError in the docstring, and replace the guard comment with the MCP rule, which differs from the CLI's. Drop the embed_query mock that nothing on this branch calls, and collapse the blank-line seam. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(mcp): fit the strategy tests to main's search changes Two tests mocked interfaces that main has since changed. _inject_diff_service now returns the services alone (chunkhound#407), so the commit-diff test's mock returns services instead of a (services, None) tuple. Semantic search now embeds the query with embed_query (chunkhound#469), so the no-warning test's provider mocks embed_query instead of embed. Both assertions are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Problem
The Voyage provider sends
input_type: "document"on every embed request, including the embedding of a search query. Voyage's code models embed queries and documents asymmetrically, so semantic search currently ranks a document-to-document match against the indexed chunks. The right chunk often ends up far down the list.Measurement
I used a 14,259-chunk index of a TypeScript/Markdown repo, embedded with
voyage-code-4at 1024 dimensions. There are 15 queries, and each describes one known function in plain words without naming it, for example "work out which git branch an implement worktree should be based on". Each query was embedded both ways and ranked by the exact cosine the search SQL computes:querydocument(current)With this change, running the same 15 queries through
SingleHopStrategywith the real provider reproduces thequeryrow exactly: 14 of 15 targets in the first 90 results, and 11 ranked first.Change
chunkhound/interfaces/embedding_provider.py: a newembed_queries(provider, texts). It calls the provider'sembed_querywhen the provider's class defines one, and falls back toembedotherwise. Every other provider behaves exactly as before. The lookup is on the class, so aMagicMockprovider keeps using itsembed.VoyageAIEmbeddingProvider.embed_querysendsinput_type: "query".embedstill sends"document"for everything that gets indexed. Both share the existing sub-batching path.EmbeddingManager.embed_query_textsmirrorsembed_texts.SingleHopStrategy, which multi-hop builds on;SearchService;unified_search;DiffAwareSearchService.gap_detection.pycompares queries with each other, not with chunks, so it is unchanged.No re-index is needed. Stored vectors were and remain document embeddings.
Tests
tests/unit/test_voyageai_provider.py::TestVoyageQueryInputType:embedsendsdocument,embed_querysendsquery(including when it sub-batches), and empty input makes no call.tests/unit/test_query_embedding.py: the helper's query path and fallback, theMagicMockcase, the manager, and that single-hop search embeds its query as a query.embed, or makingembed_querysenddocument, fails these tests.embed_query_textsnext toembed_texts. Two existing tests that stub the private_embed_single_batchnow accept its newinput_typeargument.Other providers with asymmetric query/document modes could implement
embed_querythe same way. I've only touched Voyage, the one I could measure.🤖 Generated with Claude Code