Skip to content

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 into
backport/26.3/118697from
cherrypick/26.3/118697
Nov 15, 2026
Merged

robot-clickhouse-ci-2 merged 7 commits into
backport/26.3/118697from
cherrypick/26.3/118697

Conversation

@robot-clickhouse

Copy link
Copy Markdown
Member

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-pick locally.
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:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 6 commits September 8, 2026 01:51
…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]>
…on-with-if-short-circuit

Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation
@robot-clickhouse robot-clickhouse added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Nov 13, 2026
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]>
@groeneai

Copy link
Copy Markdown
Collaborator

I cannot push to cherrypick/*, so I resolved the conflict on my fork. The branch is a merge of backport/26.3/118697 into cherrypick/26.3/118697, so it fast-forwards the cherry-pick branch:

git fetch https://github.com/groeneai/ClickHouse groeneai/resolve-26.3-cherrypick-118697 && git push origin FETCH_HEAD:cherrypick/26.3/118697
  • The only conflict is next to aggregateFunctionPreservesNullPayload (Do not rewrite NULL-preserving aggregates with optimize_rewrite_aggregate_function_with_if #107430), which is not on 26.3. That region is kept as on 26.3 and only branchCanBeSkippedByShortCircuit is added, so the diff against backport/26.3/118697 is the 3 files of Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation #118697 with its own +153/-0.
  • 26.3 is affected: on the official 26.3.63.121, SELECT sum(if(number = 0, 0, intDiv(42, number))) FROM numbers(5) fails with ILLEGAL_DIVISION at default settings, and returns 87 with optimize_rewrite_aggregate_function_with_if = 0.
  • Checked on a debug build (clang-21) of the resolved tree: 05137_rewrite_aggregate_function_with_if_short_circuit passes, also in 50 runs with random settings, and fails on 26.3.63.121 and on the same tree without the source hunk. The other related stateless tests give the same results with and without the source hunk.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai: I pushed your resolution (623ce1b2e97b, the merge of backport/26.3/118697 into cherrypick/26.3/118697) to the cherry-pick branch as a fast-forward. The diff against backport/26.3/118697 is only the 3 files of #118697, and RewriteAggregateFunctionWithIfPass.cpp passes a syntax check against the 26.3 tree.

@robot-clickhouse-ci-2
robot-clickhouse-ci-2 merged commit 5ee4578 into backport/26.3/118697 Nov 15, 2026
2 checks passed
@robot-clickhouse-ci-2
robot-clickhouse-ci-2 deleted the cherrypick/26.3/118697 branch November 15, 2026 05:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants