Skip to content

Stop re-filtering columns that no later PREWHERE step reads - #128452

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:prewhere-steps-drop-unneeded-columns
Nov 1, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:prewhere-steps-drop-unneeded-columns

Conversation

@groeneai

@groeneai groeneai commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128432
Related: #124498
Related: #118630
Related: #125670

Changelog category (leave one):

  • Performance Improvement

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

A PREWHERE split into several read steps no longer filters again, at each step, the columns that only earlier steps used (their inputs and the results of their conditions). ClickBench Q42 and Q43 are 12-14% faster.

Description

Each step of a multi-step PREWHERE filters the whole read result, so every column in it is filtered again by every later step. Two kinds of them were never read again:

Now the readers chain keeps the projected-out columns only up to the last reader that may evaluate defaults (mayLeaveColumnToMissingDefaults, a superset of the cases fillMissingColumns defers), and a step removes its condition unless a later step or an output uses it, or it is a stored column (it can be the parent of a subcolumn missing in the part). The split PREWHERE on Memory drops the condition results too. #118630 changes the same decision: whichever lands second ORs its condition into keep_additional_columns. A stored column named like a split condition (#124484) now fails with NOT_FOUND_COLUMN_IN_BLOCK on MergeTree instead of returning wrong values, and returns its values on Memory; #125670 fixes that class.

Measured locally, master c189bd99 vs this PR (ThinLTO, 16 pinned cores, 10 alternating pairs): Q43 -14.2%, Q42 -11.9%, Q41 -9.1% at 4 threads; with use_columns_cache = 1 Q39 -16.8%, Q43 -13.6%; ReadResult::applyFilter falls from 7.9% to 0.1% of Q43's CPU samples. The first query of prewhere_combine_filters.xml: -25% and -28%. Nothing got slower.

Correctness: 39 differential queries and 856 related stateless tests match master. Two queries added to existing tests fail if either removal guard is dropped.

Analysis and patch by @ snelheidai in #128432.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1052-master (included in 26.11 and later)

groeneai and others added 3 commits November 1, 2026 05:19
…y evaluate defaults

`ReadResult::additional_columns` holds the columns each PREWHERE step projects out. Since ClickHouse#111795 they are
carried across all later steps, so every later step filters them again in `ReadResult::applyFilter`. Their
only consumer is `MergeTreeReadersChain::evaluateMissingDefaults`, which runs only when a later reader's
`fillMissingColumns` leaves a requested column unfilled: a column with a default expression, or a subcolumn
whose parent is available.

`mayLeaveColumnToMissingDefaults`, next to `fillMissingColumns` and built from the same `hasDefault`, is a
superset of those two cases. `IMergeTreeReader::mayEvaluateMissingDefaults` applies it to the requested
columns. The chain asks every reader but the first one (it has no earlier step) when it is built, once per
read task, and the reader caches the answer because it is reused by the consecutive read tasks of a part:
without the cache the check took 1.7% of ClickBench Q3 in the reporter's profile. Only the steps before the
last reader that may evaluate defaults keep the columns. A `chassert` in `evaluateMissingDefaults` checks the
superset on every default evaluation.

`executePrewhereActionsAndFilterColumns` takes `keep_additional_columns` instead of `is_last_reader`, whose
only use there was this decision. ClickHouse#118630 introduces the same parameter for the same decision.

Found and analysed by @ snelheidai in ClickHouse#128432.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…g later uses it

ClickHouse#71539 (8c2e541) replaced the by-name removal of intermediate filter columns with a check on
`Step::original_node`, but never assigned it. So every step but the last kept its condition result until the
end of the read, and each later step filtered it again.

Assign `original_node` for a single-condition step; the existing `node_to_step` / `all_outputs` check then
decides whether a later step or an output of the PREWHERE still uses it. The AND of several conditions of one
step is a node the steps create, nothing else references it, so it is always removed. A condition that is a
stored column stays: a later step may read it as the parent of a subcolumn missing in the part. Removing it
too returned `f.null = 1` for `SELECT f.null ... PREWHERE f AND x = 1` while `MODIFY COLUMN f Nullable(UInt8)`
is pending (0 with this change, as on master and with WHERE).

This also drops the condition columns of the split PREWHERE on `Memory` (ClickHouse#124498).

Tests: the pending-MODIFY query in `04628_multistep_prewhere_default_column`, and a step whose condition a
later step reuses in `02559_multiple_read_steps_in_prewhere_reuse_computation`. Both queries pass on master
as well; they fail if the stored-column or the later-use guard is dropped.

Found and analysed by @ snelheidai in ClickHouse#128432.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the line on why mayEvaluateMissingDefaults is cached (a reader is reused by the consecutive read tasks of a part); it describes the new code's design.

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

groeneai commented Nov 1, 2026

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

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The added queries stay green if both removals are disabled; add a mechanism-level assertion DISAGREE The oracle of the optimization is the perf suite: prewhere_combine_filters.xml query #0 runs on PRs and moves -25% / -28% with this change, so a revert is a flagged slowdown. No ProfileEvent or system table exposes per-step columns; an assertion would need new counters or a grep of the LOG_TEST dump. The added queries guard the two removal conditions (dropping either fails them).

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

Session id: cron:clickhouse-review-slot-9:20261101-053800

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. send_logs_level = 'test' on a 3-condition PREWHERE shows 1, 2, 2 condition columns plus additional_columns after the steps on master and 0 columns with this PR; ClickBench Q37-Q43 A/B on ThinLTO binaries, 10 alternating pairs.
b Root cause explained? Every step filters the whole read result. The inputs a step projects out are kept for all later steps (#111795) although only evaluateMissingDefaults reads them, and intermediate condition results are kept because #71539 never assigned Step::original_node.
c Fix matches root cause? Yes. Projected-out columns are kept only up to the last reader that may evaluate defaults; a condition is removed when no later step or output uses it and it is not a stored column. No setting, no threshold.
d Test intent preserved / new tests added? The #111795/#117533 tests (04628, 04629, 05227) and 02559* pass. Two queries added to existing tests (04628, 02559 reuse) fail when the stored-column guard or the later-use guard is dropped; they pass on master.
e Both directions demonstrated? Q43 -14.2%, Q42 -11.9% (4 threads), Q39 -16.8% (columns cache), applyFilter 7.9% -> 0.1% of Q43's samples; the first query of prewhere_combine_filters.xml -25%/-28%. Mutants of each guard fail the tests; master passes them.
f Fix is general across code paths? All evaluateMissingDefaults callers (PREWHERE readers, MergeOnKey patch keys), every reader subclass, merges via MergeTreeSequentialSource, Memory split PREWHERE (re-reads physical columns), Parquet V3 (ignores remove_filter_column).
g Fix generalizes across inputs (params/datatypes/wrappers)? 39 differential queries match master: Wide/Compact, missing DEFAULT/MATERIALIZED/Nullable defaults, Tuple/Nested/.null subcolumns, Nullable/LowCardinality/LC(Nullable), reused and selected conditions, patch parts, FINAL, Memory, query_plan_merge_filters = 0.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or on-disk change.
i Invariants and contracts preserved? The keep predicate is a superset of fillMissingColumns's deferral cases, checked by a chassert in evaluateMissingDefaults (it trips when the subcolumn case is dropped). A removed condition is never an input of a later step or an output. The per-reader cache is used by one thread at a time.

Session id: cron:clickhouse-impl-slot-5:20261101-023600

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @CurtizJ, could you review this and add the can be tested label so CI runs? Every step of a multi-step PREWHERE filters the whole read result, and two kinds of columns rode along to the end: the inputs a step projects out (now kept only up to the last reader that may evaluate missing defaults) and the intermediate condition results (Step::original_node was never assigned after #71539).

@clickhouse-gh

clickhouse-gh Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [db22610]

Summary: ✅


AI Review

Summary

This PR reduces repeated filtering in multi-step PREWHERE by releasing projected-out columns after the last reader that may evaluate missing defaults, and removing intermediate condition results when no later step or output needs them. Review of the current diff and affected callers found no actionable correctness, safety, or compatibility issues. The reported before/after measurements support the performance claim, and both modified regression tests pass in CI at db22610a975e94d54717b85ea4466da4ab270da1.

Final Verdict

Status: ✅ Approve

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

clickhouse-gh Bot commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing db22610a9 with master c189bd99f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 1ee49128d; 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

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Nov 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 1, 2026
Merged via the queue into ClickHouse:master with commit 054ef0c Nov 1, 2026
529 of 531 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 1, 2026
alexey-milovidov added a commit that referenced this pull request Nov 4, 2026
…umn-117023

Conflict with #128452 (`keep_additional_columns` passed by the caller): keep master's decision,
and additionally keep the projected-out columns when patch parts are read, because
`applyPatchesAfterReader` evaluates `DEFAULT` columns again from them.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 7, 2026
Master no longer reproduces the AMBIGUOUS_COLUMN_NAME: since ClickHouse#128452 an
intermediate PREWHERE step removes its filter column when nothing later uses it,
so the ON copy is gone before the WHERE copy with the same name is computed.
The renaming in `tryBuildPrewhereSteps` is therefore dropped, and the file is
restored to its version at the base of this branch (which also stops the PR
from conflicting with ClickHouse#124553, which removed `columns` from that function).

`05427` stays as a regression test: it passes on master 5b24a5f and fails
on 26.10.2.103 with Code 352 in 8 of its 9 queries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
thevar1able pushed a commit to actueleai/ClickHouse that referenced this pull request Nov 24, 2026
… runtime filter in the query condition cache"

This reverts commit 64da8a0, reversing
changes made to be89302.

Conflicts resolved by keeping the later changes in the same lines:
`is_query_prewhere` (ClickHouse#130645), the `last_reader_evaluating_defaults`
argument (ClickHouse#128452), `readsSameColumns` (ClickHouse#124880), `follows_top_k_filter`
(ClickHouse#129882), and the PREWHERE query condition cache write of ClickHouse#115522 in
its own form before it merged ClickHouse#122380.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants