Skip to content

perf(duckdb): score embeddings before joining in semantic search - #474

Merged
e91d82c73 merged 2 commits into
chunkhound:mainfrom
fstrasz:perf/semantic-score-first
Nov 12, 2026
Merged

e91d82c73 merged 2 commits into
chunkhound:mainfrom
fstrasz:perf/semantic-score-first

Conversation

@fstrasz

@fstrasz fstrasz commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Exact semantic search (no HNSW scan) now keeps embedding vectors out of the joins with chunks and files, and, when a path filter is set, the page query scores only the embeddings of chunks in that scope. (The count query is the exception; see below.)

Why. search_semantic joined embeddings_N to chunks and files first, so every joined row carried its whole vector (4 KB at 1024 dims). The query now scores into (chunk_id, similarity), takes the page, and fetches the chunk rows for that page only. How it scores depends on the scope:

  1. Path-scoped: find the eligible chunk ids first (chunk and file present, path matches), then score only those chunks' embeddings. A narrow filter scores its own chunks, not the corpus.
  2. Unscoped: score every embedding, then join to drop any whose chunk or file is gone. Finding eligible ids first here makes DuckDB hash the embeddings side of the join, vectors included, which is as slow as the original query.

Measured on a synthetic index (14,000 chunks × 1024 dims, 1,000 files, chunk ids spread across directories, HNSW index present), DuckDB 1.5.4 on Windows. Each figure is the median of 21 search_semantic calls, count query included:

Search Before After
Unscoped, top 90 356 ms 136 ms
Path with 14 chunks 150 ms 28 ms
Path with 1,400 chunks 159 ms 45 ms

All three return the same rows as before. On the real 14k-chunk voyage-code-4 index, the unscoped query went from 299 ms to 124 ms.

Three details are deliberate:

  • A malformed stored vector never fails a search. Inserting a NaN vector stores NULL elements, and array_cosine_similarity raises on those. The cosine is wrapped in TRY(), so such a row scores NULL and is skipped wherever it sits, including in the count query's threshold. Before this, one such vector in scope made every search return nothing.
  • The NULL and threshold filters apply after the page. Rows they remove sort last, so filtering after LIMIT/OFFSET returns the same rows. Before the page, DuckDB pushes those filters down into the embeddings scan and scores every row there.
  • ORDER BY ... LIMIT never sits over a bare scan of the embeddings table, so the VSS optimizer cannot rewrite it into an approximate HNSW_INDEX_SCAN. Profiled with the HNSW index present: no index scan in either shape.

The count query is unchanged apart from TRY(). It still joins embeddings_N to chunks and files and applies every condition in one WHERE:

  • With a threshold set, it computes the cosine, so a thresholded search scores twice. On a path-scoped search, DuckDB's planner picks the order of the path filter and the cosine, so the count may score rows outside the scope.
  • Without a threshold, it counts malformed vectors that the page skips, so total_count can be higher than the rows a caller can page through. I'll fix that in a separate PR after this one.

Tests. tests/unit/test_duckdb_semantic_search_exact.py compares results with a brute-force cosine ranking. It covers an orphaned embedding, the path filter, the threshold and the offset, and a malformed vector left behind by a deleted chunk mid-way through the id range. That last test fails on the first version of this PR, which returned no results.

Relation to #392. I first offered this on #392, which touches the same function, in this comment. It is independent of that PR. Whichever merges second needs a small rebase, and I'm happy to do it.

🤖 Generated with Claude Code

The exact (non-HNSW) semantic query joined embeddings to chunks and files
first, so every joined row carried its whole vector, and computed the
cosine twice when a threshold was set. It now scores each embedding into
(chunk_id, similarity), joins that to chunks/files to apply the path
filter, threshold and page, and fetches the chunk rows for the page only.

The joins stay in the page step, so an embedding whose chunk or file is
gone never ranks or shortens a page (embeddings have no foreign key to
chunks). ORDER BY/LIMIT sit over the join, never over a bare scan of the
embeddings table, so the VSS optimizer cannot turn it into an approximate
HNSW scan.

Measured on a 14k-chunk, 1024-dim index: 299 ms -> 124 ms per query, same
top 90. The new test compares against a brute-force ranking and fails when
the page step's joins are made LEFT JOINs (orphan returned / page short).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@VakninAriel VakninAriel 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.

PR #474 — consolidated review

Verdict: Request changes

The broad-search optimization works, but scoring before membership/path filtering introduces two reproducible regressions: excluded malformed embeddings can empty valid searches, and selective path searches become slower. Preserve narrow intermediate rows and late content retrieval while fixing eligibility-before-scoring behavior.

  • PR: #474
  • Base: 11357f8858130dea53802ff5cb4df6876688a114
  • Head: 07d7cd5f662e0980e55564bf776f5dfe8408a6af
  • Scope: both changed files, surrounding database/search contracts, new and existing tests, base/head differential experiments, query plans and performance.
  • Review only: no production fixes, commits, or GitHub posting. Original working-tree status remains unchanged.

Reviewer provenance and reconciliation

Two isolated agents were dispatched concurrently with the exact requested groups opus and astra. They did not read each other's reports. Distinct underlying models could not be verified: both reported PI_MODEL=frontier-chat-dev/gpt-6-astra, but these environment variables may be inherited from the parent. Do not describe these reports as verified Opus-versus-Astra agreement. The report filenames identify requested groups, not proven runtime identity.

Both independently found the selective-path slowdown. The Astra-requested run additionally reproduced the malformed excluded-vector failure. The other run's smaller malformed-vector spot checks did not reproduce it; dynamic range pruning makes the data layout important. The coordinating reviewer inspected and reran the larger real-provider reproduction and confirmed it, then independently reran the performance experiment and targeted tests. Findings below are deduplicated and use verified PR-head line numbers.

P2 — Exclude ineligible embeddings before evaluating cosine

Location: chunkhound/providers/database/duckdb_provider.py:4010–4015.

The new scored projection evaluates cosine before the chunk/file/path joins. A malformed vector that would have been excluded can now raise during scoring and cause the existing exception handler to return an empty search, including total: 0.

Verified reproduction: DuckDB 1.5.4, real DuckDBProvider/schema, HNSW index present, 14,000 chunks spread across 1,000 files. Insert an eight-dimensional [float('nan')]*8 vector for interior chunk ID 2 through the public insert_embeddings_batch API. Insertion succeeds; DuckDB stores NULL array elements. Other embeddings are valid.

Scenario Base PR head
Bad vector belongs to another directory; search tiny 14 results, total 14 0 results, total 0
Delete the bad vector's chunk, leaving its embedding; unscoped search 90 results, total 13,999 0 results, total 0

Head logs array_cosine_similarity: left argument can not contain NULL values.

Malformed-vector acceptance and empty-result exception handling already exist. The introduced defect is the enlarged failure domain: a row outside the requested directory, or an orphan that should not participate at all, can now break an otherwise-valid search. Live in-scope malformed vectors fail on both revisions and are not a separate finding. This is layout/plan-dependent; tiny fixtures may prune the bad row before evaluating it.

Requested correction: Ensure eligibility is established before potentially failing scoring, retaining a narrow intermediate representation and late content retrieval; alternatively define safe handling of already-stored invalid arrays. Validation only on future inserts does not repair existing databases. Keep membership checks before LIMIT/OFFSET. Add a behavioral regression test covering excluded malformed vectors and an interior-ID orphan.

P2 — Preserve selective path filtering ahead of expensive scoring

Location: chunkhound/providers/database/duckdb_provider.py:4010–4022.

With a selective path and no threshold, base filters eligible chunk IDs before cosine evaluation. Head evaluates scores across much of the corpus before the path join rejects unrelated rows.

Coordinator rerun: DuckDB 1.5.4, real cosine HNSW index, 14,000 × 1024-dimensional valid vectors, 1,000 files, one DuckDB thread. Medians of 20 randomized base/head executions of count + result queries, warmed in-memory database; setup/index construction excluded.

Query Base PR head Effect
Unscoped top 90 86.40 ms 31.85 ms 2.71× faster
Narrow path: 14 eligible chunks 13.74 ms 22.27 ms 1.62× slower
Medium path: 1,400 eligible chunks 17.93 ms 27.74 ms 1.55× slower

EXPLAIN ANALYZE confirms head's score projection processes 13,001 rows before reducing to 14 eligible chunks; base scores only 14. Both independent reviews reproduced the direction, including larger corpora. The Opus-requested run also reproduced it with contiguous-per-file insertion and a directory spread across the corpus, so it is not limited to round-robin chunk layouts. Ratios are workload-specific, not universal claims about every path filter.

Requested correction: Retain selective membership filtering before cosine for scoped requests, while preserving the broad-search optimization and late content retrieval. A scoped query branch is one option. Validate broad and selective workloads with physical plans and a reproducible benchmark; avoid flaky wall-clock unit-test assertions.

What is working

  • Unscoped speedup independently reproduced.
  • Inner joins before pagination protect page slots from valid-vector orphans.
  • Result fields, parameter ordering, normal provider/model/path/threshold scopes, and pagination remain intact in tested cases.
  • New tests exercise public behavior and compare against an independent NumPy cosine oracle. Both also pass against the base executor, appropriate for a contract-preserving optimization.
  • Reviewers' indexed and unindexed query plans remained exact: no HNSW_INDEX_SCAN in tested search queries. A bare-vector positive control used HNSW, confirming the index/extension was functional. This resolves the main initial concern for the examined DuckDB 1.5.4 plans, not every future optimizer version.

Nonblocking observations / excluded findings

  • Both CTEs inline; SQL naming does not enforce materialization or a physical execution barrier.
  • Threshold plans still show a cosine predicate and scoring projection; the separate count query also computes cosine. The description should not promise one cosine evaluation across an entire search call.
  • Tie-order/pagination instability also occurs on base; not an introduced defect.
  • Nearby count_params typing errors are in unchanged code; not PR findings.

Verification and limitations

Coordinator reran:

  • Targeted DuckDB/path/provider/multi-hop tests: 118 passed.
  • Real-provider malformed excluded-vector reproduction: both base/head divergences confirmed.
  • Randomized-order indexed performance experiment: measurements above.
  • Mypy over chunkhound: 994 errors in 90 files, 372 files checked; not a clean typecheck. The entire base tree was not typechecked for a full error-by-error comparison.
  • git diff BASE HEAD --check: passed.
  • Original git status --short: same preexisting untracked artifacts, no tracked changes.

The two independent runs additionally performed separate differential matrices (768 cases in one, 22 full-sized indexed/unindexed cases in the other) and indexed positive-control checks. Do not sum overlapping test runs into a unique-test count.

Environment: original dependencies include DuckDB 1.4.4, so all query evidence explicitly used a uv overlay with DuckDB 1.5.4. Other dependencies/native support were reused read-only. A fresh locked install was blocked by the host's manylinux_2_31 versus the published native wheel's manylinux_2_34 requirement. One review's smoke-inclusive attempt had 57 passes and eight CLI failures due to that install constraint. No successful full-suite or smoke-suite claim; no Windows or persisted cold-cache benchmark.

… fails a search

Review follow-ups for chunkhound#474 (VakninAriel, 2026-11-04):
- Path-scoped search finds the eligible chunk ids first and scores only
  their embeddings, so a narrow filter no longer scores the corpus
  (14-chunk path: 122 -> 28 ms; base 150 ms).
- Unscoped search keeps scoring first: finding eligible ids first there
  makes DuckDB hash the embeddings side, vectors included (376 ms).
- array_cosine_similarity is wrapped in TRY(): a vector stored with NULL
  elements (what NaN becomes) scores NULL and is skipped, so an orphan or
  out-of-scope bad vector no longer empties the search.
- The NULL and threshold filters apply after the page; the rows they drop
  sort last, and before the page DuckDB pushes them into the scan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fstrasz

fstrasz commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review, and for the reproductions; both made the problems easy to pin down. Both findings are fixed in 7c087f5, a new commit on top of the reviewed head 07d7cd5.

P2: exclude ineligible embeddings before evaluating cosine. Fixed two ways:

  • Path-scoped search now finds the eligible chunk ids first (chunk and file present, path matches) and scores only those chunks' embeddings, using a semi join. An out-of-scope vector is never scored.
  • The cosine is wrapped in TRY(). A vector stored with NULL elements now scores NULL and is skipped, so an orphan anywhere in the id range can't fail an unscoped search. The same holds for the count query's threshold predicate.

TRY() also changes the in-scope case you set aside: one bad vector in scope used to make every search return nothing, and now only that row is skipped. Without a threshold, total still counts that row, because the count query doesn't compute the cosine.

I did not establish eligibility first for unscoped searches. I tried it: DuckDB 1.5.4 flipped the semi join so the embeddings table became the hash-join build side, vectors included, and the query took 376 ms, no better than base. Unscoped search therefore still scores first and drops orphans in the join, as before. TRY() is what makes that safe.

P2: preserve selective path filtering ahead of scoring. Fixed by the path-scoped shape above. One more change was needed: a similarity IS NOT NULL or threshold filter placed before the page got pushed down into the embeddings scan, which scored every row there first. Both filters now apply after LIMIT/OFFSET. Ordering is similarity DESC NULLS LAST, so the rows they remove come last, and filtering after the page returns the same rows.

Measurements. Synthetic index matching your layout: 14,000 chunks × 1024 dims, 1,000 files, chunks inserted round-robin so each directory's ids span the whole range, HNSW index present. DuckDB 1.5.4 on Windows, default threads. Each figure is the median of 21 search_semantic calls, count query included, so the absolute numbers aren't comparable to yours.

Search Base 11357f8 PR head 07d7cd5 7c087f5
Unscoped, top 90 356 ms 143 ms 136 ms
Path with 14 chunks 150 ms 122 ms 28 ms
Path with 1,400 chunks 159 ms 127 ms 45 ms
  • The result ids were identical across the three revisions for every search.
  • Profiled with the HNSW index present, neither shape uses HNSW_INDEX_SCAN.
  • The cosine no longer shows up as a filter on the embeddings scan in either shape.

Your reproduction on the same index. I set chunk 2 (in medium/, between tiny/'s ids 1 and 1001) to an all-NULL vector:

Scenario Base 07d7cd5 7c087f5
Path tiny, bad vector outside it 14 / 14 0 / 0 14 / 14
Chunk 2 deleted, bad embedding kept, unscoped 90 / 13,999 0 / 0 90 / 13,999

Test. I added test_malformed_vector_outside_the_scope_does_not_empty_the_search. Through the public API, it deletes an alpha chunk from the middle of the id range and inserts a NaN vector for that id. It then checks that an unscoped search and a beta-scoped search both still equal the brute-force ranking. It fails on 07d7cd5 with assert [] == [31, 8, 27, …] and passes on 7c087f5.

Your nonblocking notes.

  • The description is updated. It no longer says the cosine is evaluated once per search, and it now states that a thresholded count computes it again.
  • I left the CTE-inlining point alone. The semi join and the LIMIT boundary are what fix the evaluation order, not the CTE names.

Checks.

  • All 32 test files that exercise search_semantic or path filtering: 598 passed. The only failures are two Watchman event-translation tests, which fail the same way on 07d7cd5 (Windows).
  • ruff: 79 findings on the two files, against 81 on 07d7cd5.
  • mypy: the same findings as 07d7cd5.
  • Smoke, serial: the seven non-CLI tests pass. test_cli_help_commands times out its 5 s limit on this machine with or without the change: uv run chunkhound --version takes 4.7–5.5 s here on both revisions.

🤖 Generated with Claude Code

fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 6, 2026
… fails a search

Review follow-ups for chunkhound#474 (VakninAriel, 2026-11-04):
- Path-scoped search finds the eligible chunk ids first and scores only
  their embeddings, so a narrow filter no longer scores the corpus
  (14-chunk path: 122 -> 28 ms; base 150 ms).
- Unscoped search keeps scoring first: finding eligible ids first there
  makes DuckDB hash the embeddings side, vectors included (376 ms).
- array_cosine_similarity is wrapped in TRY(): a vector stored with NULL
  elements (what NaN becomes) scores NULL and is skipped, so an orphan or
  out-of-scope bad vector no longer empties the search.
- The NULL and threshold filters apply after the page; the rows they drop
  sort last, and before the page DuckDB pushes them into the scan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@VakninAriel

Copy link
Copy Markdown
Collaborator

Re-reviewed at 7c087f56. The follow-up addresses both findings from the previous review, and the revised approach preserves the benefit of the original optimization:

  • Excluded malformed vectors no longer empty otherwise-valid searches. I reran the out-of-scope and interior-ID orphan reproductions; both now return the expected results. Using TRY() is a reasonable resolution of the safe-handling alternative discussed in the earlier review.

  • Selective-path performance is fixed, without losing the unscoped speedup. In the repeated 14,000 × 1024-dimensional indexed benchmark, count + page query medians were:

    Search Base Previously reviewed head Revised head
    Unscoped 92.60 ms 33.35 ms 33.61 ms
    Path with 14 chunks 15.43 ms 23.74 ms 6.06 ms
    Path with 1,400 chunks 20.25 ms 33.06 ms 13.13 ms

    The scoped page-query plans now score only the eligible chunks. These are warm, single-threaded DuckDB 1.5.4 measurements, not universal timing guarantees.

  • The checked ranking and scope contracts remain intact. The indexed plans stayed exact, valid-input differential comparisons matched base, and 119 targeted tests passed, including the three tests in this PR.

The explanation of the two query shapes and the added malformed-orphan regression test also make the intent easier to follow.

Nonblocking follow-up: single-hop search can overstate totals and suggest an empty next page

Result filtering, lines 4067–4070; count query, lines 4076–4088.

The new safe-skip behavior is an improvement: a malformed live embedding no longer prevents valid results from being returned. However, when threshold=None, the count query still includes that embedding even though page.similarity IS NOT NULL excludes it from every result page. This makes total, has_more, and next_offset inconsistent with the searchable result set.

You already called out the unthresholded count limitation in your response. Tracing the consumers narrows its practical impact: single-hop search can display an inflated total and suggest an empty next page. It does not lose valid results or change their ranking.

Specifically:

  • CLI: chunkhound/api/cli/commands/search.py:198–208 displays the total, and 247–253 uses has_more/next_offset to suggest --offset for the next page. With the fixture below, the first page would display Results: 3 of 12 and suggest --offset 3, even though no further valid results exist.
  • MCP: chunkhound/mcp_server/tools.py:442–459 uses the metadata to render a footer such as Page 1 of 4 (results 1–3 of 12) | next_offset=3.
  • Scope: SingleHopStrategy.search forwards the database pagination unchanged (chunkhound/services/search/single_hop_strategy.py:71–82). Normal multi-hop search instead builds pagination from its accumulated results (chunkhound/services/search/multi_hop_strategy.py:377–390), so this count mismatch does not propagate through that path. The service selects multi-hop for providers supporting reranking; otherwise it uses single-hop. The CLI also supports explicitly selecting --single-hop.

I did not find an internal loop automatically following this metadata. Both CLI and MCP Markdown formatting show “No results found” for an empty page rather than continuing to display a pagination footer. The database/API metadata in the reproduction below remains incorrect, but it should not be described as a repeated user-facing pagination loop or a general search failure.

Given that narrower impact, the requirement for malformed live embeddings, and the improvement over the previous all-or-nothing failure, I would treat this as a nonblocking metadata-correctness follow-up, rather than retain the earlier P2 merge-blocking assessment.

Reproduction

Confirmed through the actual DuckDBProvider on DuckDB 1.5.4, with a cosine HNSW index present:

  1. Create 12 live chunks with valid, nonzero eight-dimensional embeddings under provider test, model mini.

  2. Replace nine of those embeddings with NaN vectors through the public API, keeping their chunks alive. For chunk IDs 4–12:

    provider.insert_embeddings_batch([
        {
            "chunk_id": chunk_id,
            "provider": "test",
            "model": "mini",
            "embedding": [float("nan")] * 8,
            "dims": 8,
        }
        for chunk_id in range(4, 13)
    ])

    These are stored with NULL array elements, so the new TRY() expression gives them NULL scores.

  3. Search with a valid query vector, no threshold, and successive offsets:

    query = [1.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
    results, pagination = provider.search_semantic(
        query_embedding=query,
        provider="test",
        model="mini",
        page_size=3,
        offset=0,  # Repeat with 3, 6, and 9.
        threshold=None,
    )

Observed at the database API boundary (the empty-page metadata is not rendered by the CLI/MCP Markdown formatters):

Threshold Offset Results returned total has_more next_offset
None 0 3 12 true 3
None 3 0 12 true 6
None 6 0 12 true 9
None 9 0 12 false null
-1.0 0 3 3 false null

Expected: the first unthresholded page should also report total=3, has_more=false, and next_offset=None, since only three embeddings can produce results. Nine malformed rows make the example obvious; one can also produce a phantom final page at a page boundary.

This is not a claim that base handled malformed live vectors correctly—it failed the search wholesale. The remaining issue is making the new, better safe-skip behavior consistent across results and pagination. The orphan test does not catch it because the membership joins already exclude that orphan from the count.

Suggested follow-up: make count eligibility agree with result eligibility, preserving the scoped-query performance improvement, and add a public behavioral regression test covering a malformed live embedding and its pagination metadata. Validation only on future inserts would not cover malformed arrays already stored in a database.

Nonblocking description clarification

The scoped page query now scores only eligible embeddings, but the thresholded count query can still evaluate cosine before path filtering. That behavior also exists on base, so it is not another performance blocker. Please qualify “scores only what the scope allows” to distinguish the page query from the whole thresholded search call.

Review conclusion: both original findings are resolved; no remaining merge-blocking finding from this re-review. The single-hop metadata inconsistency and description clarification above are nonblocking follow-ups. Verification was targeted, not a full-suite run. Mypy remains unclean with the same aggregate as the earlier review; no additional typing finding is being raised here.

@VakninAriel VakninAriel 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.

PR #474 — Approve with nonblocking follow-ups
Reviewed head 7c087f5 with three independent review agents. No new merge-blocking issues found.

Confirmed nonblocking finding
P3 — Pagination counts malformed live embeddings that results exclude
chunkhound/providers/database/duckdb_provider.py:4071–4088

Without a threshold, malformed vectors are skipped from results but included in total. Reproduced with three valid results: pagination reported total=32 and suggested an empty next page.

This affects single-hop pagination metadata, not valid-result ranking. It is already acknowledged in the PR discussion.

Verification
29 targeted tests passed, including all three new tests.
Independent reviewer: 480 valid-input comparisons matched base; examined plans remained exact.
Mypy: 994 errors in 90 files; no new PR-specific typing defect established.
Full suite and performance benchmarks were not rerun.

@fstrasz

fstrasz commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@VakninAriel thanks for the re-review and the approval.

  • P3 (pagination total counts malformed vectors). Agreed. I'll fix it in a separate PR once this one merges, since it changes the count query this PR touches. The obvious fix, TRY(cosine) IS NOT NULL in the count, adds a second scoring pass to every unthresholded search, so I'll measure a cheaper NULL-element check first.
  • Description. Updated. The first line now says the path-scoped page query is the one that scores only in-scope embeddings, and a new paragraph on the count query says it can still score out-of-scope rows when a threshold is set, and that it counts malformed vectors without one.

No code change since 7c087f5.

🤖 Generated with Claude Code

@e91d82c73
e91d82c73 added this pull request to the merge queue Nov 12, 2026
Merged via the queue into chunkhound:main with commit 24752d0 Nov 12, 2026
25 checks passed
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
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