Skip to content

fix(duckdb): similarity lookups skip a malformed vector instead of failing - #522

Merged
HananKavitzAmat merged 5 commits into
chunkhound:mainfrom
fstrasz:fix/similarity-lookups-skip-malformed-vectors
Nov 23, 2026
Merged

HananKavitzAmat merged 5 commits into
chunkhound:mainfrom
fstrasz:fix/similarity-lookups-skip-malformed-vectors

Conversation

@fstrasz

@fstrasz fstrasz commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

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_similarity and array_cosine_distance raise on such a vector, and these three queries compute the cosine without TRY():

Lookup What happens What the user sees
get_chunk_similarities raises Its callers (regex-result scoring in search_service.py and the research path in unified_search.py) catch the error, so every regex result loses its similarity score.
find_similar_chunks returns [] through its except Multi-hop expansion finds no neighbours.
search_by_embedding returns [] Nothing comes back.

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), returns TRY(array_cosine_{metric}(e.embedding, ?::FLOAT[dims])), and all three sites use it:

  • get_chunk_similarities drops a NULL score, so the chunk is treated like one with no embedding; callers already read scores with scores.get(cid, 0.0).
  • The two neighbour queries order by distance ASC NULLS LAST and drop NULL rows after the LIMIT. That returns the same rows as filtering first.

I also tried distance IS NOT NULL in the WHERE clause and rejected it: EXPLAIN shows TRY(cosine) evaluated twice. Medians on a 22k × 1024 copy, interleaved runs:

Variant Median
unguarded (main) 471 ms
this PR 500 ms
filter in WHERE 553 ms

search_semantic already wraps its cosine in TRY() 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, in tests/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_async over all live ids, search_by_embedding, and find_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 give assert [] == [...]. 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

DuckDBProvider on a copy of a real 22,349-chunk, 1024-dim index (DuckDB 1.5.4), with one in-scope vector set to NaN:

main this PR
get_chunk_similarities (60 ids) raises 59 of 60 scored; the malformed chunk is left out
search_by_embedding (unscoped / path-scoped) 0 rows 20 rows
find_similar_chunks (unscoped / path-scoped) 0 rows 20 rows

The query plans are unchanged. EXPLAIN shows no HNSW_INDEX_SCAN for 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: [Unreleased] → Fixed.

🤖 Generated with Claude Code, reviewed by FStrasz

fstrasz and others added 2 commits November 12, 2026 09:24
…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]>
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]>
@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

@fstrasz Please pull your rust-check fix from main in all your PRs. Please

fstrasz and others added 2 commits November 17, 2026 06:21
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]>
@fstrasz

fstrasz commented Nov 17, 2026

Copy link
Copy Markdown
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 HananKavitzAmat 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.

Looks good. merging

@HananKavitzAmat
HananKavitzAmat added this pull request to the merge queue Nov 23, 2026
Merged via the queue into chunkhound:main with commit 9fcc0ae Nov 23, 2026
27 checks passed
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.

2 participants