Skip to content

Fix header column order after the no-rescoring vector search rewrite - #114457

Merged
alexey-milovidov merged 46 commits into
masterfrom
fix-vector-search-header-order
Oct 6, 2026
Merged

alexey-milovidov merged 46 commits into
masterfrom
fix-vector-search-header-order

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

The second-pass vector search optimization (vector_search_with_rescoring = 0) removed the distance function from the ExpressionStep outputs and re-appended the rewritten _distance alias at the end, changing the header column order. Steps created above the Sorting before that rewrite runs — the local top-N Limit and the exchange steps of a distributed plan — kept the original column order, and makeDistributedPlan failed to rebuild the plan fragments with a logical error: Cannot add step Limit to QueryPlan because it has incompatible header with root step Sorting. Non-distributed plans never re-validate step headers after optimization, which is why this only surfaced with make_distributed_plan = 1.

The fix reinserts the rewritten output node at the original position of the distance column, so the header column order is preserved and all previously created parent steps stay consistent.

Found by AST fuzzer on #42701 (report); the same signature also hit the unrelated #98789 on 2026-08-08.

The regression test asserts only the row count: the distributed plan currently returns an incorrect top-N for vector search queries regardless of the rescoring mode — a separate, pre-existing bug.

Related: #114456
Related: #42701

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 into CHANGELOG.md):

Fix a logical error Cannot add step Limit to QueryPlan because it has incompatible header with root step Sorting when a vector search query with vector_search_with_rescoring = 0 was executed with the experimental make_distributed_plan setting.


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

Version info

  • Merged into: 26.10.1.1642-master (included in 26.10 and later)

The second-pass vector search optimization (`vector_search_with_rescoring = 0`)
removed the distance function from the `ExpressionStep` outputs and re-appended
the rewritten `_distance` alias at the end, changing the header column order.
Steps created above the `Sorting` before the rewrite runs - the local top-N
`Limit` and the exchange steps of a distributed plan - kept the original order,
and `makeDistributedPlan` failed to rebuild the plan fragments with a logical
error: "Cannot add step Limit to QueryPlan because it has incompatible header
with root step Sorting". Reinsert the rewritten output at the original position
instead.

Found by AST fuzzer:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=42701&sha=019244e0d46b4d9029fc261a549e1c5cd79b1bbb&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
#42701

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f1447bf]

Summary: ✅


AI Review

Summary

This PR now covers the original header-order mismatch in the no-rescoring vector-search rewrite plus the follow-up carrier edge cases around filters, row policies, deferred FINAL filters, and dotted-column names. After reading the current diff, the touched code in context, the full prior thread history, and the latest CI state, I did not find a remaining correctness, safety, or PR-metadata issue that warrants a new review comment.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit f1447bf.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.60% 79.70% +0.10%

Changed lines: Changed C/C++ lines covered: 32/39 (82.05%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 12, 2026
@shankar-iyer shankar-iyer self-assigned this Aug 12, 2026
alexey-milovidov and others added 3 commits August 13, 2026 05:32
…sumes the vector column

The bailout only checked whether the vector column itself (or an alias of it) is an output
of the expression under the `Sorting` step. An output consuming the column indirectly kept
its INPUT node alive while `replaceVectorColumnWithDistanceColumn` removed the column from
the read header. The reachable case is a filter condition over the vector column, e.g.
`WHERE length(vec) = 2 ... ORDER BY L2Distance(vec, ...) LIMIT 3` with
`vector_search_with_rescoring = 0` failed with `NOT_FOUND_COLUMN_IN_BLOCK` under both
analyzers, because the rewrite removed only the vector column output from the filter DAG.

Make the bailout dependency-based: skip the optimization if any output other than the
ORDER BY distance expression transitively consumes the vector column INPUT, in both the
pre-sort expression DAG and the filter/PREWHERE DAG.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f1447bf14 with master 33e5818c7 (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

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (04e5aa1) to get a fresh CI run.

The only red on the previous run was Stress test (amd_debug) with Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (STID 6726-6874). This is unrelated to this PR — it is the fleet-wide failure tracked in #114368 (stale set skip-index granule decoded with the new column type after ALTER MODIFY COLUMN + KILL MUTATION), and the fix is in progress in #112484.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed the private sync regression in https://github.com/ClickHouse/clickhouse-private/pull/68602: worker reads now serialize the rewritten column list, so _distance matches the worker plan header. Pushed ceab12a5c9b to sync-upstream/pr/114457.

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

No query shows a performance change that can be attributed to this PR. Only clickbench Q34 was flagged: its median went from 1256 ms to 1175 ms (-6.4%), which is inside master's current range of 1093-1370 ms, so it was correctly treated as no change. The diff only touches the no-rescoring vector-search rewrite and how row-level filters are handled under it, plus copying deferred row-policy filters when a read step is cloned. None of the ClickBench or TPC-H queries use vector search, row policies or FINAL, so these benchmarks don't run that code. The result fits a correctness fix with no performance cost on these workloads.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 2e32bfe9-0b92-4548-82ea-584eb086f668
  • MIRAI run: e9c5e0dd-e984-4320-b783-aaa71f53cc0a
  • PR check IDs:
    • clickbench_3462950_1791251268
    • clickbench_3462963_1791251268
    • clickbench_3462969_1791251268
    • tpch_adapted_1_official_3462981_1791251268
    • tpch_adapted_1_official_3462992_1791251268
    • tpch_adapted_1_official_3463020_1791251268

Keep the search column in the read header when a row-level filter DAG consumes it, and cover the no-rescoring path with a row policy regression test.\n\nhttps://github.com//pull/114457

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 19, 2026
alexey-milovidov and others added 4 commits September 19, 2026 11:49
…ctor search column

`findSearchColumnInput` accepted any input whose name ends in `.` plus the
unqualified search column name. For a table that has an indexed column `vec`
next to a `Nested` column `n` with an element `vec` (a physical column literally
named `n.vec`), a filter or row policy over `n.vec` was mistaken for a consumer
of `vec`, so `vector_search_with_rescoring = 0` silently fell back to rescoring
even when only the `ORDER BY` used the real vector column.

Resolve the input the same way `optimizeVectorSearchWithQuantizedCodes` does for
dotted names: an exact match always wins, and the fallback strips only a single
leading table qualifier and skips a candidate that is itself a physical column
of the table.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…umn's leaf name

`05230_vector_search_no_rescoring_dotted_column_name` covers the case the review
pointed at: a table with an indexed `vec` next to a `Nested` column `n`, whose
element is the physical column `n.vec`. A filter `has(n.vec, [9.])` must not be
taken for a consumer of `vec`, so the no-rescoring rewrite has to stay applied.

Proved with a control binary carrying the previous suffix match: the plan-shape
assertion counts `0` instead of `1` there, so the test really fails without the
fix. `length(n.vec)` is not usable for this - it is rewritten to the `.size0`
subcolumn, whose name does not end in `.vec`.

The test also keeps a negative case: a filter over `vec` itself must still
disable the rewrite.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ger exists

Since v26.9 the server rejects `enable_analyzer = 0` with
`SETTING_CONSTRAINT_VIOLATION`, so after merging `master` the old-analyzer
queries in `04871_vector_search_no_rescoring_vector_column_consumers` and
`04907_vector_search_no_rescoring_row_policy` fail. Remove them together with
the now-pointless `no-old-analyzer` tag of `04907`; the remaining queries cover
the same carriers through the analyzer.

Also reword the comment on `findSearchColumnInput`, which referred to the old
analyzer as the producer of a table-qualified input name. The fallback that
strips a single qualifier is kept, because it is safe in both directions: a
missed consumer would turn into `NOT_FOUND_COLUMN_IN_BLOCK` at runtime.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was 5720 commits / 10 days behind) and addressed the ⚠️ Request changes verdict.

  • Review finding adopted (774bd4ca04cc): findSearchColumnInput no longer accepts any input whose name merely ends in . plus the search column. An exact match wins; the fallback strips exactly one leading qualifier and rejects a candidate that is itself a physical column of the table, which is what separates a qualified tab.vec from the Nested element n.vec.
  • Regression test 05230_vector_search_no_rescoring_dotted_column_name (306f5d9dedb0). One correction to the suggested repro: length(n.vec) does not trigger the bug, since it is rewritten to the n.vec.size0 subcolumn; has(n.vec, [9.]) does. Proved with a control binary carrying the old suffix match - the plan-shape assertion counts 0 there instead of 1.
  • Pre-existing test breakage fixed (ed06e5ed3e3e): since v26.9 the server rejects enable_analyzer = 0 with SETTING_CONSTRAINT_VIOLATION, so the old-analyzer queries in 04871 and 04907 would have gone red right after the master merge. Removed them along with the now-pointless no-old-analyzer tag on 04907; the analyzer queries cover the same carriers.

Verified against a server built from this branch: 04852, 04871, 04907, 05153 and the new 05230 all pass, and the whole vector_search family is 72/74 - the two failures are environmental in a bare local server (02354_vector_search_distributed_index_analysis needs the parallel_replicas cluster, 04040_vector_search_cache_eviction_on_mutation needs the index-cache configuration).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114457&sha=1dbd13b5e3beeecface74459274393e84fe17995&name_0=PR&name_1=Stress%20test%20%28amd_msan%29 (Logical error: 'GroupingAggregatedTransform pushed bucket 1 twice', STID 3994-4c1d) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is tracked in #115986 and is unrelated to this PR (vector search plan rewrite only); the branch already contains #114523. All other checks are green, the AI Review verdict is ✅, and there are no unresolved review threads.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. The aborting query is 04878_distributed_plan_shuffle_bucket_order_promise's remote() GROUP BY with distributed_plan_force_shuffle_aggregation = 1, run with enable_cascades_optimizer = 1. That is the Cascades path fixed by #119814 (yours, merged 2026-09-25), not the rule-based path #114523 fixed, so there is no new PR from me. The job built be7b9ba1 (1dbd13b5 merged into master 365470f5), which predates #119814, and the head is still 1dbd13b5, so a master merge picks the fix up.

…eader-order

Conflict in `useVectorSearch.cpp`: master independently added exact-match
bailouts for the projection, filter and row-policy consumers of the vector
column (`is_search_column`, pruned DAG copies). They cover the same cases as
this PR's `findSearchColumnInput` / `anyOutputConsumesInput` guards, so master's
version is kept and the PR's duplicate guards and helpers are dropped. The PR's
header-order fix, deferred PREWHERE bailout and `ReadFromMergeTree` changes are kept.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master (d96121cf5b0d) to resolve the conflict and pick up #119814, which @groeneai identified as the fix for the Stress test (amd_msan) failure (GroupingAggregatedTransform pushed bucket 1 twice, Cascades path) — thanks.

Conflict resolution in useVectorSearch.cpp (8de6dffdae6): master independently gained exact-match bailouts for every consumer of the vector column (projection, WHERE/PREWHERE, active and deferred row policy) via pruned DAG copies and is_search_column. They cover the same cases as this PR's findSearchColumnInput / anyOutputConsumesInput / findPassthroughOutput guards, so master's version is kept and the duplicate guards were dropped. What remains of this PR: reinserting the rewritten distance output at its original position (the header-order fix), the deferred-PREWHERE bailout, the row-policy passthrough removal and deep copy of the deferred row-level filter in ReadFromMergeTree, and the five tests.

Verified on a local build: 04852, 04871, 04907, 05153 and 05230 pass; the rest of the vector_search family is green apart from 7 tests that need the CI server config (system.query_log, the parallel_replicas cluster, S3 storage policies, custom_local_disks_base_directory).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114457&sha=8de6dffdae69fbc7088271f9af08e344f2932a5f&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, flaky, unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

The fix is in progress: #123790 (it includes the change from my #123774, closed in its favor). In its own run on 2a290a03b667, 05237_with_expression_alias_scope_descendant passes in the arm_binary DBReplicated job.

The failure on 8de6dffdae69 has the same diff as on the other PRs (view 10, stored alias is bare 0). It is deterministic in that job, and the 71 reruns pass only because the diagnostics rerun runs without --replicated-database (my open #112247 fixes that). The new head f1447bf14376 includes #123789, so it will not run this job until #123790 brings it back with the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. The 05237_with_expression_alias_scope_descendant failure is tracked by #123790 and has nothing to do with this PR. On the current head f1447bf1437, every CI job passes except CH Inc sync. The sync robot asked for a manual merge, and the merge went through without conflicts: origin/master + f1447bf1437 are now pushed to the private sync PR, which is MERGEABLE, so the check should go green once private CI reruns.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 6, 2026
Merged via the queue into master with commit 640dc19 Oct 6, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-vector-search-header-order branch October 6, 2026 09:54
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 6, 2026
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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants