Skip to content

Keep the primary key conditions at the end of PREWHERE next to a condition that cannot use the key - #131360

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:prewhere-pk-tail-non-key-conjunct
Nov 14, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:prewhere-pk-tail-non-key-conjunct

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #131131

Changelog category (leave one):

  • Performance Improvement

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

A condition on a primary key column that cannot use the primary key, such as a join runtime filter on the join key or key LIKE '%x', no longer moves the other primary key conditions out of the end of PREWHERE, so the more selective conditions run first. The second query of #131131 with enable_join_runtime_filters = 1 is about 1.4x faster.

Description

Second query of #131131 (#131131 (comment)): with enable_join_runtime_filters = 1, PREWHERE on t2 ORDER BY (c1, c2, c7) first ran c2 = 'e3', which keeps 99% of the rows, and only later c9 = 'i9', which rejects all of them.

move_primary_key_columns_to_end_of_prewhere keeps the conditions on a contiguous key prefix at the end of PREWHERE. Since #106337, MergeTreeWhereOptimizer::analyzeImpl groups conditions by column set and gives each group one key position, which is none when a member cannot use the key. The runtime filter __applyFilter(rf, c1) reads only c1, so it joined the group of c1 IN (...), key position 0 was lost, and no key condition stayed at the end. key IN (...) AND length(key) = 2 or AND key LIKE '%1' does the same.

Change, in analyzeImpl only:

Validation: the new test prints 0 0 0 before and 1 1 1 after (runtime filter, length(key), position(key) guard group); 50/50 randomized runs. New perf test (the issue's query, 60M rows), local release perf.py: PR / master = 0.69-0.71. On the issue's data (120M rows, release, n=10): 0.700 s -> 0.478 s with runtime filters (0.450 s without), reading 2.69 GB instead of 4.48 GB; results identical. 05056_pr_local_plan_runtime_filter_read_mode: its EXPLAIN now prints the remote branch's filter as one expression (display only), and allow_reorder_prewhere_conditions is clamped to 1 there.

The first query of #131131 is still not reproduced as a slowdown on OSS builds.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2272-master (included in 26.11 and later)
  • Backported to: 26.10.5.26

…ition that cannot use the key

`move_primary_key_columns_to_end_of_prewhere` keeps the conditions on a contiguous primary key prefix at
the end of PREWHERE, computed from the key positions of the conditions. `analyzeImpl` groups conditions by
column set and gives each group one key position, which is "none" as soon as one member cannot use the key.
So a condition on a key column that cannot use the key (a join runtime filter `__applyFilter(rf, key)` on
the join key, `length(key) = 2`, `key LIKE '%1'`) joined the group of `key IN (...)`, the prefix lost
position 0, and every key condition fell back to the cost order: `PREWHERE` could first run a condition
that keeps almost all rows (`c2 = 'e3'` before `c9 = 'i9'` on the second query of ClickHouse#131131).

A conjunct now joins a group only if it agrees with it on whether it can use the primary key. Groups that
keep a condition that may throw behind its guard are not split; the key prefix counts each of their
members that can use the key.

Related: ClickHouse#131131

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings, then 0 on the fix round) plus my own review (4 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The runtime filter case of the new test does not assert that the filter is in PREWHERE, so it passes without testing when the filter is left in a separate step (query_plan_merge_filters is randomized) AGREE, fixed @ fe1775a query_plan_merge_filters pinned to 1; the case also requires __applyFilter(..., key) in the same PREWHERE expression
2 ⚠️ With move_all_conditions_to_prewhere = 0 the split groups count the same column twice in the move threshold DISAGREE Non-default setting (no compatibility entry). The threshold already counts a column shared by two moved conditions twice, and did so for this exact case before #106337 (one condition per conjunct). A key condition left in WHERE at the threshold is what the end-of-PREWHERE rule intends for key conditions
3 💡 query_plan_optimize_prewhere in the test is obsolete AGREE, fixed @ fe1775a removed
4 💡 For a LowCardinality join key the runtime filter is __applyFilter(rf, _CAST(key)), which counts as a condition that may throw, so it stays grouped with key IN DISAGREE The key prefix is still restored (the other key conditions keep the end of PREWHERE); splitting or moving such groups would let a throwing condition run before its guard (#131054)

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-10:20261113-153700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05629_prewhere_primary_key_tail_with_non_key_condition prints 0 0 0 on the base build every run (no randomization); the second query of #131131 reads 4.48 GB instead of 2.69 GB with runtime filters on every run.
b Root cause explained? Yes. Since #106337 analyzeImpl gives each condition group one primary key position, none if any member cannot use the key. A runtime filter on the join key (or length(key) = 2, key LIKE '%1') joined the group of key IN (...), position 0 left pk_positions, the contiguous prefix of move_primary_key_columns_to_end_of_prewhere became empty, and every key condition was cost-ranked, so c2 = 'e3' (keeps 99%) ran before c9 = 'i9' (rejects all).
c Fix matches root cause? Yes. The key position is kept where it was lost: conditions are grouped only with conditions that agree on key usability, and guard groups (which must keep their order) contribute each key member's position to the prefix. No runtime-filter special case, no setting.
d Test intent preserved / new tests added? Yes. New stateless test with three cases (runtime filter, length(key), position(key) guard group; the first also checks that the runtime filter is in PREWHERE); dropping either rule fails at least one case. New perf test with the issue's query. 05056 reference updated for the intended plan change (display of one filter), with allow_reorder_prewhere_conditions clamped to 1 so it stays stable.
e Both directions demonstrated? Yes. Base 0 0 0, fix 1 1 1; rule (a) alone 1 1 0, rule (b) alone 0 0 1. 50/50 randomized runs pass. Local release perf.py: PR / master = 0.69-0.71.
f Fix is general across code paths? Yes. Both grouping kinds are handled (exact column sets, and storage-column guard groups including subcolumns at several key positions). The allow_reorder_prewhere_conditions = 0 and move_primary_key_columns_to_end_of_prewhere = 0 paths are unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes: String key, Nullable key with the ANTI join form or(rf, isNull(key)), seven condition shapes, JSON subcolumn key. With a LowCardinality key the runtime filter reads _CAST(key) and is a guard group: the key prefix is restored there, the group keeps its previous place.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; move_primary_key_columns_to_end_of_prewhere = 0 gives the old placement.
i Invariants and contracts preserved? Yes. Guard groups are formed exactly as before and keep their written order; a group's own key position and estimate are unchanged; the prefix can only grow; query results are identical in every measured variant.

Session id: cron:clickhouse-impl-slot-6:20261113-152500

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fe1775a]

Summary: ✅


AI Review

Summary

The PR preserves the primary key prefix at the end of PREWHERE when another condition on the same columns cannot use the primary index, while keeping guard groups intact. Reviewed the current code, full diff, and all prior discussion for fe1775a33eec4ba0f6fe83eeb3680199d81f24ba. No actionable findings; the focused regression test passed in Fast test, and the PR provides before/after performance measurements.

Missing context / blind spots
  • ⚠️ Broader sanitizer, distributed, and performance CI jobs were still pending at review time. Their completed results would close the remaining CI validation gap. Tests and benchmarks were not independently rerun locally; performance evidence comes from the measurements recorded in the PR.
Final Verdict

Status: ✅ Approve. No review changes required.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fe1775a33 with master d89be9791 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.60, programs/clickhouse-keeper ×0.63 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.8 s 11.7 s +8.2 s (+238%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.2 s +5.2 s (+257%)
Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Nov 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 977d79f Nov 14, 2026
606 of 608 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 14, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 16, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 16, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 16, 2026
Backport #131360 to 26.10: Keep the primary key conditions at the end of PREWHERE next to a condition that cannot use the key
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants