Repository navigation
perf(duckdb): score embeddings before joining in semantic search - #474
Conversation
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
left a comment
There was a problem hiding this comment.
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_SCANin 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_paramstyping 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]>
|
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:
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. P2: preserve selective path filtering ahead of scoring. Fixed by the path-scoped shape above. One more change was needed: a 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
Your reproduction on the same index. I set chunk 2 (in
Test. I added Your nonblocking notes.
Checks.
🤖 Generated with Claude Code |
… 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]>
|
Re-reviewed at
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 pageResult 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 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:
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. ReproductionConfirmed through the actual
Observed at the database API boundary (the empty-page metadata is not rendered by the CLI/MCP Markdown formatters):
Expected: the first unthresholded page should also report 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 clarificationThe 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
left a comment
There was a problem hiding this comment.
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.
|
@VakninAriel thanks for the re-review and the approval.
No code change since 7c087f5. 🤖 Generated with Claude Code |
Brings in chunkhound#489, chunkhound#474, chunkhound#488, chunkhound#521, chunkhound#510, chunkhound#504 and chunkhound#534. No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in chunkhound#489, chunkhound#474, chunkhound#488, chunkhound#521, chunkhound#510, chunkhound#504 and chunkhound#534. No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Exact semantic search (no HNSW scan) now keeps embedding vectors out of the joins with
chunksandfiles, 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_semanticjoinedembeddings_Ntochunksandfilesfirst, 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: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_semanticcalls, count query included:All three return the same rows as before. On the real 14k-chunk
voyage-code-4index, the unscoped query went from 299 ms to 124 ms.Three details are deliberate:
array_cosine_similarityraises on those. The cosine is wrapped inTRY(), 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.LIMIT/OFFSETreturns the same rows. Before the page, DuckDB pushes those filters down into the embeddings scan and scores every row there.ORDER BY ... LIMITnever sits over a bare scan of the embeddings table, so the VSS optimizer cannot rewrite it into an approximateHNSW_INDEX_SCAN. Profiled with the HNSW index present: no index scan in either shape.The count query is unchanged apart from
TRY(). It still joinsembeddings_Ntochunksandfilesand applies every condition in oneWHERE:total_countcan 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.pycompares 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