Repository navigation
Cherry pick #118697 to 26.3: Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation - #131321
Merged
robot-clickhouse-ci-2 merged 7 commits intoNov 15, 2026
Conversation
…n short-circuit evaluation
`optimize_rewrite_aggregate_function_with_if` lifts the non-constant branch of an `if` into
an `-If` combinator argument. The `-If` combinator has no lazy argument evaluation, so the
lifted branch is evaluated for every row, while `if` evaluated it only on the rows its
condition selected. A short-circuit guard such as
SELECT sum(if(number = 0, 0, intDiv(42, number))) FROM numbers(5)
therefore failed with a division by zero at default settings, because the rewritten
`sumIf(intDiv(42, number), number != 0)` ran the division on the rows the condition
excluded. Both `if` arms were affected, and it is not specific to `sum`: with a `NULL`
constant, `avg` and `count` failed the same way.
Refuse the rewrite when the branch about to be lifted is one that lazy execution would have
skipped. The condition is not invented for this fix. `findLazyExecutedNodes` already decides
laziness per node as
`force_enable_lazy_execution || has_lazy_child || isSuitableForShortCircuitArgumentsExecution`,
so the new guard mirrors those three terms, keyed on `short_circuit_function_evaluation`:
- `disable`: no guard, since `if` evaluates both branches there and the un-rewritten query
throws as well. The optimization is kept.
- `enable`: decline when the lifted subtree contains a short-circuit-suitable function.
The recursion covers `has_lazy_child`, and `FunctionIf::isShortCircuit` leaves
`force_enable_lazy_execution` false, so the suitability term alone decides here.
- `force_enable`: decline for any non-constant function, since every argument is lazy in
that mode regardless of suitability.
A constant is exempt because it is already evaluated while the query tree is built, which is
also what keeps `tests/performance/rewrite_aggregate_if.xml` on the rewritten path.
The walk stops at table and subquery nodes, and describes a function's arguments with
`FunctionNode::getArgumentColumns()` rather than by calling `getResultType()` on each of them.
Both matter. `getResultType()` is defined only for expression nodes, and the `in` family
carries a table expression or a subquery in its second argument slot, so asking it there
throws `UNSUPPORTED_METHOD` instead of answering; `getArgumentColumns()` reports that slot as
a set, exactly as the resolver did. And a subquery is evaluated in its own scope, as a set or
a scalar, so the laziness of the enclosing expression never reaches inside it: descending
there would decline rewrites that `findLazyExecutedNodes` allows.
The cost is that a branch lazy execution would have skipped stops being rewritten at default
settings: `intDiv`, `modulo` and `positiveModulo` over a non-constant divisor, `divide` over
`Decimal`, a cast, a string function. Bare columns, constants and `plus`/`minus`/`multiply`
keep the rewrite. IFunction.h blesses that trade for exactly this predicate: reporting an
expensive but safe function as throwing is safe and only loses an optimization, whereas the
converse is not.
`canThrow`, the literal wording of the second direction proposed in the issue, is not
reachable from a pass. It is declared on `IExecutableFunction` and `IFunction` but not on
`IFunctionBase`, which is what `FunctionNode::getFunction()` returns, and its default is
`isSuitableForShortCircuitArgumentsExecution` anyway.
Closes #85784.
Co-authored-by: Claude Opus 5 <[email protected]>
`branchCanBeSkippedByShortCircuit` descended the subtree by calling itself for every child. Drain an explicit worklist instead, the form the analyzer already uses for the same kind of subtree question (`isNodePartOfTree` and `isStorageUsedInTree` in `src/Analyzer/Utils.cpp`), so the walk no longer takes a stack frame per tree level. The predicate is unchanged. A `ConstantNode` and the table, table function, query and union node types still stop the descent without qualifying; a resolved `FunctionNode` that reports short-circuit suitability, or any resolved function under `force_enable`, still qualifies; anything else falls through to its children. The answer is an existential over the subtree, so the order nodes are visited in cannot change it. `05137_rewrite_aggregate_function_with_if_short_circuit` is untouched, and its 22 reference rows are reproduced value for value. Co-authored-by: Claude Opus 5 <[email protected]>
…rt-circuit Co-Authored-By: Claude Opus 5.5 <[email protected]>
…te-function-with-if-short-circuit
…on-with-if-short-circuit Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation
Resolve the conflict by porting only the hunks of #118697. The conflicting region holds aggregateFunctionPreservesNullPayload from #107430, which is not on 26.3, so it is left as on 26.3 and only branchCanBeSkippedByShortCircuit is added there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Collaborator
|
I cannot push to
|
Member
|
🕵 Thanks @groeneai: I pushed your resolution ( |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Original pull-request #118697
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Before you resolve anything
Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job