Skip to content

Short-circuit evaluation for coalesce and ifNull - #121457

Merged
alexey-milovidov merged 45 commits into
masterfrom
coalesce-short-circuit
Nov 6, 2026
Merged

alexey-milovidov merged 45 commits into
masterfrom
coalesce-short-circuit

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

Related: #81999 #43839

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.

Both functions are now short-circuit functions, 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. If no row needs an argument, it is not evaluated at all.

-- No division-by-zero exception anymore:
SELECT coalesce(if(number = 0, toNullable(0), NULL), intDiv(42, number)) FROM numbers(10);

Implementation: coalesce and ifNull implement isShortCircuit with lazy execution disabled for the first argument, and execute the remaining arguments with maskedExecute under the mask of the rows where all the preceding arguments are NULL - the mask is derived from the isNotNull column that coalesce computes for the multiIf it delegates to anyway, so it costs nothing extra.

The setting short_circuit_function_evaluation controls 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 for if and multiIf today.

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):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Functions coalesce and ifNull now use short-circuit evaluation: an argument is evaluated only for the rows where all the preceding arguments are NULL.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1566-master (included in 26.11 and later)

`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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [634213f]

Summary: ✅


AI Review

Summary

The PR adds runtime short-circuit evaluation to coalesce and ifNull, including valid enum values in skipped rows. Reviewed head 634213f1ddf79a6c4a4362e78d03f46ddb2441e2, the current implementation, and all prior discussion. No actionable findings remain. All eight added regression files matched their reference output using the d350f35466c6 ARM release artifact; the affected implementations are unchanged at the reviewed head. Focused benchmarks in the discussion support the performance claim. Constant-folding errors and scalar subqueries remain outside the explicitly documented runtime scope.

Missing context / blind spots
  • ⚠️ The full CI run for the reviewed head is still in progress. Its Fast test passed; the remaining sanitizer, stress, and performance results should be checked before merging.
Final Verdict

Status: ✅ Approve. No new inline findings or thread updates are needed.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 21, 2026
Comment thread src/Functions/coalesce.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 20 not_sure 220 128 -41.8% <0.0001 cpu: ClickBench Q20 calls neither coalesce nor ifNull, the only functions this PR changes. The -41.8% gain and the CPU drop more likely come from a different base commit than from this diff.

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
  • StressHouse run: dfbc5964-7654-4423-a8c3-5565cbc0014c
  • MIRAI run: 6a646963-7ca6-49bc-9169-e6ffa8b47b0e
  • PR check IDs:
    • clickbench_85982_1791938853
    • clickbench_86050_1791938856
    • clickbench_86240_1791938925
    • tpch_adapted_1_official_86349_1791938941
    • tpch_adapted_1_official_86498_1791938956
    • tpch_adapted_1_official_86599_1791938959

@novikd novikd self-assigned this Sep 22, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 22, 2026
alexey-milovidov and others added 2 commits September 22, 2026 23:35
… 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]>
Comment thread src/Functions/coalesce.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 634213f1d with master 8908f932f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 117ffe67e; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

857 object files changed (+1.08 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion.cpp.o 24.64 MiB 24.66 MiB +25.29 KiB (+0.10%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/ifNull.cpp.o 203.25 KiB 225.16 KiB +21.91 KiB (+10.78%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/coalesce.cpp.o 248.97 KiB 267.79 KiB +18.82 KiB (+7.56%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1364 translation units recompiled, 8514 s compile time in total, 1363 of them have a recent master baseline.

Job report

Comment thread src/Functions/coalesce.cpp Resolved
alexey-milovidov and others added 2 commits October 5, 2026 04:54
…` 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 (05237_with_expression_alias_scope_descendant, failing in dozens of unrelated PRs over the last days) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The 05257_sql_security_view_sealed failure under parallel replicas is unrelated as well and is addressed by #123729; the Build (amd_fuzzers) failure is fixed on master, which is now merged into this branch.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

The fix is in progress: #123790 (open), which includes the change from my closed #123774. In its run on 2a290a03b66, 05237_with_expression_alias_scope_descendant passes in the arm_binary DBReplicated 1/2 job.

The failure on 2e5433f18 has the same diff as on the other PRs (view 10, stored alias is bare 0). The 67 passing reruns do not use the Replicated database (my open #112247 fixes that). The new head 90343fa7166 includes the revert #123789, so this job will not run on it until #123790 merges.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai for the update on #123790.

On 90343fa7166, the two remaining failures are unrelated to this PR, and each is already tracked:

@groeneai, please help get those fixes merged. I merged the latest master into this branch.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Status of both fixes:

alexey-milovidov and others added 2 commits October 6, 2026 19:21
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai for the status of #118499 and #120885.

The only red job on 2f7237bb3c5 was Stress test (amd_tsan). Its Hung check is unrelated to this PR: the stuck query is SELECT DISTINCT a, b, x, y FROM (SELECT a, b, 1 AS x, 2 AS y FROM distinct_in_order ORDER BY a ASC WITH FILL) ORDER BY a ASC, b ASC, which does not use coalesce or ifNull. It looks like the uninterruptible WITH FILL large-gap case from #107474, and Hung check fails in many other PRs and on master in recent days. @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121457&sha=2f7237bb3c5c0dc99c8d2581dd673adeca185751&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

I addressed the review about SEMI_ANTI_JOIN_COLUMN_ACCESS_DENIED in the coalesce folding (with a new test) and merged the latest master.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #120259 (mine). @ yariks5s approved it at an earlier head; the current head 885feab has green CI and no conflicts.

Root cause, from this run's query_log: two server-side fuzzed inserts, INSERT INTO test_3.distinct_in_order SELECT max2(number, number), number % 5, number % 10 FROM numbers(1048575, 1000000), cut to about 130k rows each by max_rows_to_read = 100000, read_overflow_mode = 'break', put unique a values from 1048575 up next to the test's 1M rows with a = 0. ORDER BY a WITH FILL then emits 2.3M rows with 1.18M distinct a, so nearly every row is its own range in DistinctSortedStreamTransform. buildFilterForRange constructs a HashMethodKeysFixed state per range (DistinctSortedStreamTransform.cpp:92), and that constructor packs the keys of the whole chunk (HashMethod.h:519-521). The transform is therefore quadratic in the chunk size with no cancellation check inside, which is why max_execution_time = 10 was ignored for 1677 s. It is not the WITH FILL generation from #107474: the fill subquery alone takes 0.22 s.

A/B on the amd_release artifacts, same table, the hung query with its Settings from query_log (read and result limits removed so both arms read all parts):

No master commit touched DistinctSortedStreamTransform.cpp, FillingTransform.cpp or HashMethod.h between the two bases. #120259 only addresses this stack, not the other Hung check failures. #111061 (@ rvasin, open) is complementary: it adds cancellation checks inside this transform.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121457&sha=48c7668bf9611ca3286538aa1ade9d8d2c8814a8&name_0=PR&name_1=Fast%20test (05453_webterminal_close_at_binary_format_question timed out in Fast test; the test was added in #127912 and is unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress (possibly #126995), link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

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 web terminal session of 05453 starts at 09:46:17.081;
  • 32 ms later, 05394_executable_pool_does_not_keep_closed_connection_open runs dictGet('executable_pool_simple', ...), which starts the executable_pool process /bin/sh (pid 166022) at 09:46:17.113;
  • the WebSocket closes at 09:46:18.105 (Closing server descriptors and waiting for client to finish), and the test's query stays in system.processes until the 60 s Fast test limit kills the test;
  • pid 166022 is reaped only at 09:48:54.751, when 02179_dict_reload_on_cluster runs SYSTEM RELOAD DICTIONARIES, and 20 ms later (09:48:54.771) the same handler thread logs Embedded client has finished.

The pool process inherits the pseudo-terminal master (opened without O_CLOEXEC), so closing it in the server does not hang up the slave until that process exits. #126995 opens both ends with O_CLOEXEC. This job has no ReadBuffer is canceled. Can't read from it. abort, so #128090 is not involved.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 (Cannot start clickhouse-server: Unknown expression or function identifier partition_strategy while attaching the fuzzer-created AzureBlobStorage table test_2.t_inline_right__fuzz_4 whose engine arguments end with partition_strategy = 'none'; unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress (it looks like #122707, still open), link it here. Thanks also for the analysis of the 05453_webterminal_close_at_binary_format_question timeout; it will be fixed when #126995 is merged.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the bug #122707 fixes. The restart fails on ATTACH of test_2.t_inline_right__fuzz_4, stored as AzureBlobStorage(<connection string>, 'clickhouse-tests', 'fuzz_azure_engine_716.orc', 'ORC', 'brotli', partition_strategy = 'none'): the server appends partition_strategy = 'none' to the stored engine arguments, and the Azure argument parser on master still accepts partition_strategy only as a positional argument, so loading fails with UNKNOWN_IDENTIFIER.

#122707 no longer conflicts with master, its CI is green at 542f5c1, and it is waiting for review.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (1df150b) and pushed f8babf3; the merge was clean and coalesce.cpp, ifNull.cpp, MaskOperations.cpp and IFunction.cpp compile. The only failure on f73f1c8, Stress test (amd_debug) (Cannot start clickhouse-server on the AzureBlobStorage partition_strategy = 'none' attach), is unrelated to this PR. #122707 fixes it and is still open. Thanks @groeneai for confirming.

Comment thread src/Functions/coalesce.cpp Resolved
alexey-milovidov and others added 3 commits November 3, 2026 06:32
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed d350f35. The merge was clean, and coalesce.cpp, ifNull.cpp, MaskOperations.cpp and Settings.cpp compile.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (f906f0f) and pushed 634213f. The merge was clean, and coalesce.cpp, ifNull.cpp, MaskOperations.cpp, IFunction.cpp and Settings.cpp compile.

The only failure on d350f35 was Performance Comparison (amd_release, master_head, 2/6). Its 5 slower queries are prefetch_in_aggregation #0-#3 (GROUP BY over String/FixedString keys) and jit_aggregate_functions #35 (groupBitAnd). None of them uses coalesce or ifNull, so this PR's code is not involved. The same prefetch_in_aggregation #2/#3 queries were also reported slower on the same shard for the unrelated PR #128177 (a PromQL change) on 2026-11-03. The new coalesce_short_circuit perf test shows the intended speedups: 4.7x-5.1x for n_10 and 1.65x for n_50, on both amd and arm.

@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 (prefetch_in_aggregation string-key queries slower on amd shard 2/6) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

This is not caused by this PR. Since #119976 (merged 2026-10-28), the iceberg_suite_*_synthio_* perf tests run SYSTEM ENABLE FAILPOINT, and libfiu kept its fast-path flag set after the fail point was disabled, so for the rest of the server's life every fiu_do_on takes libfiu's lock and a hash lookup (the adaptive aggregation merge does that once per new key). Shard 2/6 also runs iceberg_suite_local_synthio_write and iceberg_suite_s3_synthio_rw_features, before these tests, so both servers were in that slow state: prefetch_in_aggregation #0 took 1244 ms (old) and 1577 ms (new), while on master amd it took ~120 ms until 2026-10-27 and 1.1-2.0 s since 2026-10-28. The reported diffs are noise between two slowed-down servers.

The fix is already in progress: ClickHouse/libfiu#8 (merged) clears the flag when the last fail point is disabled, and #129334 updates contrib/libfiu to it (CI green, not merged yet). In its own perf run, where only the new server has the fix, prefetch_in_aggregation #0/#2/#3 took 70/94/509 ms against 1331/1364/6928 ms on the old one, and jit_aggregate_functions #35 took 99 ms against 190 ms. Until it is merged, shards that run a synthio test first can keep reporting these queries.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

All good.

@alexey-milovidov alexey-milovidov self-assigned this Nov 6, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 6, 2026
Merged via the queue into master with commit d3b4f86 Nov 6, 2026
187 checks passed
@alexey-milovidov
alexey-milovidov deleted the coalesce-short-circuit branch November 6, 2026 22:10
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
Marouane-elfadli added a commit to Marouane-elfadli/ClickHouse that referenced this pull request Nov 7, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants