Skip to content

Vector similarity pk partial filter - #104754

Open
zex-hyd wants to merge 85 commits into
ClickHouse:masterfrom
zex-hyd:feature/vector-similarity-pk-partial-filter
Open

zex-hyd wants to merge 85 commits into
ClickHouse:masterfrom
zex-hyd:feature/vector-similarity-pk-partial-filter

Conversation

@zex-hyd

@zex-hyd zex-hyd commented May 12, 2026 •

Copy link
Copy Markdown

Fixes the case where vector_similarity skip indexes were not used when a primary key condition left only a subset of marks in a part. Previously, that situation skipped vector index analysis entirely, so reads could not use the HNSW granule to narrow work the way the index is intended.

This PR keeps running vector index analysis under partial PK pruning and passes surviving PK MarkRanges into USearch filtered_search as a predicate, so graph traversal only keeps neighbors whose rows map to PK-allowed data marks.

Motivated by #104122. Typical pattern: a long-retention table (for example tickets by time in the primary key) plus a narrow time predicate and ORDER BY vector distance with LIMIT — partial PK on the part plus vector search.

When other skip indexes (minmax, set, text) run earlier in the pipeline and narrow MarkRanges, the vector path still sees that reduced ranges input, so behavior stays conjunctive without extra glue.

limit is oversampled with vector_search_index_fetch_multiplier when row_filter is set, using the same rule as additional_filters_present and rescoring. filtered_search can still return fewer than limit hits if the PK slice removes almost all rows inside a granule.

Stateless: 04217_vector_similarity_pk_partial_pruning.

Changelog category (leave one):

  • Performance Improvement

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

Vector similarity skip indexes are used when the primary key leaves only a subset of marks in a part: neighbors are filtered with USearch filtered_search to PK-allowed data marks instead of skipping the vector index for that case.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Medium Risk
Changes MergeTree mark filtering and vector-search hint propagation during query execution; mistakes could cause incorrect pruning or _distance ordering behavior under mixed PK/skip-index conditions.

Overview
Enables vector_similarity skip index usage even when primary key pruning leaves only a subset of marks in a part, by passing PK-surviving row intervals into USearch filtered_search and restricting ANN hits to those ranges.

Updates vector-search hint handling to merge per-granule ANN results into part-global row offsets, conservatively dropping _distance hints if any non-empty granule lacks distances, and adds per-index_mark caching to avoid repeated ANN work when marks are referenced by multiple PK ranges.

Adds new VectorSearchUtils types (GranuleRowFilter, ANNSearchOverrides) and adjusts tests to expect index usage under partial PK pruning, plus a new stateless regression test (04217_vector_similarity_pk_partial_pruning).

Reviewed by Cursor Bugbot for commit 082abd3. Bugbot is set up for automated code reviews on this repo. Configure here.


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

@shankar-iyer shankar-iyer self-assigned this May 13, 2026
@shankar-iyer shankar-iyer added the can be tested Allows running workflows for external contributors label May 13, 2026
@shankar-iyer
shankar-iyer requested a review from Copilot May 13, 2026 02:34
@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [77c57bc]

Summary: ❌

job_name test_name status info comment
Docs check (Mintlify) FAIL
No direct edits to generated or read-only docs FAIL cidb
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

AI Review

Summary

This PR keeps vector_similarity skip indexes active when primary-key pruning leaves only part of a part, adds a selectivity fallback through vector_search_min_surviving_pk_fraction, and expands the partial-PK/rescoring tests and docs. The execution-path changes look coherent, but the new setting's compatibility boundary is described inconsistently and should be aligned before merge.

Findings

⚠️ Majors

  • [src/Core/Settings.cpp:9461] vector_search_min_surviving_pk_fraction now advertises conflicting rollback versions: the source-of-truth history entry is 26.10, its prose still says "compatibility with versions before 26.8", and the generated settings page in this PR still renders 26.8. One of those surfaces must be wrong, so users cannot reliably know which compatibility version restores the pre-PR behavior. Suggested fix: choose one release boundary, make the structured setting history and prose match it, then regenerate docs/reference/settings/session-settings/vector-search.mdx from that same source.
Final Verdict

⚠️ One compatibility/documentation contract issue remains: align the release boundary for vector_search_min_surviving_pk_fraction across Settings.cpp and the generated settings docs before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 13, 2026

Copilot AI left a comment

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.

Pull request overview

This PR improves MergeTree vector similarity skip-index usage by keeping vector index analysis enabled even when primary key pruning leaves only a subset of marks in a part, and constraining USearch traversal/results to PK-allowed marks via filtered_search.

Changes:

  • Extend the vector similarity index condition API to accept an optional per-granule PK MarkRanges row-filter.
  • Pass PK-surviving MarkRanges into vector index analysis during filterMarksUsingIndex, enabling vector search under partial PK pruning.
  • Add a stateless regression test covering partial PK pruning scenarios (including PK range + vector ORDER BY LIMIT, with/without additional filters).

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
tests/queries/0_stateless/04217_vector_similarity_pk_partial_pruning.sql Adds stateless queries to validate correctness under partial PK pruning with vector similarity ordering.
tests/queries/0_stateless/04217_vector_similarity_pk_partial_pruning.reference Adds expected outputs for the new stateless test.
src/Storages/MergeTree/MergeTreeIndices.h Extends IMergeTreeIndexCondition with GranuleRowFilter and an optional row-filter argument for vector ANN.
src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.h Updates vector similarity condition interface to accept the optional row-filter.
src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp Implements PK-aware ANN via USearch filtered_search and adds key→mark predicate logic.
src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp Removes the early-return that disabled vector index under partial PK pruning; constructs/passes row-filter to ANN.

zex-hyd and others added 5 commits July 19, 2026 16:44
…parts

Address the AI review "Request changes" verdict on ClickHouse#104754.

1. New setting `vector_search_min_surviving_pk_fraction` (default `0.5`): the
   minimum fraction of the marks of a part that must survive primary key
   analysis for the `vector_similarity` index to be used on a partially pruned
   part. Below it, `filterMarksUsingIndex` skips the index for the part, as
   before this feature, and exact distances are computed for the surviving rows.

   The measurement posted in the pull request (1M x 64 dim, single part, single
   HNSW granule) shows `filtered_search` is ~2x faster than the brute-force
   fallback when 80% of the part survives, but ~1.7x slower at 10% and ~10x
   slower at 2%, because the filtered graph traversal rejects most of the
   visited neighbours. The threshold keeps the win for wide slices and the old
   behavior for selective ones.

2. `04217_vector_similarity_pk_partial_pruning`: assert the ordered ids *and*
   distances of a cross-granule result against the brute-force baseline, using
   a mark-aligned filter (`id <= 2 OR id >= 6`) so both skip-index granules
   contribute hits and no row is removed afterwards. This covers the part-global
   `_distance` / row-offset merge that the previous row-count and primary-key
   membership assertions could not. Also cover the new threshold: below it the
   index is not used (`USearchSearchCount = 0`) and the result is exact, while
   with the threshold disabled the same query post-filters the index hits and
   returns fewer rows.

3. Because the default threshold restores the previous behavior for selective
   primary key conditions, `02354_vector_search_nonindexed_columns` and
   `04490_vector_search_rescoring_prewhere_eligibility` no longer need the
   expectation changes made earlier in this branch and are reverted to `master`.
   `02354_vector_search_pre_and_post_filtering` sets the new setting explicitly
   instead of depending on the default, and `02354_vector_search_rescoring`
   keeps the brute-force baseline and additionally shows the index-path result
   for the same query.
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed f1c14676075..4d921062aa1: merged the latest master (the branch was ~3300 commits behind) and addressed both minimum required actions of the AI review's Request changes verdict.

1. Selectivity fallback for auto mode (blocker). New setting vector_search_min_surviving_pk_fraction (default 0.5): the minimum fraction of the marks of a part that must survive primary key analysis for the vector_similarity index to be used on a partially pruned part. Below the threshold, filterMarksUsingIndex skips the index for the part exactly as before this feature and the surviving rows are scanned exactly. This keeps the ~2x win of the 80%-surviving case from the benchmark above and the old behavior for the 10% / 2% cases that regressed ~1.7x / ~10x. 0 always uses the index, 1 only when the primary key prunes nothing. (vector_search_filter_strategy is not visible in filterMarksUsingIndex — prefilter is already resolved in the plan — so the threshold applies to both auto and postfilter; setting it to 0 forces the previous behavior of this branch.)

2. Cross-granule assertion in 04217_vector_similarity_pk_partial_pruning (test finding). Added a case that compares the ordered (id, distance) pairs of a multi-granule query against the use_skip_indexes = 0 baseline. It uses a mark-aligned filter (id <= 2 OR id >= 6) so both skip-index granules contribute hits and nothing is removed by the residual predicate — that makes the index result exactly comparable to brute force, so a dropped granule or a mis-paired _distance fails the test. Also added coverage of the new threshold itself.

3. The 02354_vector_search_nonindexed_columns CI failure is fixed by the above. That test (added on master by 605222d9251/0d5e67f1a19) asserts that with key IN (0, 30, 60, 90) the implicit PREWHERE is restored; the branch produced row hints there and printed Filter column: instead of Prewhere filter column: in 32 jobs. Only 4 of 34 marks survive, which is below the default threshold, so the master behavior and the master version of the test are restored (same for 04490_vector_search_rescoring_prewhere_eligibility).

4. Recall of the partial-PK index path — worth a design decision before this merges. The primary key ranges are mark-granular, so the index searches a superset of the qualifying rows and the exact predicate then removes some of its top-k hits. When the boundary mark holds many non-qualifying rows, that can remove nearly all of them. On the 04217 table (index_granularity = 3, 12 rows), with the threshold disabled:

SELECT id FROM tab_pk_partial WHERE id >= 9 ORDER BY L2Distance(vec, [0., 2.]) LIMIT 3
-- index path (vector_search_min_surviving_pk_fraction = 0): []
-- brute force  (use_skip_indexes = 0):                      [9, 10, 11]

(id >= 9 keeps the mark holding ids 6, 7, 8 as well, since the primary key range of the preceding mark ends at the boundary value; the index returns 6, 7, 8 and id >= 9 then drops all three.) The same effect shows in 02354_vector_search_rescoring, where WHERE id > 3 ... LIMIT 3 returns 4, 5 on the index path instead of 4, 5, 6 — I made that visible in the test instead of hiding it behind use_skip_indexes = 0. With production granularities only the boundary marks are affected, and vector_search_index_fetch_multiplier mitigates it, but it is a change of the default result quality for primary-key-filtered vector searches that @rschu1ze / @shankar-iyer should sign off on. Raising the default threshold, or fetching limit + rows_in_boundary_marks neighbours, would be the natural knobs.

Verified locally on a build of this branch: 04217_vector_similarity_pk_partial_pruning, all 02354_vector_search_* and 04490_vector_search_rescoring_prewhere_eligibility pass (the only failure, 02354_vector_search_distributed_index_analysis, needs a parallel_replicas cluster that my single-node server does not define).

@rschu1ze rschu1ze added the hold Skip for auto-updating. label Jul 27, 2026
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
@rschu1ze

Copy link
Copy Markdown
Member

Added hold label, this needs human review @shankar-iyer

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 81.00% 86.20% +5.20%
Functions 91.50% 92.00% +0.50%
Branches 73.10% 78.40% +5.30%

Changed lines: Changed C/C++ lines covered: 213/253 (84.19%) · Uncovered code

Full report · Diff report

@zex-hyd

zex-hyd commented Aug 5, 2026

Copy link
Copy Markdown
Author

Hi @alexey-milovidov @shankar-iyer, would really appreciate a review!

@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f10725547 with master 36b4a90c4 (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
Binary Master PR Δ
programs/clickhouse-stripped 693.25 MiB 690.26 MiB -2.99 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

68 object files changed (+104.92 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp.o 915.79 KiB 998.94 KiB +83.15 KiB (+9.08%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp.o 507.02 KiB 524.50 KiB +17.48 KiB (+3.45%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 8, 2026
@zex-hyd

zex-hyd commented Aug 10, 2026

Copy link
Copy Markdown
Author

@rschu1ze @alexey-milovidov @shankar-iyer It looks like this PR now requires manual approval again for running the CI, probably after the latest merge from master / maintainer-side updates.

Could you please take another look when you get a chance? The latest PR workflow on the current head is green, and I believe the main review points have been addressed.

Thanks!

@rschu1ze

rschu1ze commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

@zex-hyd This PR contains rather complex changes and we are busy with other vector search developments at the moment. Expect some delay, sorry.

@zex-hyd

zex-hyd commented Aug 12, 2026

Copy link
Copy Markdown
Author

Thanks for the update, @rschu1ze.
I understand. I’ll keep the branch mergeable and wait for further review.

@abashkeev abashkeev added the comp-vector-index Vector similarity index in MergeTree: ANN/HNSW index build/query, usearch integration, vector ind... label Sep 4, 2026
…larity-pk-partial-filter

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

- retargeted PR record [email protected] to 26.10 (settings-history check rule)

Also resolved conflicts in:
- `docs/reference/settings/session-settings/manifest.json`
- `src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp`
- `src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp`

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Core/Settings.cpp

This setting is the minimum fraction of the marks of a part that must survive primary key analysis for the vector similarity index to be used. If fewer marks survive, ClickHouse skips the vector similarity index for the part and computes exact distances for the surviving rows instead. Valid range: [0.0, 1.0]. `0` always uses the index, `1` uses it only if the primary key prunes nothing.
)", 0, \
{"26.10", 1.0, 0.5, "New setting: minimum fraction of the marks of a part surviving primary key analysis for the vector similarity index to be used on a partially pruned part. previous_value=1.0 so `compatibility` with versions before 26.8 restores the legacy rule of using the vector index only when the primary key prunes nothing."}) \

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 compatibility cutoff for this setting is inconsistent across the branch: this source-of-truth entry uses 26.10, the description text still says "compatibility with versions before 26.8", and the generated docs/reference/settings/session-settings/vector-search.mdx in the same PR still renders 26.8. Because the actual compatibility behavior keys off this history entry, either the rollback boundary is wrong or the published guidance will tell users the wrong version to pin. Please settle on one cutoff and regenerate the settings docs from that same source.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-vector-index Vector similarity index in MergeTree: ANN/HNSW index build/query, usearch integration, vector ind... external Author is not a member of the ClickHouse organization hold Skip for auto-updating. manual approve Manual approve required to run CI pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants