Skip to content

Do not restrict a vector search to index rows when a delete is pending - #119371

Merged
alexey-milovidov merged 21 commits into
masterfrom
fix-vector-search-lightweight-delete-117286
Oct 10, 2026
Merged

alexey-milovidov merged 21 commits into
masterfrom
fix-vector-search-lightweight-delete-117286

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Fix a vector search returning fewer rows than its LIMIT, and missing true nearest neighbours, after a lightweight DELETE (or with a delete mutation applied on the fly): the vector index is no longer used for a part while it still holds deleted rows.

Documentation entry for user-facing changes

...

After a lightweight DELETE, a vector search returned fewer rows than its LIMIT and missed true nearest neighbours:

INSERT INTO hv SELECT number, [toFloat32(number % 97), toFloat32(number % 31)] FROM numbers(10000);
DELETE FROM hv WHERE id IN (5, 3012, 6019, 9026);       -- the exact matches of [5, 5]
SELECT count() FROM (SELECT id FROM hv ORDER BY L2Distance(v, [5.0, 5.0]) LIMIT 10);  -- 6

Deleting a whole cluster of near neighbours emptied the result. The rows that were returned were also not the nearest survivors: the deleted candidates shadowed them.

A lightweight delete does not rebuild a secondary index, so the vector index keeps returning the row ids of deleted rows. Both vector-search optimizations then restrict the read to exactly those rows — the rewritten plan without rescoring, and the exact row filter with rescoring — so _row_exists removes the deleted candidates afterwards with nothing left to take their place. Before exact row filtering was added (#108846, 26.7) the read covered the candidates' granules, so the surviving rows there were rescored and the query still satisfied its LIMIT.

Do not use the vector similarity index during index analysis for a part that has a delete the index does not know about: a materialized lightweight delete, a delete mutation that is applied on the fly, or a patch part attached to the part that updates _row_exists (a lightweight update may delete rows). This applies with apply_deleted_mask = 0 too, because such a query can still filter by _row_exists explicitly. Such a part is read in full and sorted by the exact distance until a merge or a mutation rebuilds the index; the check is per part, so other parts keep using the index. Only disabling the two optimizations is not enough: the index returns exactly LIMIT candidates and the mark filtering narrows the read to their granules, so with small granules and every candidate deleted the query was still short or empty. A part skipped this way carries no vector-search read hints, so both optimizations turn off for the query by their existing checks.

04491_vector_search_rescoring_lightweight_delete_filter asserted the old behaviour — that the row filter excludes a surviving granule mate after a lightweight delete, without checking that the LIMIT is still satisfied — and now asserts that the index answer equals the bruteforce one.

New test: 05205_vector_search_lightweight_delete_limit, covering both rescoring modes, the emptied-cluster case, a pending delete applied on the fly, a delete written as a patch part, and WHERE _row_exists with apply_deleted_mask = 0. It uses ten copies of a 10x10 grid (1000 rows) with index_granularity = 1 and a small HNSW graph, because every index build ran for more than a minute under ASan in the flaky check; the ten exact matches of the reference vector are the whole result of a LIMIT 10, so deleting them emptied the result before the fix. Verified in both directions, and a differential run of the vector_search/vector_similarity/lightweight_delete stateless tests shows no new failures.

Closes: #117286
Caused by: #108846


Workflow [PR]
Sync PR [sync-upstream/pr/119371]

Version info

  • Merged into: 26.10.1.2076-master (included in 26.10 and later)
  • Backported to: 26.9.16.9, 26.8.25.6

After a lightweight `DELETE`, a vector search returned fewer rows than its `LIMIT` and missed true
nearest neighbours:

    INSERT INTO hv SELECT number, [toFloat32(number % 97), toFloat32(number % 31)] FROM numbers(10000);
    DELETE FROM hv WHERE id IN (5, 3012, 6019, 9026);       -- the exact matches of [5, 5]
    SELECT count() FROM (SELECT id FROM hv ORDER BY L2Distance(v, [5.0, 5.0]) LIMIT 10);  -- 6

Deleting a whole cluster of near neighbours emptied the result. The rows that were returned were also
not the nearest survivors: the deleted candidates shadowed them.

A lightweight delete does not rebuild a secondary index, so the vector index keeps returning the row
ids of deleted rows. Both vector-search optimizations then restrict the read to exactly those rows -
the rewritten plan without rescoring, and the exact row filter with rescoring - so `_row_exists`
removes the deleted candidates afterwards with nothing left to take their place. Before exact row
filtering was added (#108846, 26.7) the read covered the candidates' granules, so the surviving rows
there were rescored and the query still satisfied its `LIMIT`.

Skip both optimizations for a query whose parts have a delete the index does not know about: a
materialized lightweight delete, a delete mutation that is applied on the fly, or a patch part (which
can carry an update of `_row_exists`). The read then falls back to the candidates' granules, as before
26.7, until a merge or a mutation rebuilds the index.

`04491_vector_search_rescoring_lightweight_delete_filter` asserted the old behaviour - that the row
filter excludes a surviving granule mate after a lightweight delete, without checking that the `LIMIT`
is still satisfied - and now asserts that the index answer equals the bruteforce one.

Closes: #117286
Caused by: #108846
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [056d216]

Summary: ✅


AI Review

Summary

This PR fixes the deleted-row/vector-search correctness bug by skipping the vector similarity index for parts whose deleted rows would otherwise make the shortlist stale, and the current code covers the previously discussed edge cases around patch parts, on-the-fly deletes, explicit _row_exists filters, and deferred PREWHERE under FINAL. I do not see remaining correctness blockers in the implementation; the only issue left is that the PR metadata / changelog wording now overstates the final shipped behavior.

PR Metadata
  • Changelog category: Bug Fix is the right category for this user-visible correctness fix.
  • Changelog entry: required and specific, but it is no longer accurate after the apply_deleted_mask = 0 follow-up. The final code still uses the vector index for lightweight-deleted parts when deleted rows remain visible and the query does not filter on _row_exists.
  • Suggested replacement: Fix vector search returning fewer rows than its LIMIT, and missing true nearest neighbours, when deleted rows are hidden from a part: the vector index is skipped for that part until a merge or mutation rewrites it.
Final Verdict

✅ No remaining blockers or majors in the code. Please align the PR metadata / changelog wording with the final shipped behavior before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-vector-index Vector similarity index in MergeTree: ANN/HNSW index build/query, usearch integration, vector ind... label Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 056d216a6 with master d741c9860 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 21 s compile time in total, 7 of them have a recent master baseline.

Job report

alexey-milovidov and others added 3 commits September 18, 2026 07:47
`MutationsSnapshot::hasPatchParts` is table-wide, so a single patch part in
another partition disabled both vector-search optimizations for every query
on the table. The `AlterConversions` built for a part already account for the
patches attached to that part: a patch that updates `_row_exists` puts the
column into the updated columns, so `hasLightweightDelete` sees it. Drop the
snapshot-wide check and rely on the per-part one.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The flaky check ran the test for more than 400 seconds under ASan: every
`INSERT` built an HNSW index over 10000 rows in about 85 seconds, and the
lightweight `DELETE` mutations cost as much again, five index builds per run.

Use ten copies of a 10x10 grid (1000 rows) with a small graph instead: the ten
exact matches of the reference vector are the whole result of a `LIMIT 10`, so
deleting them still emptied the result before the fix. Pin the primary index
granularity so that the fallback reads the same rows regardless of the
randomized table settings, reuse the first table for the deleted-cluster case,
and compare distances rather than ids (forty rows tie at distance 1).

Also cover a delete written as a patch part (a lightweight update of
`_row_exists`), which the per-part check now handles.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119371&sha=f8b5faac3e75e4269c9eb181257c705e3972e420&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
PR: #119371

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The function takes a fourth argument in the Cloud build, so the new call did
not compile there. Follow the shape `optimizeDirectReadFromTextIndex` already
uses for the same call.
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 2f4a6a86-f252-4500-96df-366107a326e3
  • MIRAI run: 349e69eb-2e3a-45db-9413-dee3f7a41b4e
  • PR check IDs:
    • clickbench_694718_1791624192
    • clickbench_694731_1791624192
    • clickbench_694737_1791624192
    • tpch_adapted_1_official_694743_1791624193
    • tpch_adapted_1_official_694775_1791624193
    • tpch_adapted_1_official_694789_1791624193

alexey-milovidov and others added 2 commits September 24, 2026 23:48
Disabling only the exact-row rewrite was not enough: the index still returns
exactly `LIMIT` candidates, and the mark filtering narrows the read to their
granules. With small granules (`index_granularity = 1`) and every candidate
deleted, the read contained nothing but deleted rows and the query was still
short or empty.

Now the vector similarity index is not used at all during index analysis for a
part that has a materialized lightweight delete, a lightweight delete in a patch
part, or a pending `ALTER DELETE` applied on the fly: the part is read in full
and sorted by the exact distance. The part carries no vector-search read hints
then, so the checks in `optimizeVectorSearchWithVectorIndexSecondPass` that
require hints for every part already turn both optimizations off, and the
separate check there is removed.

`05205_vector_search_lightweight_delete_limit` now uses `index_granularity = 1`,
so that reading only the candidates' granules would return nothing.

Addresses the review comment on `useVectorSearch.cpp`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov and others added 4 commits October 3, 2026 17:34
With `apply_deleted_mask = 0` lightweight-deleted rows (materialized or in
`_row_exists` patch parts) are returned, so the read sees exactly the rows
the vector index was built on. Only a pending `ALTER DELETE` applied on the
fly still disables the index unconditionally.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119371&sha=db76bfff0b652f38661203ab3ae61237131b7949&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%201%2F2%29 (05237_with_expression_alias_scope_descendant: view returns 10 instead of 100 under DatabaseReplicated; it also fails on many other PRs since 2026-10-03, e.g. #121924, #101774, #114008) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The Build (amd_fuzzers) link failure (relocation R_X86_64_PC32 out of range) was fixed on master by #123738; I merged master to pick it up.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

The fix is already in progress in #123790 (open). It includes the change from my #123774, which was closed in its favor. In #123790's own run on 2a290a03b667, 05237 passes in this arm_binary DBReplicated job.

It is not flaky: it fails every time under the Replicated database. The view is re-interpreted from the DDL log, and the stored definition qualifies nested as <db>.nested, so it reads the table (10) instead of the WITH alias (100). The passing reruns do not use the Replicated database (my open #112247 fixes that).

The failing run is on the old head db76bfff, before #123789 reverted #122853 (which added this job). The new head cd23ba3f includes the revert, so this job will not run on it until #123790 merges.

alexey-milovidov and others added 2 commits October 6, 2026 02:14
…weight_delete_filter`

The `id` tie-breaker added to `ORDER BY` disabled the vector search optimization
altogether, so the query no longer went through the index on master either and
the test passed there, which made `Bugfix validation` red. Order by the distance
only, as the optimization requires, and sort the collected ids instead.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119371&sha=cd23ba3febbff2bc614bb6f2fe38c0f5e23be132&name_0=PR&name_1=Bugfix%20validation%20(functional%20tests%2C%20amd64)
#119371

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

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. The 05237_with_expression_alias_scope_descendant failure is tracked in #123790.

I merged master and fixed the red Bugfix validation in 48d7ce2. The modified 04491_vector_search_rescoring_lightweight_delete_filter had an id tie-breaker in ORDER BY, which turns off the vector search optimization entirely. That made the test pass on master too. The test now orders by the distance only, so on master the query goes through the index again.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119371&sha=48d7ce2c8eb2156af3d868e7154afc7ba7e2a80d&name_0=PR&name_1=Stateless%20tests%20(amd_llvm_coverage%2C%20AsyncInsert%2C%20s3%20storage%2C%20parallel) and provide a fix in a separate PR. If the fix is already in progress, link it here. The job hit its 9000 s budget at test 13287 of 15404 with no failing test; this looks like what #116209 (splitting the coverage s3 parallel jobs into batches) addresses.

I merged master (no conflicts), rebuilt, and checked that 05205_vector_search_lightweight_delete_limit and 04491_vector_search_rescoring_lightweight_delete_filter pass.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

The fix is #116209 (mine). It splits this job and its ParallelReplicas twin into 2 batches each. It had drifted into a conflict with master in the generated workflows; I merged master into it (dbba2b3), it is mergeable again and waiting for your review.

The run on 48d7ce2c is that capacity limit, not a hang: 22 minutes of setup, then a steady ~1000 tests per 8 to 11 minutes until the runner's Timeout exceeded [9000] at 13287/15404. No test failed and none took over 310 s; the ParallelReplicas twin passed on the same commit in 6372 s. Applying the runner's crc32(name) % 2 split to this run's per-test durations gives halves of 50.3% / 49.7%, so the heavier AsyncInsert batch should take about 5900 s.

… even with `apply_deleted_mask = 0`

A query with `apply_deleted_mask = 0` can still filter by `_row_exists`
explicitly, which drops the deleted candidates of the index shortlist with
nothing to refill them, the same as the default masked read. Skip the index
whenever the part has deleted rows, and cover that case in
`05205_vector_search_lightweight_delete_limit`.

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

Copy link
Copy Markdown
Member

The code is ok.

Technically, we have to accept this change. Otherwise results are incorrect. We also might need to find a reason to relax it in a smart way. Either by adding a setting for incomplete reads, or by doing rescoring automatically.

Same problem as post-filtering returning fewer rows then LIMIT n. We have the index fetch multiplier, we could document that CH will automatically use the multiplier if there are pending DELETEs and will fetch more candidate rows from the index, but no guarantee of returning n rows.

@shankar-iyer shankar-iyer self-assigned this Oct 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 9, 2026
… index

Address review: describe the behavior for lightweight `DELETE` and pending
`ALTER DELETE` mutations, and when the index is used again.

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

mintlify Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 10, 2026, 8:00 AM

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @shankar-iyer Thanks. I documented the current behavior in 88edddd (new Deleted rows section in the vector index docs): parts with lightweight-deleted rows or a pending ALTER DELETE are read without the index (exact search) until a merge or mutation rewrites them, and apply_deleted_mask = 0 keeps the index.

Automatically raising vector_search_index_fetch_multiplier for such parts instead of the full scan is a reasonable follow-up, but it changes the guarantee (fewer than LIMIT n rows becomes possible again), so I would leave it to a separate PR rather than widen this fix.

alexey-milovidov and others added 2 commits October 10, 2026 07:20
… vector index

Address review: with `FINAL` and `apply_prewhere_after_final = 1` the `PREWHERE`
on `_row_exists` is deferred until after the `FINAL` merge. The index analysis
still sees it in `query_info.prewhere_info` (it is removed from there only in
`initializePipeline`, after the analysis), so the vector index is not used for a
part with lightweight-deleted rows. Pin that in the test: the table becomes a
`ReplacingMergeTree` (the ids are unique, so the other checks are unaffected).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Such rows would still be returned as candidates by the index and then removed after the read, so the query could return fewer than `LIMIT N` rows or miss the nearest remaining neighbors.
To keep the results correct, ClickHouse does not use the vector similarity index for parts with deleted rows and reads these parts in full (exact search) instead.
The index is used for the part again after a merge or a mutation rewrites it, for example after `OPTIMIZE TABLE ... FINAL`.
With setting `apply_deleted_mask = 0`, lightweight-deleted rows are returned by the query, so the index is still used unless the query filters by `_row_exists` explicitly.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The docs here are now accurate, but the PR metadata is still broader than the final behavior: the current Changelog entry says the vector index is no longer used for a part while it still holds deleted rows. After the apply_deleted_mask = 0 follow-up, plain reads in that mode still use the index unless the query filters on _row_exists, so the release-note text now overstates the exact-search fallback. Please narrow the changelog / PR summary wording to match this exception.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
Merged via the queue into master with commit e1120c2 Oct 10, 2026
164 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-vector-search-lightweight-delete-117286 branch October 10, 2026 22:41
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 10, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 10, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 11, 2026
Backport #119371 to 26.9: Do not restrict a vector search to index rows when a delete is pending
clickhouse-gh Bot added a commit that referenced this pull request Oct 11, 2026
Backport #119371 to 26.8: Do not restrict a vector search to index rows when a delete is pending
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 12, 2026
alexey-milovidov pushed a commit to tripleaceme/ClickHouse that referenced this pull request Oct 19, 2026
…ter walk

`_list_commits_page` ran one `gh api repos/ClickHouse/ClickHouse/commits`
call and raised on the first non-zero exit or timeout, and the per-TU
master first-parent walk makes ~20 such calls per job. GitHub fails single
requests (HTTP 503 and 504, a body cut short so `--jq` reports `unexpected
end of JSON input`, a stalled body) while the requests around them succeed,
so one blip errored the whole check: 9 jobs on 9 PRs between 2026-10-03 and
2026-10-14, the failing anchors 11-15 days deep in walks whose earlier
fetches had just succeeded, and the same commits passing on other runs.

Retry the listing up to 3 times (after 5 s, then 10 s), keeping the 120 s
per-call timeout. A timeout, an HTTP 5xx or 429, or a failure whose stderr
names no HTTP status is retried; any other 4xx (unknown sha, permissions)
fails at once, since `gh` reports an HTTP error as `gh: <message> (HTTP
<status>)`. After the last attempt the error propagates as before, so the
walk stays fail-close as the `extend_master_shas` docstring requires. The
praktika `GH` helpers retry but pass no subprocess timeout, which ClickHouse#115201
kept on this call site on purpose.

CI reports:
- https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124959&sha=1d61eebf3fe5ed809d4811ea947169074a3e1712&name_0=PR&name_1=Build%20profile%20diff
  (ClickHouse#124959)
- https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125328&sha=ab772cc3b97c2e6777f2ef60723bcbeb5a5f29e3&name_0=PR&name_1=Build%20profile%20diff
  (ClickHouse#125328)
- https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122585&sha=bf8b2d2470663e1b5703c2014b7887fe2d5dd239&name_0=PR&name_1=Build%20profile%20diff
  (ClickHouse#122585)
- https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119371&sha=88edddd16dcd4250ac56e1642f964a03763097f4&name_0=PR&name_1=Build%20profile%20diff
  (ClickHouse#119371)

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

This branch was successfully deployed

1 active deployment
staging - docs — 056d216a Deployed Oct 10, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-vector-index Vector similarity index in MergeTree: ANN/HNSW index build/query, usearch integration, vector ind... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Vector search after a lightweight DELETE returns fewer rows than LIMIT and misses true nearest neighbors, down to an empty result (26.7 regression)

7 participants