Skip to content

fix(search): embed search queries with Voyage input_type="query" - #469

Merged
ofriw merged 2 commits into
chunkhound:mainfrom
fstrasz:fix/voyage-query-input-type
Nov 8, 2026
Merged

ofriw merged 2 commits into
chunkhound:mainfrom
fstrasz:fix/voyage-query-input-type

Conversation

@fstrasz

@fstrasz fstrasz commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

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-4 at 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:

query embedded as target 1st in top 10 in top 90 median rank
query 11 / 15 14 / 15 14 / 15 1
document (current) 0 / 15 2 / 15 5 / 15 355

With this change, running the same 15 queries through SingleHopStrategy with the real provider reproduces the query row exactly: 14 of 15 targets in the first 90 results, and 11 ranked first.

Change

  • chunkhound/interfaces/embedding_provider.py: a new embed_queries(provider, texts). It calls the provider's embed_query when the provider's class defines one, and falls back to embed otherwise. Every other provider behaves exactly as before. The lookup is on the class, so a MagicMock provider keeps using its embed.
  • VoyageAIEmbeddingProvider.embed_query sends input_type: "query". embed still sends "document" for everything that gets indexed. Both share the existing sub-batching path.
  • EmbeddingManager.embed_query_texts mirrors embed_texts.
  • Query call sites switched over:
    • SingleHopStrategy, which multi-hop builds on;
    • the regex-result similarity scoring in SearchService;
    • the research unified_search;
    • DiffAwareSearchService.
  • Gap-query clustering in gap_detection.py compares 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: embed sends document, embed_query sends query (including when it sub-batches), and empty input makes no call.
  • tests/unit/test_query_embedding.py: the helper's query path and fallback, the MagicMock case, the manager, and that single-hop search embeds its query as a query.
  • Changing the single-hop call site back to embed, or making embed_query send document, fails these tests.
  • The diff-search test mocks gained embed_query_texts next to embed_texts. Two existing tests that stub the private _embed_single_batch now accept its new input_type argument.
  • These four files pass on this branch (179 passed). On our fork I also ran every test file matching search, research, diff, embed, voyage, rerank, mcp, query, gap or unified, before and after the change. The same 64 tests fail both times, on Windows; none fail newly.

Other providers with asymmetric query/document modes could implement embed_query the same way. I've only touched Voyage, the one I could measure.

🤖 Generated with Claude Code

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]>
@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

@ofriw This PR looks good to me but you probably know voyageAI better than I do...
Any reason against it?

@ofriw ofriw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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]>
@fstrasz

fstrasz commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All six changes are in 4ffe520, on top of the reviewed head, so nothing was rebased.

  1. Provider contract. EmbeddingProvider declares embed_query next to embed. OpenAIEmbeddingProvider.embed_query delegates to embed, and Voyage's sends input_type="query". The four query sites call provider.embed_query directly. embed_queries, its getattr/type() lookup and the MagicMock test are gone. The test fakes in tests/fixtures, tests/contracts and the Codex integration test gained embed_query too.
  2. One test per call site. tests/unit/test_query_embedding.py drives single-hop, SearchService.search_regex_async, UnifiedSearch.search_by_symbols and DiffAwareSearchService._search_diff with a provider whose query and document vectors differ. Each test asserts that the query vector is the one scored or ranked on. I checked each one by reverting its site to embed (or embed_texts for the diff site): every revert fails exactly that site's test.
  3. Voyage input mode. input_type is required on _embed_single_batch and _embed_single_batch_locked and typed VoyageInputType = Literal["query", "document"] on those and _embed_as. The only "document" literal is in embed and the only "query" is in embed_query. Tests pass the mode explicitly, including two calls in test_embedding_provider_analytics.py.
  4. EmbeddingManager. One _embedding_result(provider, embeddings) builds LocalEmbeddingResult. embed_texts and embed_query_texts differ only in the provider method they call.
  5. Fixture. _embed_texts takes provider_name: str | None = None, so [method-assign] covers both lines. mypy no longer reports lines 81–82 and finds no unused ignore in the file. The fixture's MagicMock provider also gets embed_query, because the research path now calls it.
  6. CHANGELOG. One Fixed entry under [Unreleased] saying no re-index is needed.

On "a provider without embed_query fails type checking": that holds for anything typed EmbeddingProvider. As a heads-up, which predates this PR: neither concrete provider currently matches the protocol structurally, because embed_streaming is declared async def returning an AsyncIterator while both providers implement it as an async generator. So take(OpenAIEmbeddingProvider(...)) against an EmbeddingProvider parameter already fails mypy on main. I left that alone.

Checks, on Windows: tests/unit + tests/contracts fail the same 6 tests before and after this commit (LLM config tests that read the environment). Repo-wide mypy reports the same 1006 errors before and after, with nothing new in the touched files.

fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 2, 2026
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]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 2, 2026
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]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 2, 2026
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]>
@fstrasz

fstrasz commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@ofriw, when you have a moment, could you re-review? All six changes from your 11-02 review are in 4ffe520, the current head, added the same day as a commit on top of the reviewed head. My comment above lists them one by one. Your requested changes are the only thing blocking the merge.

@ofriw ofriw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM. Thank you for this valuable contribution!

@ofriw
ofriw added this pull request to the merge queue Nov 8, 2026
Merged via the queue into chunkhound:main with commit c0b586d Nov 8, 2026
49 of 50 checks passed
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
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]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
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]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
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]>
VakninAriel pushed a commit to VakninAriel/chunkhound that referenced this pull request Nov 24, 2026
* 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]>
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.

3 participants