Repository navigation
Short-circuit evaluation for coalesce and ifNull - #121457
Conversation
`coalesce` returns the leftmost non-`NULL` argument, but it used to evaluate every argument for every row. The same applies to `ifNull`, which is its two-argument form. Make both functions short-circuit, the same way as `if` and `multiIf`: an argument is lazily executed and evaluated only for the rows where all the preceding arguments are `NULL`. When no row needs an argument, it is not evaluated at all. Closes: #81999 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [634213f] Summary: ✅
AI ReviewSummaryThe PR adds runtime short-circuit evaluation to Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings or thread updates are needed. |
|
📊 Cloud Performance Report ✅ AI verdict: One query was flagged: ClickBench Q20 is -41.8% faster (220 ms to 128 ms), and CPU time drops by a similar amount. The PR adds short-circuit (lazy) evaluation only to coalesce and ifNull, and Q20 calls neither, so I downgraded the result to not sure. The PR build and the master baseline are different builds, so the gain more likely comes from other code differences between them than from this change. The PR adds its own coalesce_short_circuit performance test, which is the right place to measure its effect. No queries were suppressed by the master variance band, so there was nothing to sanity-check there. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
… the analyzer Constant folding during analysis still evaluated every argument of `coalesce` and `ifNull`, so `SELECT coalesce(toNullable(1), intDiv(1, 0))` threw `ILLEGAL_DIVISION`, unlike the analogous `if` and `multiIf`. Add the same special case as for `if` and `multiIf` in `resolveFunction`: when an argument is statically known to be never `NULL` (a non-`NULL` constant or an expression of a type that cannot contain `NULL`) and all the preceding arguments are constant `NULL`, the next arguments are unreachable; if resolving any of them throws, the node is replaced by the live argument. Otherwise the generic path runs, keeping the common-supertype result type. #121457 (comment) Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes857 object files changed (+1.08 MiB total), 0 added.
719 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 units1364 translation units recompiled, 8514 s compile time in total, 1363 of them have a recent master baseline. |
…ction_evaluation` docs Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…` arguments The number of arguments passed to `isShortCircuit` does not tell which arguments are live: leading constant `NULL` arguments are removed only in `executeImpl`. For `coalesce(NULL, a, b)` the argument `a` is fully executed, so a node shared by `a` and `b` would be evaluated once for all rows and once more under the mask of `b`. Evaluate such common descendants once for all rows, as `if` and `ifNull` do. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121457&sha=2e5433f183cec0fd78988e2d2c89ffef90c94ac1&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%201%2F2%29 ( The |
|
The fix is in progress: #123790 (open), which includes the change from my closed #123774. In its run on The failure on |
|
Status of both fixes:
|
…when folding `coalesce` Mirror the carve-out of the `if` and `multiIf` dead-branch folding: an access violation for a column of the non-preserved side of a SEMI/ANTI JOIN in a statically unreachable `coalesce` or `ifNull` argument must be reported instead of being folded away. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Thanks @groeneai for the status of #118499 and #120885. The only red job on I addressed the review about |
|
The fix is already in progress: #120259 (mine). @ yariks5s approved it at an earlier head; the current head Root cause, from this run's A/B on the
No master commit touched |
…er folding of `coalesce` Address review: the analyzer-time folding of unreachable constant arguments of `coalesce` and `ifNull` suppressed exceptions even when short-circuit evaluation is disabled, so constant and non-constant dead arguments behaved differently. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121457&sha=48c7668bf9611ca3286538aa1ade9d8d2c8814a8&name_0=PR&name_1=Fast%20test ( |
|
The fix is already in progress: #126995 (mine, open, CI green on its current head, waiting for a review). This Fast test run has the same cause as the one I described in #125952 (comment). The server log of this job (server time):
The pool process inherits the pseudo-terminal master (opened without |
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121457&sha=f73f1c8145f3a74d5876f1599828ed339cddee32&name_0=PR&name_1=Stress%20test%20%28amd_debug%29 ( |
|
This is the bug #122707 fixes. The restart fails on #122707 no longer conflicts with master, its CI is green at 542f5c1, and it is waiting for review. |
|
🕵 Merged |
…common-descendant planning An argument of type `Nullable(Nothing)` is never executed by `coalesce`, but it can still have descendants in the actions DAG, e.g. `if(intDiv(100, number) > 0, NULL, NULL)`. Skipping such arguments when counting could leave only two counted arguments, which disabled lazy execution of common descendants, so a node shared with a lazy argument was evaluated eagerly for all rows (`ILLEGAL_DIVISION` in the example from the review). Count all arguments instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Iceberg configuration of the performance comparison widens `UInt64` columns to `Int64`, so `coalesce(n, length(...))` gets arguments of `Int64` and `UInt64`, whose common type is a `Variant`, and `sum` throws `Illegal type Variant(Int64, UInt64) of argument for aggregate function sum`. The test measures a function, not the storage, so opt it out with `<test iceberg="0">` rather than the skip list (changing the skip list would run the whole Iceberg configuration in this pull request). https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121457&sha=eb67ff04118314089aeaf6a6ddc87a54bdc8eb98&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%20iceberg_s3%2C%201%2F3%29 #121457 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
|
|
🕵 Merged The only failure on d350f35 was @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121457&sha=d350f35466c6272c0053ddead2c367fe8cdf319f&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%202%2F6%29 ( |
|
This is not caused by this PR. Since #119976 (merged 2026-10-28), the The fix is already in progress: ClickHouse/libfiu#8 (merged) clears the flag when the last fail point is disabled, and #129334 updates |
multiIf stops evaluating its arguments once an earlier condition has taken every row, and replaces the skipped lazy arguments with a column of default values through executeColumnIfNeeded(column, /*empty=*/ true). multiIf still converts those columns to the result type afterwards. For a type whose default value is not valid, such as an Enum without the value 0 (also inside Nullable, Tuple or a typed JSON path), the conversion throws UNKNOWN_ELEMENT_OF_ENUM, even though the skipped rows are never read. maskedExecute already avoids this: in its no-ones branch it fills the default column with valid values (hasInvalidColumnDefault + fillUnusedRowsWithValidValues, added in ClickHouse#121457). executeColumnIfNeeded builds the same kind of column without that step, so the earlier fix covered only one of the two places. Move the construction into a static helper, createUnusedColumnWithValidValues(type, size), and call it from both maskedExecute and executeColumnIfNeeded. The helper creates the default column and, only when hasInvalidColumnDefault(type) is true, fills it using an all-zero mask of the same size (fillUnusedEnumRows throws LOGICAL_ERROR if the sizes differ). maskedExecute behaves as before, because its mask was already all zeros. Types with a valid default return early and cost nothing extra. One shared helper keeps the two paths from drifting apart again. Part of ClickHouse#129926
Related: #81999 #43839
coalescereturns the leftmost non-NULLargument, but it used to evaluate every argument for every row. The same applies toifNull, which is its two-argument form.Both functions are now short-circuit functions, the same way as
ifandmultiIf: an argument is lazily executed and evaluated only for the rows where all the preceding arguments areNULL. If no row needs an argument, it is not evaluated at all.Implementation:
coalesceandifNullimplementisShortCircuitwith lazy execution disabled for the first argument, and execute the remaining arguments withmaskedExecuteunder the mask of the rows where all the preceding arguments areNULL- the mask is derived from theisNotNullcolumn thatcoalescecomputes for themultiIfit delegates to anyway, so it costs nothing extra.The setting
short_circuit_function_evaluationcontrols this, as for the other short-circuit functions.Note about the example in the issue: a scalar subquery such as
(SELECT count() FROM t)is evaluated during query analysis, not during expression execution, so that particular query is not affected - as is also the case forifandmultiIftoday.Similarly, constant folding during analysis still evaluates every argument: an all-constant unreachable argument that throws, such as
SELECT coalesce(toNullable(1), intDiv(1, 0)), still raises the exception during analysis. Errors are not suppressed there by design.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Functions
coalesceandifNullnow use short-circuit evaluation: an argument is evaluated only for the rows where all the preceding arguments areNULL.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/121457]
Version info
26.11.1.1566-master(included in26.11and later)