Repository navigation
fix(duckdb): similarity lookups skip a malformed vector instead of failing - #522
Merged
HananKavitzAmat merged 5 commits intoNov 23, 2026
Conversation
…iling DuckDB's cosine functions raise on a stored vector with NULL elements, which is how a NaN vector is stored. Three queries computed the cosine unguarded, so one such vector in scope failed the whole call: - get_chunk_similarities raised; the regex-result scoring that calls it caught the error and left every result unscored; - find_similar_chunks returned [], so multi-hop expansion found nothing; - search_by_embedding returned []. A module helper, _guarded_cosine_sql(), now builds the TRY()-wrapped cosine expression for all three, and each drops the NULL scores: get_chunk_similarities leaves the chunk out (as for a chunk with no embedding), and the two neighbour queries order NULLS LAST and drop NULL rows after the LIMIT, which returns the same rows as filtering first. Filtering in WHERE on the alias instead made DuckDB evaluate the cosine twice (553 vs 500 ms median on a 22k x 1024-dim copy; unguarded 471 ms). None of these joined queries uses the HNSW index, before or after. search_semantic already wraps its cosine in TRY() and is left as is here; it can move onto the helper as a follow-up. On a copy of a 22,349-chunk index with one live in-scope vector made malformed: before, get_chunk_similarities raised and both neighbour lookups returned 0 rows, scoped and unscoped; after, 59 of 60 ids are scored and each lookup returns its 20 rows. The new test makes one live chunk's vector malformed and checks all three lookups against a brute-force ranking. It fails on the base (InvalidInputException), and reverting any one site makes it fail again. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…imilarity lookups Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Nov 12, 2026
Brings in chunkhound#521. CHANGELOG.md conflicted only because both PRs add a line at the top of [Unreleased] ### Fixed; both entries are kept, this PR's first. No other conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Collaborator
|
@fstrasz Please pull your rust-check fix from main in all your PRs. Please |
Brings in chunkhound#510, chunkhound#504 and chunkhound#534. No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in chunkhound#526, chunkhound#502 and chunkhound#533. CHANGELOG.md conflicted only because this PR and chunkhound#526 each add a line at the top of [Unreleased] ### Fixed; both entries are kept, this PR's first. No other conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Contributor
Author
|
@HananKavitzAmat done. Main, including #534's rust-checks fix, is now merged into every open PR of ours: #462, #467, #481, #484, #485, #490, #491, #492, #493, #505, #509, #519, #522 and #525. They were all ordinary merges, with no force-pushes. CI is running on the last ones. 🤖 Generated with Claude Code, reviewed by FStrasz |
HananKavitzAmat
approved these changes
Nov 23, 2026
HananKavitzAmat
left a comment
Collaborator
There was a problem hiding this comment.
Looks good. merging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
One stored embedding with NULL elements (what a NaN vector is stored as) makes three DuckDB similarity lookups fail as a whole. In DuckDB 1.5.4,
array_cosine_similarityandarray_cosine_distanceraise on such a vector, and these three queries compute the cosine withoutTRY():get_chunk_similaritiessearch_service.pyand the research path inunified_search.py) catch the error, so every regex result loses its similarity score.find_similar_chunks[]through itsexceptsearch_by_embedding[]To reproduce, set one in-scope chunk's vector to NaN and call any of the three lookups.
Fix
One module helper,
_guarded_cosine_sql(metric, dims), returnsTRY(array_cosine_{metric}(e.embedding, ?::FLOAT[dims])), and all three sites use it:get_chunk_similaritiesdrops a NULL score, so the chunk is treated like one with no embedding; callers already read scores withscores.get(cid, 0.0).distance ASC NULLS LASTand drop NULL rows after theLIMIT. That returns the same rows as filtering first.I also tried
distance IS NOT NULLin theWHEREclause and rejected it:EXPLAINshowsTRY(cosine)evaluated twice. Medians on a 22k × 1024 copy, interleaved runs:WHEREsearch_semanticalready wraps its cosine inTRY()and is not touched here. Moving it onto the same helper is a small follow-up once this and #521 have landed.Tests
test_malformed_vector_is_skipped_by_every_similarity_lookup, intests/unit/test_duckdb_semantic_search_exact.py(existing fixture), replaces one live chunk's vector with NaN. It then checks each of the three public lookups against a brute-force ranking:get_chunk_similarities_asyncover all live ids,search_by_embedding, andfind_similar_chunks.On main it fails with
InvalidInputException: array_cosine_similarity: left argument can not contain NULL values. Reverting one site at a time also fails it: site 1 raises, and sites 2 and 3 giveassert [] == [...]. So each site is pinned.All 4 tests in the file pass.
Related unit, MCP, CLI and smoke tests were run serially. The only failures, on main and on this branch alike, were CLI subprocess timeouts on the test machine, with no assertion failures; those tests don't reach these queries. ruff and mypy report the same findings as main on the changed files.
Measurements
DuckDBProvideron a copy of a real 22,349-chunk, 1024-dim index (DuckDB 1.5.4), with one in-scope vector set to NaN:get_chunk_similarities(60 ids)search_by_embedding(unscoped / path-scoped)find_similar_chunks(unscoped / path-scoped)The query plans are unchanged.
EXPLAINshows noHNSW_INDEX_SCANfor these joined queries before or after, so nothing moves from approximate to exact search.A query whose scan includes a malformed row runs about 3× slower (88 → ~265 ms in-memory, 22k rows) because of
TRY()'s error path. Before this change that query failed outright.Overlap
CHANGELOG.md's### Fixed, so whichever merges second needs a one-line rebase there.duckdb_provider.py: this PR merges cleanly with fix(compaction): preserve non-cosine HNSW metrics during auto-compaction rebuilds #464, fix(logging): convert loguru printf-style calls to {} (fixes #458) #479, fix(pipeline): store the mtime of a file confirmed unchanged by hash #502 and fix(realtime): a file write is one executor submission; a failed resync is retried #510. The older ones already conflict with main in the same files and gain no new conflict.CHANGELOG.md:[Unreleased]→ Fixed.🤖 Generated with Claude Code, reviewed by FStrasz