Skip to content

Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation - #118697

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-rewrite-aggregate-function-with-if-short-circuit
Oct 10, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-rewrite-aggregate-function-with-if-short-circuit

Conversation

@groeneai

@groeneai groeneai commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #85784
Closes: #118625

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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 as sum(if(number = 0, 0, intDiv(42, number))) into a query failure: the rewritten sumIf(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:

SELECT sum(if(number = 0, 0, intDiv(42, number))) FROM numbers(5);
-- Code: 153. DB::Exception: Division by zero. (ILLEGAL_DIVISION)
-- 87 with optimize_rewrite_aggregate_function_with_if = 0

Not sum-specific: with a NULL constant avg and count fail the same way, and both if arms are
affected. Analyzer only (enable_analyzer = 0 returns 87).

Root cause. The pass lifts the non-constant if branch into an -If combinator argument. -If has
no lazy argument evaluation, so that branch runs for every row, where if ran it only on the rows its
condition 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 on
short_circuit_function_evaluation: no guard at disable (nothing was protected there; the un-rewritten
query throws too), decline at enable when the lifted subtree holds a function
isSuitableForShortCircuitArgumentsExecution accepts, decline at force_enable for any non-constant
function. 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:
intDiv and modulo over a non-constant divisor, divide over Decimal, casts, string functions.
Bare columns, constants, plus/minus/multiply and anything behind a subquery or table expression
(IN) keep it. At force_enable any non-constant function declines. Across tests/ one firing site
changes its decision; no expected output changes.

Validation. New test 05137_rewrite_aggregate_function_with_if_short_circuit asserts both
directions, green 50/50 under randomized settings.
tests/performance/rewrite_aggregate_if.xml still produces an identical query tree.


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

Version info

  • Merged into: 26.10.1.2024-master (included in 26.10 and later)
  • Backported to: 26.9.28.162, 26.8.37.166, 26.3.64.4

…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Four rounds before publication, each a cold read of the diff plus an independent model
(engine: codex). Fifteen findings accepted and two dismissed with recorded evidence, consolidated into
the rows below. Mutation arms are cited where the fix was a test-liveness fix, since an assertion that
cannot fail is not coverage.

# Sev Finding Verdict Evidence / action
1 ❌ The guard rejected valid queries: it described the lifted branch by calling getResultType() on every function argument, but the IN family carries a table expression or subquery in its second slot, which has no result type. sum(if(number = 0, 0, number IN (SELECT 1))) failed at default settings. AGREE It now goes through FunctionNode::getArgumentColumns(), as the resolver does, and the walk stops at a subquery or table expression. Reproduced on the pre-fix commit first, then measured across 18 shapes against a pristine binary.
2 ⚠️ The walk descended into subqueries, declining sound rewrites. AGREE Same node-type rule. Pinned by an EXPLAIN QUERY TREE assertion over an IN subquery holding intDiv.
3 ⚠️ The tests could not tell the general rule from an intDiv special case: every protected expression at enable used intDiv, and the force_enable witness bypasses the suitability predicate, so replacing that predicate with getFunctionName() == "intDiv" passed the whole file. AGREE Added a conversion witness, count(if(s = 'bad', NULL, toDate(s))). That mutant now reddens it, and moves no other assertion.
4 ⚠️ Two missing positive controls: both %sumIf% fire-assertions were the constant-first arm, and both force_enable assertions were negative, so a mutant that declined every rewrite in the other arm, or at force_enable, passed the file. AGREE One positive control added for each, with a confirming mutant for each.
5 💡 A comment claimed a nested if can never re-protect its subtree. It can, when the inner condition matches the outer. AGREE Claim removed.
6 💡 I asked for an assertion that fails when only the UNION arm of the node-type rule is deleted. AGREE, my error Not achievable, and measured rather than argued: deleting that arm alone moves no assertion, deleting the QUERY arm alone moves only the plain-subquery one, and deleting both moves the union one. A union's expressions are reachable only through its inner query nodes, so that arm is redundant defence like the table arms. The assertion stays for what it does pin: a union-shaped IN right-hand side keeps the rewrite.
7 💡 The Cost paragraph named intDiv and modulo without qualification. AGREE They report short-circuit suitability only over a non-constant divisor, so the description and the commit message now say so.
8 ⚠️ The nested-if assertion is vacuous whenever randomized optimize_if_chain_to_multiif is on: IfChainToMultiIfPass runs immediately before this pass and flattens that shape to multiIf, which this pass does not match, and the expected value is the same either way, so the assertion goes dead rather than failing. AGREE optimize_if_chain_to_multiif = 0 pinned in the test. Proved load-bearing in both directions: a mutant that stops the walk at a nested if reddens that assertion with the pin and does not redden it with the setting forced back to 1.
9 ⚠️ The guard also runs for shapes that are never rewritten, such as max(if(c, 5, x)), and should be narrowed to the qualified arms. DISAGREE Behaviour there is identical, since the only effect is declining a rewrite that never happens, and no throw is reachable: getFunction() returns {} for every non-ordinary kind and for an unresolved function, and getArgumentColumns() is the construction the resolver itself used. Narrowing would duplicate the guard into both arms for no gain.
10 ⚠️ The walk crosses scope boundaries that findLazyExecutedNodes does not (lambda bodies, arrayJoin arguments, indexHint arguments), so it declines rewrites that were valid. DISAGREE The mechanism holds, but nothing protected is lost. FunctionArrayMapped reports short-circuit suitability true, so arrayMap and its siblings already decline at the outer node and a lambda carve-out would change nothing for them. Where the outer node reports false instead (the mapExists family, arrayJoin, indexHint), findLazyExecutedNodes finds no lazy candidate either, so the un-rewritten query evaluates the inner expression exactly as often: the difference is a lost optimization, never a behaviour change. IFunction.h blesses that direction for this predicate, calling the converse unsafe, and each carve-out would add a place for a genuinely protected expression to slip through. Noted, not blocking, and worth revisiting if a real query shows the cost.

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

Session id: cron:clickhouse-review-slot-9:20260908-015800

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [93bdbe6]

Summary: ✅


AI Review

Summary

This PR teaches RewriteAggregateFunctionWithIfPass to skip the f(if(...)) -> fIf(...) rewrite when it would defeat short-circuit branch evaluation, and adds a focused stateless regression test covering enable, force_enable, and disable. After checking the current diff, the prior review discussion, and the runtime short-circuit execution path, I did not find remaining correctness, test, or PR-metadata issues.

Final Verdict
  • Status: ✅ Approve

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @KochetovNicolai, could you review this? The pass lifts the non-constant if branch into an -If argument, which has no lazy argument evaluation, so sum(if(number = 0, 0, intDiv(42, number))) threw at default settings; it now declines the rewrite when the lifted branch holds a function that isSuitableForShortCircuitArgumentsExecution accepts, which is the second of the two directions listed in #85784.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 93bdbe6c2145b324ea0ffd30bb08410d3658da8a was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

See the job log for details.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e2c3bc9

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential) / 04648_distributed_plan_task_error_propagation flaky, public master regression: the recorded CANNOT_SCHEDULE_TASK is lost, so the client sees POCO_EXCEPTION 1000 where server error 439 is expected #118417 (external, open); #118390 (mine, open) is the in-flight sibling for this row
Stateless tests (arm_asan_ubsan, azure, sequential) / 04340_distributed_plan_status_reenqueue_fault flaky, same root cause: the injected recordFailure line never appears, so the test reads reenqueue fault handled: 0 #118417 (external, open)
PR aggregator reflecting the two rows above same owner, #118417

Neither test is touched by this PR, whose diff is src/Analyzer/Passes/RewriteAggregateFunctionWithIfPass.cpp plus one new stateless test. Both failures survived the runner's 3-rerun reproducibility check (0 of 3 reproduced) and span 52 and 44 distinct pull requests with 14 and 9 true-master runs over 30 days, so neither is caused by this branch. Tracking issue: #118626.

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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai, reimplement it in a non-recursive way

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@novikd novikd self-assigned this Sep 8, 2026
`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]>
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5e15815

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential, selected tests) / 04648_distributed_plan_task_error_propagation flaky, public master regression (return code: 232, expected server error 439; praktika's own reruns: 1/36 failed). 113 failures across 76 distinct PRs and 19 master runs in 30d #118417 (external, open); sibling #118390 (mine, open)
Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential, selected tests) / 04340_distributed_plan_status_reenqueue_fault flaky, same root cause (reenqueue fault handled: 0, the injected recordFailure line absent; all reruns passed). 95 failures across 65 distinct PRs and 10 master runs in 30d #118417 (external, open)
Finish Workflow / Post Hooks consequence of the two rows above, not an independent defect: both Bugfix validation (functional tests, amd64) and (functional tests, aarch64) were DROPPED (Dropped due to previous failure [Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential, selected tests)]), so new_tests_check.py had no per-arch verdict to read #118417 (external, open)
Mergeable Check, PR workflow-level aggregators rolling up the rows above; no failure of their own #118417 (external, open)
Sync - CH Inc sync (private, not actionable by me)

Nothing here is PR-caused: this diff touches only src/Analyzer/Passes/RewriteAggregateFunctionWithIfPass.cpp and tests/queries/0_stateless/05137_rewrite_aggregate_function_with_if_short_circuit.{sql,reference}, and neither failing test exercises that pass.

Session id: cron:our-pr-ci-monitor:20260909-020033

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

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.

@novikd novikd self-assigned this Oct 9, 2026
@novikd

novikd commented Oct 9, 2026

Copy link
Copy Markdown
Member

@groeneai merge fresh master into the branch

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master (d3d0c92) in 1da431e. The merge was clean and the PR diff is unchanged; 05137 and the other tests for this pass are green locally on the merged build.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1da431e

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) / 05239_written_rows_quota_interval_rollover flaky, not from this PR: the rollover checkpoint line 1 1 is missing because the asynchronous inserts miss their quota intervals. 6/6 reruns pass; 13 PRs show it since 2026-10-09 #124935 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05316_secret_arguments_declared_by_engines not from this PR: under DatabaseReplicated the test's last query_log check counts the CREATE DICTIONARY row twice (0 2 instead of 0 1; the password stays hidden). 180 PRs show it since 2026-10-02 #124928 (external, merged 17:58Z). This run was dispatched at 16:14Z, before that merge, so I will merge master here to pick it up
Mergeable Check, PR praktika rollups of the two stateless rows above (Failed: 2) #124935 (mine, open), #124928 (external, merged)

Session id: cron:our-pr-ci-monitor:20261009-230008

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
Merged via the queue into ClickHouse:master with commit fe63a33 Oct 10, 2026
163 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
@novikd novikd added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 13, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 13, 2026
Backport #118697 to 26.8: Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation
clickhouse-gh Bot added a commit that referenced this pull request Nov 13, 2026
Backport #118697 to 26.9: Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation
alexey-milovidov pushed a commit that referenced this pull request Nov 15, 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]>
robot-clickhouse-ci-2 added a commit that referenced this pull request Nov 15, 2026
Cherry pick #118697 to 26.3: Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation
robot-clickhouse added a commit that referenced this pull request Nov 15, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 15, 2026
alexey-milovidov added a commit that referenced this pull request Nov 15, 2026
Backport #118697 to 26.3: Fix optimize_rewrite_aggregate_function_with_if defeating short-circuit evaluation
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Nov 23, 2026
…nction_with_if defeating short-circuit evaluation
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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

6 participants