Skip to content

Use per-column indexes for coalesce(a, b) <op> const predicates - #103468

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
raimannma:coalesce-two-arg-index-pruning
Apr 24, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
raimannma:coalesce-two-arg-index-pruning

Conversation

@raimannma

@raimannma raimannma commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

Closes #103194.

Rewrites coalesce(a_1, ..., a_N) <op> const and ifNull(...) <op> const predicates at KeyCondition time into

(y_1 <op> const)
OR (isNull(y_1) AND y_2 <op> const)
OR ...
OR (isNull(y_1) AND ... AND isNull(y_{M-1}) AND y_M <op> const)
[OR (isNull(y_1) AND ... AND isNull(y_M) AND (c <op> const))]

so per-column primary-key and skip indexes on each y_i can prune granules through the existing use_skip_indexes_for_disjunctions path. The arguments are normalized mirroring FunctionCoalesce::getReturnTypeImpl (drop NULL literals, truncate at first non-Nullable), so the rewrite is always semantically equivalent to the original coalesce. Only equals, less, greater, lessOrEquals, greaterOrEquals are rewritten (and their operand-swapped mirrors); other ops (notEquals, IS NULL, …) fall through unchanged.

Gated behind allow_key_condition_coalesce_rewrite (on by default). The rewrite is strictly additive for index pruning; runtime filtering still uses the original predicate.

Changelog category (leave one):

  • Performance Improvement

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

Rewrite coalesce(a, b, ...) <op> const and ifNull(a, b) <op> const predicates before index analysis so per-column primary key and skip indexes on each argument can prune granules. Controlled by the new setting allow_key_condition_coalesce_rewrite (on by default).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.62

raimannma and others added 4 commits April 23, 2026 21:04
Rewrite `<op>(coalesce(a, b), const)` and `<op>(ifNull(a, b), const)` (and the
flipped-argument forms) into `(a <op> const) OR (isNull(a) AND b <op> const)`
inside `cloneDAGWithInversionPushDown`, before index analysis. The existing
`use_skip_indexes_for_disjunctions` machinery in
`MergeTreeDataSelectExecutor::mergePartialResultsForDisjunctions` then combines
per-column pruning across the OR. PK analysis also benefits when one input is a
primary key column.

The rewrite only triggers when both `coalesce`/`ifNull` arguments are
non-constant - the single-constant case is already handled by the monotonic
chain introduced in ClickHouse#94754. Scope is limited to `equals`, `less`, `greater`,
`lessOrEquals`, `greaterOrEquals`; negated and IN forms fall through unchanged.

Gated behind the new setting `allow_key_condition_coalesce_rewrite` (default
`true`).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Follow-up to 57be91e: `tryRewriteCoalesceComparison` in `KeyCondition.cpp`
was hard-gated to 2-argument `coalesce`/`ifNull`. Extend it to arbitrary N by
rewriting `<op>(coalesce(a_1, ..., a_N), const)` into

    (a_1 <op> const)
    OR (isNull(a_1) AND a_2 <op> const)
    OR (isNull(a_1) AND isNull(a_2) AND a_3 <op> const)
    ...
    OR (isNull(a_1) AND ... AND isNull(a_{N-1}) AND a_N <op> const)

so per-column PK and skip indexes on each `a_i` are consulted via the existing
`use_skip_indexes_for_disjunctions` machinery in
`MergeTreeDataSelectExecutor::mergePartialResultsForDisjunctions`. The final
branch needs no trailing `isNull(a_N)` - if execution reaches it, `a_N` is the
`coalesce` result regardless of nullability.

N=2 produces the same DAG shape as before, so `04114_coalesce_two_column_index_pruning`
still passes byte-for-byte. Added `04115_coalesce_n_column_index_pruning`
covering N=3, N=4, flipped-argument form, partial-column-indexed pruning,
each of the 5 ordered operators, and the `allow_key_condition_coalesce_rewrite=0`
off-baseline.

The bail-out on any constant argument is kept intentionally: the 2-arg single-
constant case is still handled by the monotonic-chain path from ClickHouse#94754, and
a constant in the middle of the list would truncate `coalesce` (short-circuit
on the first non-NULL), which needs separate handling.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Follow-up to b523b14: `tryRewriteCoalesceComparison` in `KeyCondition.cpp`
bailed out whenever any argument of `coalesce`/`ifNull` was a constant, which
left common shapes like `coalesce(a, 42, b) <op> const` unpruned - the monotonic
chain path (`isKeyPossiblyWrappedByMonotonicFunctionsImpl`) rejects anything
with more than two arguments, so nothing handled them.

Replace the any-constant bailout with the same normalization `FunctionCoalesce::getReturnTypeImpl`
performs: drop `NULL`-literal args and truncate at the first non-Nullable arg
(everything after it is unreachable by short-circuit). Then emit:

    (y_1 <op> const)
    OR (isNull(y_1) AND y_2 <op> const)
    ...
    OR (isNull(y_1) AND ... AND isNull(y_{M-1}) AND y_M <op> const)
    [OR (isNull(y_1) AND ... AND isNull(y_M) AND (c <op> const))]

The final `c <op> const` branch is only emitted when the terminator is a non-null
constant; `KeyCondition` folds it downstream. This covers `coalesce(a, 42, b)`
(normalizes to `coalesce(a, 42)`), `coalesce(a, NULL, b)` (normalizes to
`coalesce(a, b)`), `coalesce(a, b, 42)`, and `coalesce(a, b, 42, d)` (d dropped).

Degenerate normalized shapes are now handled directly: `M=0, has_c` emits
`c <op> const`; `M=1, !has_c` emits `y_1 <op> const`; `M=1, has_c` emits the
two-branch form. The `M=1, has_c` shape subsumes `coalesce(a, 42) <op> const`,
which used to fall through to the monotonic-chain path - the new rewrite is
strictly more powerful there (exposes `isNull(a)` and enables skip-index pruning
on non-PK `a`).

`04114` reference update: the `tab_pk` case now produces `(a in [42, 42])`
instead of `or((a isNull), (a in [42, 42]))` because `a` is non-Nullable and
normalization truncates at it, so no `isNull` branch is ever built. Granule
count (17/1024) is unchanged. The `tab_monotone` case now has a non-deterministic
`Condition:` string (the folded-FALSE `isNull(a) AND (0 = 42)` branch appears
or disappears depending on random settings); the test now asserts only the
`PrimaryKey` / `Granules: 3/1024` lines, which is the load-bearing signal.

Added `04116_coalesce_partial_constant_index_pruning` covering middle constant,
trailing constant with both TRUE and FALSE tail, `NULL`-literal in middle,
`N=4` truncation (unreachable `d` index is correctly not consulted), flipped
operand, all five ordered operators, `ifNull(a, 42)`, off-baseline with
`allow_key_condition_coalesce_rewrite=0`, and negative regressions
(`!=`, `IS NULL`).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Post-review cleanup of `tryRewriteCoalesceComparison`:
- return `const ActionsDAG::Node *` (nullptr = no match) instead of bool + out-param
- replace `std::map<String, String>` mirror op lookup with a `std::string_view` helper
- flatten the is-const dispatch with two upfront bool checks
- append trailing const as a synthetic last arg to unify the subsequent-branch
  and trailing-branch loops into one
- precompute only the `isNull(y_i)` nodes actually consumed (one fewer DAG node)
- trim WHAT-narration comments and verbose test header blocks

No behaviour change; the emitted DAG is identical for all inputs.
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3de0ba6]

Summary: ✅


AI Review

Summary

This PR adds a KeyCondition rewrite for coalesce/ifNull comparisons against constants, enabling better primary-key and skip-index pruning (including N-argument and partial-constant forms) behind allow_key_condition_coalesce_rewrite. The implementation and tests are consistent with the stated scope, and I did not find correctness, safety, or compatibility issues that require changes.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ✅
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ✅
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Apr 24, 2026
Comment thread src/Core/Settings.cpp Resolved
raimannma and others added 3 commits April 24, 2026 13:34
Reflect that the rewrite now covers N-argument `coalesce`/`ifNull` and
partial-constant forms (e.g. `coalesce(a, 42, b)`), not just the 2-arg
shape.

Also add the setting to the experimental-settings style-check ignore
list — it is a stable optimization enabled by default, not experimental.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
`readability-avoid-const-params-in-decls` flagged `const bool need_inversion`
in the forward declaration of `cloneDAGWithInversionPushDown`, since
const-qualification of by-value parameters only has an effect in definitions.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
After the `coalesce`/`ifNull` index-pruning rewrite, the `Condition` in
`EXPLAIN indexes` now prints as `or((ts isNull), (ts in ...))` instead of the
old `coalesce(ts, '0') in ...` / `ifNull(ts, '0') in ...`. Sync the reference
file to the new output.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
The `allow_key_condition_coalesce_rewrite` entry in `SettingsChangesHistory`
still described the rewrite as applying only to two-argument
`coalesce(a, b)` / `ifNull(a, b)` forms, but the rewrite now covers
N-argument and partial-constant forms as well. Update the reason string
to match the description in `Settings.cpp`.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.70% -0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.30% 76.20% -0.10%

Changed lines: 97.94% (95/97) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

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.

Interesting, and looks reasonable.

@alexey-milovidov alexey-milovidov self-assigned this Apr 24, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Apr 24, 2026
Merged via the queue into ClickHouse:master with commit 23a6adf Apr 24, 2026
165 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 24, 2026
@raimannma
raimannma deleted the coalesce-two-arg-index-pruning branch April 24, 2026 17:39
@PedroTadim

Copy link
Copy Markdown
Member

Hello! Can a performance test be added?

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 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.

coalesce(colA, colB) = X cannot use PK or skip index on either input column

4 participants