Repository navigation
Fix vector search with arrayJoin below the sort and with a row policy - #114074
Conversation
`arrayJoin` changes the number of rows: an empty array drops its base row. Vector search shortlists a few base rows through the index and feeds only those to the expression below the sort, so the rows a later base row would have contributed were never produced and the query returned fewer rows than the `LIMIT`. `optimizeTopK` already rejects `arrayJoin` for the same reason. A row policy restricts rows inside the reader just like a `WHERE` or a `PREWHERE`, so it must count as an additional filter. It did not, so a query filtered only by a policy was treated as unfiltered: the `vector_search_filter_strategy = 'prefilter'` bailout was skipped, and the index fetched only `LIMIT` neighbours without the `vector_search_index_fetch_multiplier` compensation.
|
Workflow [PR], commit [825ff84] Summary: ✅
AI ReviewSummaryThis PR hardens the vector-search Final Verdict✅ Approved. No new inline findings. LLVM Coverage ReportMeasured on commit 825ff84.
Changed lines: Changed C/C++ lines covered: 115/120 (95.83%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 23 s compile time in total, 8 of them have a recent master baseline. |
The policy filter runs inside the reader on the read columns, and `replaceVectorColumnWithDistanceColumn` removed the physical vector column from the read list, leaving the policy without its input: a query such as `SELECT id FROM t ORDER BY cosineDistance(vec, ...) LIMIT 1` with a policy `USING length(vec) > 0` failed with `NOT_FOUND_COLUMN_IN_BLOCK` on the default `vector_search_with_rescoring = 0` path. Give it the same treatment as a `SELECT` clause containing the vector column: skip the rewrite. Addresses the AI review finding on #114074. Co-Authored-By: Claude Fable 5 <[email protected]>
With `FINAL` and the default `apply_row_policy_after_final = 1`, a row policy that is not part of the sorting key is moved into `deferred_row_level_filter` by `deferFiltersAfterFinalIfNeeded` before the vector-search second pass runs, so checking only `getRowLevelFilter` missed it and `replaceVectorColumnWithDistanceColumn` still erased the vector column that the deferred policy needs, leading to a `NOT_FOUND_COLUMN_IN_BLOCK` exception. The second pass now inspects `getDeferredRowLevelFilter` as well. Co-Authored-By: Claude Fable 5 <[email protected]>
…ector column An explicit `PREWHERE` turns the non-rescoring vector-search rewrite off, because that rewrite drops the physical vector column from the read list in favour of the virtual `_distance` column. Under `FINAL` the `PREWHERE` can additionally be deferred until after the final merge, either through `apply_prewhere_after_final` or behind a row policy over a non-sorting-key column. Deferring copies the filter into `deferred_prewhere_info` and keeps `query_info.prewhere_info` in place until the pipeline is built, i.e. past every query plan optimization, so the `getPrewhereInfo` bailout still fires and the vector column survives for the deferred filter. Pin that: the queries return the nearest row and the plan keeps reading `vec`, with a control query without `PREWHERE` proving the plan check is not vacuous. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`deferFiltersAfterFinalIfNeeded` copies `query_info.row_level_filter` into `deferred_row_level_filter`; it does not move it. `query_info.row_level_filter` is cleared in `ReadFromMergeTree::initializePipeline`, i.e. after every query plan optimization has run, so at the time of the vector-search second pass both carriers hold the policy and either one alone would trigger the guard. Both are still checked so that the guard does not depend on that ordering, but the comment should not claim the policy has already moved. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… column A plain `WHERE` filter below the sort that reads the search column (e.g. `WHERE length(vec) > 0`) reached the non-rescoring rewrite: `replaceVectorColumnWithDistanceColumn` dropped the vector column from the read list, and the `FilterStep` was rebuilt on top of the new reader header while its predicate still needed the column, failing with `NOT_FOUND_COLUMN_IN_BLOCK`. Reachable with default settings, because the implicit `PREWHERE` optimization is disabled for vector-search candidates. The bailout now prunes a copy of the filter step's DAG the same way the rebuild does and skips the optimized-plan rewrite if the search column survives among the required inputs - the same treatment as the vector column in `SELECT` and in a row policy. The pruned DAG is reused in the rebuild. Co-Authored-By: Claude Fable 5 <[email protected]>
…arch test The control query of `04839_vector_search_final_prewhere` relies on the non-rescoring rewrite actually happening under `FINAL`, which requires the vector index to be used. The randomized setting `use_skip_indexes_if_final = 0` disables the index under `FINAL`, so the rewrite never fires and the control returned 0. Pin `use_skip_indexes_if_final = 1` (and `use_skip_indexes_if_final_exact_mode = 0`) against randomization. CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114074&sha=4cb158477ac3df1c9c8a556cb00fccb02166effa&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 Co-Authored-By: Claude Fable 5 <[email protected]>
A row policy on a non-key attribute hides the `LIMIT` nearest neighbours, so the non-rescoring shortlist returns nothing with `vector_search_index_fetch_multiplier = 1` and the next visible rows once the multiplier is raised. Without the fix (the row policy not counted in `additional_filters_present`), the multiplier is not applied and the query returns nothing even with `vector_search_index_fetch_multiplier = 3` (verified against a pre-fix master binary). The policy must not filter on the primary key column: such a policy feeds the primary key analysis and is carried in `PrewhereInfo`, which makes the rewrite fall back to an exact scan that is correct regardless of the multiplier. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114074&sha=6996e85e7450afd7be2c987661928e4c5eb9abeb&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%201%2F4%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. All 57 failures in the shard are |
|
Your analysis is right, and the fix is already merged: it is your own #114415, which landed 3 hours after this run. The run is one fixture event, not 57 failures: all 57 rows carry the byte-identical That is exactly the hang #114415 recovers from. Neither its merge commit On the tracking issue: you are correct that there is no open GitHub issue. I track this signature internally; over 120 days it is 16 whole-module events, and since 2026-07-10 all 9 are on No new PR from me here: the recovery is yours and already merged, and this red is unrelated to #114074. |
The AI review asked to mirror the `arrayJoin` bailout of the vector-similarity-index path in `optimizeVectorSearchWithQuantizedCodes`. It is not needed there: that rewrite splices its shortlist `LimitStep` *above* the whole Expression/Filter chain, so an `arrayJoin` in a lower `FilterStep` runs before anything is truncated and the result always reaches the `LIMIT`. Only an `arrayJoin` in the rescore expression above the shortlist would be a problem, and that is already rejected by the `hasArrayJoin` check there. Verified against a build without any additional guard: with `vector_search_index_fetch_multiplier = 1` and the four nearest rows dropped by `arrayJoin`, the query still returns the full `LIMIT`, and the top-k deviation at multiplier 1 is plain quantization error - a plain `WHERE id >= 16` on the same data returns the identical set. Add `04893_vector_search_quantized_codes_array_join` to pin the invariant: the shortlist limit sits above the filter, the row count reaches the `LIMIT` at multiplier 1, and a large multiplier reproduces the exact top-k.
|
🕵 Fixed the deterministic CI failure in |
|
📊 Cloud Performance Report ✅ AI verdict: Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there. I downgraded all six flagged ClickBench improvements (Q18, Q23, Q31, Q32, Q33, Q34) to not_sure. This PR only changes the vector-search query plan rewrites (arrayJoin and row-policy guards, and how dotted search-column names are resolved) and adds tests, and none of these queries uses a vector similarity index or a distance ORDER BY. Q32's CPU drop of about 30% shows real work reduction, but it most likely comes from master changes between the v26.9 baseline and the v26.10 PR build. Q33 and Q34 sped up in wall time while CPU time rose slightly. No regressions were flagged, and nothing in tpch_adapted_1_official stood out. clickbenchFlagged queries (6 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
Add `05043_vector_search_dotted_search_column`: a table carrying both `vec` and a dotted `n.vec`, each with its own vector similarity index. The nearest neighbour differs between the two columns, so binding the query to the index of `vec` would be visible in the result. Checked with both analyzers, because the name extracted from `ORDER BY` is unqualified with the old one.
|
@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too. |
The dotted-name fallback in `useVectorSearch.cpp` stripped everything before the first dot whenever the exact vector-index lookup missed. On the old-analyzer path the extracted name can already be a real storage column such as `n.values.id`, so `ORDER BY L2Distance(n.values.id, ...)` could bind the optimization to an indexed `values.id` column and rank candidates by the wrong vector while the query still sorts by the column that was written. Peel the leading component only when it is a proven table qualifier: the full name is not a column of the table while the remainder is. Otherwise the optimization bails out and the query falls back to an exact scan. Regression test `05063_vector_search_multi_dot_column_name`.
`SETTINGS enable_analyzer` cannot be changed inside the `EXPLAIN` subquery, so the two analyzer variants are selected with a session-level `SET`. Reference recorded from the fixed binary; with the previous first-dot truncation the same test returns the neighbours of the unrelated indexed `values.id` column (ids `0, 1, 2`) instead of the neighbours of `n.values.id` (ids `63, 62, 61`), on both the analyzer and the old-analyzer path.
|
…ily and enable the `Quantized` codec `shankar-iyer` asked for all new tests of this pull request to carry the `02354_vector_search` prefix used by the rest of the vector-search tests, so all nine are renamed accordingly. `02354_vector_search_quantized_codes_array_join` also failed in `Fast test` with `Codec Quantized is experimental and not meant to be used in production`: `allow_experimental_codecs` became obsolete and the codec is now gated behind `enable_quantized_codec`, which the test now sets. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 @shankar-iyer, thanks — points 2 and 3 are done in
|
The analyzer is mandatory on `master` now: `SET enable_analyzer = 0` throws `SETTING_CONSTRAINT_VIOLATION`, so these sections can no longer run. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…odes rewrite `useVectorSearchWithQuantizedCodes.cpp` stripped the first dotted component of the search column whenever the codec lookup on the full name failed, so `ORDER BY L2Distance(`n.values.id`, ...)` on a column without the codec was shortlisted on `values.id.quantized` when `values.id` carried `Quantized`, and the exact rescore only saw that wrong shortlist. Resolve the name with the same rule as `useVectorSearch.cpp`: peel the leading component only when the full name is not a storage column while the remainder is. Regression `02354_vector_search_quantized_codes_multi_dot_column_name`: the pre-fix binary uses the shortlist and returns ids 2, 1, 0 instead of 63, 62, 61. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Fixes for the vector search
ORDER BY <distance> LIMIToptimization.arrayJoinbelow the sort.arrayJoinchanges the number of rows - an empty array drops its base row - so the rewrite must not shortlist base rows before it runs.optimizeTopKrejectsarrayJoinfor this reason (#82279), but the vector search optimization did not, so the rows that a later base row would have contributed were never produced:A row policy is an additional filter. A row policy restricts rows inside the reader just like a
WHEREor aPREWHERE, but it did not participate inadditional_filters_present, so a query filtered only by a policy was treated as unfiltered: thevector_search_filter_strategy = 'prefilter'bailout was skipped, so an explicit request for exact search was ignored, and the index fetched onlyLIMITneighbours without thevector_search_index_fetch_multipliercompensation, which the policy can then discard.Filters that read the vector column broke the non-rescoring rewrite (found during review). The rewrite drops the physical vector column from the read list and replaces it with the virtual
_distancecolumn, so any filter that still needs the column was left without its input and the query failed withNOT_FOUND_COLUMN_IN_BLOCK(an exception, pre-existing on master). The rewrite is now skipped - the same treatment as the vector column inSELECT- when the column is read by:FINALwithapply_row_policy_after_final),WHEREfilter below the sort, e.g.WHERE length(vec) > 0(reachable with default settings, because the implicitPREWHEREoptimization is disabled for vector-search candidates).The quantized-codes rewrite (
useVectorSearchWithQuantizedCodes) is not affected by these problems: it splices the shortlist above the wholeExpression/Filterchain, so the expansion and the filters run below it, and its reader-side filters prefilter the approximate ranking. This was checked with the same queries.Dotted vector column names. The search column name taken from
ORDER BYis unqualified whenever the distance function reads theINPUTnode directly, while the plan's DAG nodes carry the table qualifier (__table1.vec), so the bailouts above had to recognize both forms. Matching by suffix was too broad - an unrelated dotted columnn.vecwas conflated with a search column namedvecand needlessly disabled the rewrite - so the exact DAG input name is now recovered from the distance function's argument and compared exactly. The index lookup had the mirror-image problem, pre-existing on master: it stripped everything before the first dot, so a genuinely dotted storage columnn.veccollapsed tovecand could bind to the index of an unrelated column. It now peels the leading component only when it is a proven table qualifier: the full name is not a storage column, but the remainder is.useVectorSearchWithQuantizedCodes.cpphad the same problem: a dottedn.values.idwithout theQuantizedcodec was shortlisted onvalues.id.quantized. It now resolves the name with the same rule.FINALwith an explicitPREWHEREis covered by a separate regression test.FINALcan defer aPREWHEREuntil after the merge, but the deferral copies the filter and clearsquery_info.prewhere_infoonly when the pipeline is built, i.e. past every query plan optimization, so the existinggetPrewhereInfobailout still fires and the physical vector column survives for the deferred filter.Related: #82279
Related: #110188
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed vector search returning too few rows for a query with
arrayJoinbelowORDER BY <distance> LIMIT. A row policy now counts as an additional filter for vector search, sovector_search_filter_strategy = 'prefilter'is honored and the index fetch multiplier is applied for a query filtered by a row policy. FixedNOT_FOUND_COLUMN_IN_BLOCKfor a non-rescoring vector search query when aWHEREfilter or a row policy reads the vector column.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/114074]
Version info
26.10.1.1249-master(included in26.10and later)