Skip to content

Combine the filters of PREWHERE steps when the later conditions cannot throw - #128582

Merged
murphy-4o merged 15 commits into
ClickHouse:masterfrom
groeneai:prewhere-combine-step-filters
Nov 6, 2026
Merged

murphy-4o merged 15 commits into
ClickHouse:masterfrom
groeneai:prewhere-combine-step-filters

Conversation

@groeneai

@groeneai groeneai commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128442
Closes: #128454
Related: #125978
Related: #128342

Changelog category (leave one):

  • Performance Improvement

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

Faster PREWHERE with several conditions: the block is filtered once instead of after every condition when the later conditions cannot throw. ClickBench Q38 is up to 10% faster.

Description

With query_plan_merge_filters = 1 every PREWHERE read step filters its block, so a later condition never sees the rows an earlier one rejected. When the steps keep most rows, this copies every column once per step.

Core change, in tryBuildPrewhereSteps: a step skips its filter when the next step's conditions pass canBeMovedToTheFrontOfAndChain, the reader neither converts nor fills PREWHERE columns, and the last step filters. ReadResult::optimize then applies the combined filter once.

Enablers, so that common conditions qualify:

  • A comparison with a constant string that converts to the other argument's type cannot throw (EventDate >= '2013-07-01').
  • empty/notEmpty cannot throw (URL <> '').
  • The first commit is Fix exception-safety classification for Tuple comparisons #125978 (Tuple comparisons), which this relies on; it drops out if that PR lands first.

Also: predicate_statistics_log counts the rows that passed all steps so far, so its numbers stay right when a filter is deferred.

TODO: only conditions whose functions describe that they cannot throw (canThrowIfKnown) qualify; any other function keeps the step filter. A follow-up could defer every step filter instead and, if a step throws, apply the accumulated filter and evaluate it again, so the plan-time check reduces to stateless, deterministic, no side effects.

Measured locally (one-part hits, max_threads = 4, 20 alternating pairs): Q38 -10.1%, Q43 -5.5%, Q37 -4.7%, Q42 -3.5%, same memory.

Analysis and patches by snelheidai.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1486-master (included in 26.11 and later)
  • Backported to: 26.10.11.9

groeneai and others added 12 commits November 2, 2026 00:36
…Throw`

Same change as ClickHouse#125978 (fixes ClickHouse#125919).

Co-authored-by: Shoryamishra61 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Moved unchanged so that the MergeTree PREWHERE splitter can use the same
contract. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ated on more rows

With `query_plan_merge_filters = 1` (the default since ClickHouse#71539) every PREWHERE
read step of a MergeTree read applied its filter to the whole block, to keep
short-circuit evaluation of merged filters. So a step that keeps almost all
rows still copied every column through its filter.

The forced filter is now skipped when the next step's conditions (and, before
the last step, the outputs computed in the last step) pass
`canBeMovedToTheFrontOfAndChain`, the reader neither converts nor fills a
PREWHERE column (`canReadPrewhereColumnsAhead`), and the last step filters.
The step filters are then combined and applied together by
`ReadResult::optimize`. `groups_requiring_filtered_input` is unchanged.

`system.predicate_statistics_log` now counts the rows that passed all steps so
far after `optimize`, so `passed_rows` and `total_passed_rows` stay the rows
surviving a step when an earlier filter was combined but not applied (also with
`query_plan_merge_filters = 0`).

Found, analysed and measured by @ snelheidai in ClickHouse#128442.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The same loop over the children of an `ActionsDAG` node was copied in
`ExpressionActions.cpp`, `actionsDAGUtils.cpp`, `FilterStep.cpp`,
`lazyFrontier.cpp` and the PREWHERE splitter. It is now one function,
`getDataTypesWithConstInfoFromNodes`, next to `ActionsDAG`. No behaviour
change: `ActionsDAG::Node::column` is a `ColumnConstPtr`, so the
`isColumnConst` check of `lazyFrontier.cpp` was always true when the
column was set.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A comparison with a constant string was classified by the types only, so
`d > '2010-01-01'` with `d Date` counted as able to throw, like a comparison
of a `Date` column with a `String` column, which parses every row. But the
constant is converted to the type of the other argument once, before any
row is compared (`executeWithConstString`), and then values of that type
are compared. `canThrowIfKnown` now repeats that conversion, with the same
function, format settings and unwrapping of `Nullable` and
`LowCardinality`, and asks `comparisonCanThrow` about the converted type.
A string that does not convert still counts as able to throw.

`DataTypeWithConstInfo` gets the constant column, set by
`getDataTypesWithConstInfoFromNodes`. Callers that do not know the value
pass nothing and get the previous answer.

So such a comparison can be moved in front of a condition that throws
(`short_circuit_function_evaluation_reorder_arguments`), and, with the
previous commit, a PREWHERE step before it does not have to filter its
block.

Found, analysed and measured by @ snelheidai in ClickHouse#128442 and ClickHouse#128454.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s cannot throw

They read only the sizes or the bytes of the values. `URL <> ''` is
rewritten to `notEmpty(URL)` (`optimize_empty_string_comparisons`), so
without this a PREWHERE step before it keeps filtering its block.

Same change as in ClickHouse#128342, which needs it for Parquet; it drops out when
either PR is merged first.

Found, analysed and measured by @ snelheidai in ClickHouse#128442 and ClickHouse#128454.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…re_combine_filters`

Once an earlier PREWHERE step has filtered, the reader filters a column read
by a later step by the filter so far and then by that step's own filter, so
the selected `String` of the last step is copied twice. With the filters
combined it is copied once.

The query selects `s`, so it is read in full (`s != ''` alone would read only
`s.size`), and its conditions are those of ClickBench Q37: cheap ones, a
`Date` compared with a string and a non-empty string. So the gain needs both
the combined filters and the classification of the comparison and of
`notEmpty` as unable to throw.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ombine_filters`

A column that a PREWHERE step reads and that is needed after PREWHERE stays
in the block, so every later step that filters copies it again. With the
filters of the steps combined it is copied once. The previous query read `s`
in the last step only, where this saves a single copy.

`s` is now read by the second of five steps and selected, so it is read in
full (`s != ''` alone would read only `s.size`). The step before `s != ''`
skips its filter only with the `notEmpty` classification, the step before
`d >= '2020-01-06'` only with the classification of a comparison with a
constant string.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
These walks pushed every child, so a node shared by several parents was
visited once per path, which grows exponentially with the depth of a DAG
whose levels reuse a column (for example nested subqueries merged into one
filter). `canBeMovedToTheFrontOfAndChain` now also runs for the steps of a
PREWHERE.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…emark

The constant 'abc' is rejected while the query is planned, also on master, so the arm of 05481 could
not tell whether the comparison is classified as able to throw. notEmpty now describes whether it can throw.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Without that check the query also passes when the PREWHERE is evaluated as
one step, where the counter of a deferred step filter is not exercised.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the obvious comment on getDataTypesWithConstInfoFromNodes and shorten three comments on the deferred PREWHERE step filters to one line each.

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

groeneai commented Nov 2, 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; 3 rounds, 4 findings, the last round none) plus my own review (3 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ canBeMovedToTheFrontOfAndChain visits a shared DAG node once per path, which is exponential on deep DAGs with shared nodes, and PREWHERE now calls it AGREE, fixed @ d8edb5f visited set in it and in the two FilterStep walks on the same atom
2 ⚠️ IExecutableFunction::execute does not pass the constant to canThrow for ColumnReplicated DISAGREE that path keeps the answer it gives on master (conservative, no wrong result); replicated-column compaction is a separate change
3 ⚠️ 04011 Q8 also passes when the PREWHERE is not split into steps AGREE, fixed @ 688b793 asserts two distinct step expressions; with enable_multiple_prewhere_read_steps = 0 the new column is 0
4 ⚠️ under parallel replicas the step expressions of Q8 could differ between the local plan and a remote replica DISAGREE dumpDAG is index-based, the secondary query names constants as the initiator does, and a plan-based replica receives the same prewhere_info
5 💡 05259 comment says notEmpty does not describe whether it can throw AGREE, fixed @ 9da21e5 remark removed
6 💡 05481 arm with d > 'abc' fails when the query is planned, also on master, so it tests nothing AGREE, fixed @ 9da21e5 arm removed
7 💡 changelog number measured at max_threads = 4 only AGREE, fixed "up to 10%"

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

Session id: cron:clickhouse-review-slot-8:20261102-063400

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. With send_logs_level = 'test' the PREWHERE actions dump shows NEED_FILTER per step: master 11111, this PR 00001, on the shapes of ClickBench Q37/Q38 and of the perf query.
b Root cause explained? Since #71539 every PREWHERE read step filters the whole block, also before conditions that cannot throw, so columns that a step reads and the query needs later are copied again by each later step. Comparisons with a constant string and empty/notEmpty counted as able to throw.
c Fix matches root cause? Yes. The filter is skipped where it is set (the splitter), only when the next conditions pass canBeMovedToTheFrontOfAndChain, the reader neither converts nor fills a PREWHERE column and the last step filters.
d Test intent preserved / new tests added? Yes. New 05480_prewhere_skipped_step_filter_reader_and_guard, 05481_comparison_with_constant_string_cannot_throw, a query in 04011_predicate_statistics_log, the 05259 cases of #125978, and a query in prewhere_combine_filters.xml. No existing query or reference changed.
e Both directions demonstrated? Yes. 05481 and the 05259 cases fail on master and pass here; 05480 fails when either guard of the splitter is removed; the perf query is -28.0% and -26.8% in two perf.py runs.
f Fix is general across code paths? Yes. The per-step filter flag has one consumer, and one helper builds DataTypesWithConstInfo from DAG nodes for every canThrow caller; callers that do not know the constant keep the previous answer.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 450 differential queries over Date, Nullable(Date), LowCardinality(Nullable(Date)), DateTime64, Decimal, Int32, Bool, UUID, IPv4/IPv6, Enum8, FixedString, Array, Map, Tuple, <=> and empty/notEmpty, at 1 and 16 threads, match master except the reordering case in the description.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or on-disk change; only queries that threw because a throwing condition ran first can now return a result.
i Invariants and contracts preserved? Yes. Rows rejected by a step whose filter is deferred reach only conditions that cannot throw and readers that neither convert nor fill; the last step always filters; system.predicate_statistics_log values are unchanged.

Session id: cron:clickhouse-impl-slot-5:20261102-034300

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @Algunenano, could you review this and add the can be tested label so CI runs? With query_plan_merge_filters every PREWHERE read step filters its block; this PR keeps the filter only before conditions that can throw (or when the reader converts or fills PREWHERE columns), and lets comparisons with a converting constant string and empty/notEmpty count as unable to throw, so the step filters are combined and applied once.

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aba6973]


AI Review

Summary

Combines PREWHERE step filters when later evaluation is safe, improves the exception classification of comparisons and empty/notEmpty, and preserves cumulative predicate statistics. Reviewed commit aba6973bab023d91959a43848245cceeb9f97a65 and the prior discussion. No actionable findings; focused regression coverage and before/after performance measurements support the change.

Missing context / blind spots
  • ⚠️ No local build or tests were run because this checkout has no ClickHouse binary or build directory. Runtime validation relies on the supplied measurements and available Praktika reports.
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. can be tested Allows running workflows for external contributors labels Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

3368 translation units recompiled, 18971 s compile time in total, 3366 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 8.1 s

Job report

@murphy-4o murphy-4o self-assigned this Nov 3, 2026
murphy-4o and others added 2 commits November 5, 2026 17:17
Keep `getDataTypesWithConstInfoFromNodes` file local and `canBeMovedToTheFrontOfAndChain`
in `FilterStep.cpp` (declared in `FilterStep.h`), so the other callers keep their argument
lists and the classification of comparisons with a constant string does not reach
`canBeExecutedOnMoreRows` and `canEvaluateOnPaddedRows`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@murphy-4o

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

# Conflicts:
#	src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp
@murphy-4o
murphy-4o added this pull request to the merge queue Nov 6, 2026
Merged via the queue into ClickHouse:master with commit 928c363 Nov 6, 2026
44 of 54 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 6, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 7, 2026
A conjunct on the top-K column that `canBeMovedToTheFrontOfAndChain` used to
share the `__topKFilter` step, so it ran on every row of the block, while in
WHERE it ran only on the rows the threshold passed: `SearchPhrase != 'zzzz'`
(passes every row) was slower with the previous commit alone. With its own step
the `__topKFilter` step's filter stays optional (ClickHouse#128582), so it is applied only
when it keeps < 60% of a block: while the threshold passes most rows both
conditions run on the whole block as before, once it is selective the condition
runs only on the surviving rows. Its column is read by the `__topKFilter` step.

Only with `read_ahead_columns`: without it ClickHouse#128582 forces the filter, and a
column-free step of a non-adaptive part would read its column again.

The losing shape is added to the performance test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 22, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Nov 22, 2026
Cherry pick #128582 to 26.10: Combine the filters of `PREWHERE` steps when the later conditions cannot throw
robot-clickhouse added a commit that referenced this pull request Nov 22, 2026
…en the later conditions cannot throw
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 22, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 22, 2026
Backport #128582 to 26.10: Combine the filters of `PREWHERE` steps when the later conditions cannot throw
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

6 participants