Repository navigation
Do not move a condition that can throw to PREWHERE in front of the conditions written before it - #129178
Conversation
…nditions written before it With `query_plan_merge_filters` the CTE filter `a = 'one'` and the outer `(b, toDateTime64(usage_timestamp, 3)) NOT IN (...)` are merged into one AND chain. Short-circuit `and` evaluates the second argument only on the rows passing the first, but `MergeTreeWhereOptimizer` chose the PREWHERE order by its cost tuple alone: `move_primary_key_columns_to_end_of_prewhere` ranked the primary key guard last, so the first read step parsed every row and threw CANNOT_PARSE_DATETIME. The same happened when the guard was not viable and stayed in WHERE, when the throwing conjunct was grouped with an earlier one on its column across the guard, with statistics (04053 recorded it as a known bug), and with `force_enable`. A condition that `and` would keep behind the arguments before it (some lazily executed function can throw, is stateful, has side effects or is not deterministic: the test of `findLazyExecutedNodes` / `canBeExecutedOnMoreRows`) is now a PREWHERE candidate only when it is the first condition left in WHERE, i.e. after every condition written before it was moved, and it joins a column group only if every conjunct between the group's first one and it belongs to the group. Other conditions are ordered as before. This is the rule from ClickHouse#100827 ("any prefix of the AND chain can be pushed down without checking, and conditions in the middle if they are not-throwing"). Reference changes: 02842 (`like` waits behind the conditions written before it), 04053 (the bug arm returns `good`), 05316 (a `LIKE` after an AI condition keeps both in WHERE, in the written order). Closes ClickHouse#83611 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the four added comment blocks in MergeTreeWhereOptimizer to one line each. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
cc @KochetovNicolai @Avogar, could you review this and add the |
|
Workflow [PR], commit [e92697f] Summary: ✅
AI ReviewSummaryAt Findings
Final VerdictStatus: ✅ Approve No additional changes required for this PR's accepted scope. The separately tracked Parquet limitation above remains open. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes8 object files changed (+34.05 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units12 translation units recompiled, 65 s compile time in total, 12 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.07 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
… short-circuit is disabled With `enable_multiple_prewhere_read_steps = 0` PREWHERE is one expression, and a node it passes on to the rest of the query (the `toDateTime64` the projection also needs) is an output, so it is not executed lazily and runs on every row whatever the order of `and`. The query from ClickHouse#83611 and `a = 'one' AND toDateTime64(s, 3) > X` selecting the conversion still failed with CANNOT_PARSE_DATETIME there, also when the guard and the conversion were grouped on one column or the guard was an explicit PREWHERE (`optimize_prewhere_after_pushdown = 1`). With one read step, a condition that must follow the preceding ones and computes a function node also needed by another conjunct or another output of the filter DAG is now moved only to an empty PREWHERE and is not grouped with earlier conjuncts. A condition without such a node keeps being moved, because there `and` still executes it lazily (holding every such condition back changed 02346, 03317, 05326 and 05316 with one read step, which CI randomizes). With `short_circuit_function_evaluation = 'disable'` nothing is executed lazily, so there is no order to keep: no condition must follow the preceding ones there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The result checks alone also pass if nothing is moved to PREWHERE with one read step. Check that the guard and a condition that cannot throw are still moved, also next to an explicit PREWHERE, and that a conversion nothing else needs is still moved. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…en steps with force_enable Apply the rule for a condition that computes a node needed outside it whenever PREWHERE may run in one step: with `enable_multiple_prewhere_read_steps = 0`, and when the filter DAG has a non-deterministic or stateful function, because Memory then evaluates PREWHERE in one step even with multiple steps enabled (`a = 'one' AND toDateTime64(s, 3) > X AND rand(x) >= 0` selecting the conversion threw CANNOT_PARSE_DATETIME on a Memory table). Applying it unconditionally was measured and rejected: it keeps a join runtime filter on a guarded CAST key out of the read (04630). With `short_circuit_function_evaluation = 'force_enable'` every function is executed lazily, but a PREWHERE step was asked to filter its rows only for conditions that are lazy by themselves or with `query_plan_merge_filters`. With `query_plan_merge_filters = 0` and a guard that passes more than 60% of the rows, the range reader did not filter, and `timestamp(s)` ran on the rejected row. Force the filter with `force_enable` as with `query_plan_merge_filters`. 05497 gets a check of the PREWHERE placement with multiple steps, the force_enable arm with a guard passing 90% of the rows, and the Memory arm. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp # src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp # src/Storages/MergeTree/MergeTreeWhereOptimizer.h
|
@groeneai resolve conflicts |
…tions-before-throwing-one The conflict in `MergeTreeWhereOptimizer::analyzeImpl` is resolved by keeping master's grouping key (physical columns for a guarded throwing condition, split by primary key use) and applying the PR's check that a condition that must follow the preceding ones does not join a group across conjuncts that are not in it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Resolved: merged master in 3fd8c02. The only conflict was in |
|
@groeneai the review-threads gate blocks this PR and the full CI suite was skipped on head 3fd8c02 (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=129178&sha=3fd8c0245d8ccfe48c8f73efa8a6be1ab27e416b&name_0=PR&name_1=Finish%20Workflow). Either fix the two remaining paths from the open thread on |
Memory evaluates PREWHERE in one step when the combined PREWHERE has a non-deterministic or stateful function. A user-written PREWHERE with `rand` merged with the moved WHERE (`optimize_prewhere_after_pushdown = 1`) did not count, because only the WHERE DAG was checked, so a conversion that the projection also needs was moved and computed for all rows. Check the existing PREWHERE too. With `short_circuit_function_evaluation = 'force_enable'` every function is executed lazily, but the PREWHERE step splitter still merged a condition on the guard's column into the guard's step when the function does not report itself suitable for short-circuit execution (`timestamp`). In one step the conversion passed on is computed for all rows. Give such a condition its own step under `force_enable`. Both shapes are from the review of ClickHouse#129178 and fail on master as well. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I fixed both paths in this PR instead of filing an issue, in f1d1188: the one-step check now also looks at the existing I did not resolve the thread myself: it was opened by clickhouse-gh, which resolves its own threads once its review accepts the fix, and the full suite re-runs after that. I will post the full CI result here when it finishes on this head. |
…g conditions `mustFollowPrecedingConditions` asked `canThrow` without the constant columns of the arguments, so `canThrowIfKnown` of `like`, `ilike` and `notLike` could not see the pattern and answered that the function can throw. Every `LIKE` with a constant pattern was therefore treated as a condition that must follow the conditions written before it: it was no longer moved to PREWHERE in front of them by cost, and not moved at all behind a condition that stays in WHERE. A `LIKE` on a `String` with a valid constant pattern cannot throw (the pattern is compiled once), and `prewhereConditionCannotThrow` and `canBeMovedToTheFrontOfAndChain` already pass the constant column for this reason. Pass the constant column here as well. The references of `02842_move_pk_to_end_of_prewhere` and `05316_ai_functions_last_in_prewhere` are back to what they are on master: a `LIKE` is ordered by cost again, and an AI function written before a `LIKE` runs in PREWHERE after it instead of on all rows in WHERE. Related: ClickHouse#129178
|
@groeneai and reviewers: I reviewed head 9f847e4 and pushed one fix. Nothing was built locally, so the new commit relies on CI. Fixed
The PR description needs an update: the sentences about Not fixed, needs a decision
Checked, no problem foundThe selection loop (a held-back condition moves only when it is the first one left in WHERE, also with the size threshold and with CINo test failures on 9f847e4: the only red job was |
AI review of a later commit does not approve the PR, see the AI Review comment.
|
Thanks for the fix and the review. CI on a7341e6: the full suite ran and finished with one failed test,
The same push updates the description: the |
Keeping a condition that can throw behind the conditions written before it costs the ordering by cost for every lazily executed function without `canThrowIfKnown` (`lower`, `position`, `has`, ...): such a condition is not moved in front of a condition that stays in WHERE. The only way to get the previous plans back was `short_circuit_function_evaluation = 'disable'`, and `compatibility` could not restore them. The new setting (default `true`, `false` below `compatibility` 26.11) turns the rule off for the PREWHERE optimizer only: with `false` the conditions are selected as with `disable`, and short-circuit evaluation stays enabled. As suggested in ClickHouse#100827. `05497`: the `disable` case now uses `lower`, because a `LIKE` with a constant pattern is no longer held back; a plan case for the setting and a control without it are added. Related: ClickHouse#129178 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master is 26.12 now, so the `settings_changes_history` style check requires the new setting's history record under the current version. With the record under 26.12, `compatibility` 26.11 and below restore the previous order. Related: ClickHouse#129178 Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - b486728Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261120-053111 |
|
@fm4v I need a decision on the
Two costs multiply: Should I (A) send the PR with these numbers in the description, or (B) not send it and leave |
|
I merged Since 2026-11-19, stateless tests randomize the MergeTree setting 🤖 Generated with Claude Code |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=4 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
|
@groeneai can you merge with master and fix the conflict? |
Resolve the comment conflict in MergeTreeSplitPrewhereIntoReadSteps.cpp by keeping both lines. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done: I merged current |
AI review of a later commit does not approve the PR, see the AI Review comment.
Closes: #83611
Related: #100827
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed queries failing with an exception like
CANNOT_PARSE_DATETIMEwhen the automatic move ofWHEREconditions toPREWHEREput a condition that can throw (for exampletoDateTime64of aString) in front of a condition written before it that excludes the offending rows. Such a condition is now moved only after the conditions written before it, as short-circuitandevaluates it. The new settingoptimize_move_to_prewhere_respect_short_circuit(enabled by default) controls this. Closes #83611.Description
On 26.10.2.103 (and 26.3, 26.8, master), the query from #83611 fails with
CANNOT_PARSE_DATETIME, although the CTE'sWHERE a = 'one'excludes the only row that cannot be parsed.Root cause.
query_plan_merge_filtersmerges both filters intoand(equals(a, 'one'), notIn(tuple(b, toDateTime64(...)))), whereandevaluates the second argument only on the rows passing the first.MergeTreeWhereOptimizerpicks PREWHERE conditions by cost only:move_primary_key_columns_to_end_of_prewhereranksa = 'one'last, so the first read step computestoDateTime64on every row. Likewise when the guard stays in WHERE, or via grouping, statistics orforce_enable. PREWHERE in one step (enable_multiple_prewhere_read_steps = 0, or Memory with a non-deterministic condition, also in a writtenPREWHERE) computes thetoDateTime64passed on to the projection on every row, in any order.Change. A condition that
andwould keep behind the conditions before it (a lazily executed function that can throw or is order-sensitive, as incanBeExecutedOnMoreRows) is moved to PREWHERE only after them and is not grouped across them. When PREWHERE may run in one step, one that also computes a value needed outside it is moved only to an empty PREWHERE. Withforce_enable, each condition gets its own PREWHERE step and every step filters its rows. This is #100827's rule. The new settingoptimize_move_to_prewhere_respect_short_circuit(default1,compatibilitybelow 26.12 sets0) restores the previous order, as doesshort_circuit_function_evaluation = 'disable'.Tests. New
05497fails on master in every case butdisable;05830keeps a constant-patternLIKEordered by cost.04053's bug case now returnsgood.Price. A function without
canThrowIfKnowncounts as one that can throw, solower(s) = 'x'stays in WHERE behind a condition that stays there, e.g. one reading every queried column (3x slower in the review). #100827's example on 10M rows takes 0.081 s vs 0.031 s on master.Workflow [PR]
Sync PR [sync-upstream/pr/129178]
Version info
26.12.1.213-master(included in26.12and later)