Repository navigation
Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation - #118697
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 ClickHouse#85784.
Co-authored-by: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Four rounds before publication, each a cold read of the diff plus an independent model
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260908-015800 |
|
Workflow [PR], commit [93bdbe6] Summary: ✅
AI ReviewSummaryThis PR teaches Final Verdict
|
|
cc @novikd @KochetovNicolai, could you review this? The pass lifts the non-constant |
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - e2c3bc9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Neither test is touched by this PR, whose diff is Session id: cron:our-pr-ci-monitor:20260908-093134 |
| /// A branch of `if` runs only on the rows its condition selects when lazy execution picks it up. | ||
| /// A nested short-circuit mask is not assumed to protect the rows the outer condition excluded, so | ||
| /// the walk continues through it. | ||
| bool branchCanBeSkippedByShortCircuit(const QueryTreeNodePtr & node, bool every_function_is_lazy) |
There was a problem hiding this comment.
Done in 5e15815.
The walk now drains an explicit worklist, the form isNodePartOfTree and isStorageUsedInTree use in src/Analyzer/Utils.cpp. The predicate is unchanged: a ConstantNode and the table, table function, query and union node types stop the descent without qualifying; a resolved FunctionNode that reports short-circuit suitability, or any resolved function under force_enable, qualifies; anything else falls through to its children. It answers an existential over the subtree, so visit order cannot change the result.
The test file is untouched and its 22 reference rows come back value for value.
`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]>
CI finish ledger - 5e15815Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Nothing here is PR-caused: this diff touches only Session id: cron:our-pr-ci-monitor:20260909-020033 |
|
Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
@groeneai merge fresh master into the branch |
…rt-circuit Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged master ( |
CI finish ledger - 1da431eEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261009-230008 |
…te-function-with-if-short-circuit
Backport #118697 to 26.8: Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation
Backport #118697 to 26.9: 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]>
Cherry pick #118697 to 26.3: Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation
…h_if defeating short-circuit evaluation
Backport #118697 to 26.3: Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation
…nction_with_if defeating short-circuit evaluation
Closes: #85784
Closes: #118625
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
optimize_rewrite_aggregate_function_with_if(enabled by default) turning a short-circuit-guarded aggregate such assum(if(number = 0, 0, intDiv(42, number)))into a query failure: the rewrittensumIf(intDiv(42, number), number != 0)evaluates its argument for every row, so the guarded expression ran on the rows the condition excluded and threw. The rewrite is now refused when the lifted branch relies on short-circuit evaluation. Closes #85784.Description
What breaks. At default settings this fails:
Not
sum-specific: with aNULLconstantavgandcountfail the same way, and bothifarms areaffected. Analyzer only (
enable_analyzer = 0returns 87).Root cause. The pass lifts the non-constant
ifbranch into an-Ifcombinator argument.-Ifhasno lazy argument evaluation, so that branch runs for every row, where
ifran it only on the rows itscondition selected. The pass decided from the
if's shape alone.Change. One guard, before both dispatch arms: refuse the rewrite when the lifted branch is one lazy
execution would have skipped. It mirrors the three terms of
findLazyExecutedNodes, keyed onshort_circuit_function_evaluation: no guard atdisable(nothing was protected there; the un-rewrittenquery throws too), decline at
enablewhen the lifted subtree holds a functionisSuitableForShortCircuitArgumentsExecutionaccepts, decline atforce_enablefor any non-constantfunction. This is the second direction listed in #85784, reusing an existing predicate instead of a
hand-written list of throwing functions. The first, lazy arguments for
-If, stays open.Cost. Branches lazy execution would have skipped stop being rewritten at default settings:
intDivandmoduloover a non-constant divisor,divideoverDecimal, casts, string functions.Bare columns, constants,
plus/minus/multiplyand anything behind a subquery or table expression(
IN) keep it. Atforce_enableany non-constant function declines. Acrosstests/one firing sitechanges its decision; no expected output changes.
Validation. New test
05137_rewrite_aggregate_function_with_if_short_circuitasserts bothdirections, green 50/50 under randomized settings.
tests/performance/rewrite_aggregate_if.xmlstill produces an identical query tree.Workflow [PR]
Sync PR [sync-upstream/pr/118697]
Version info
26.10.1.2024-master(included in26.10and later)26.9.28.162,26.8.37.166,26.3.64.4