Repository navigation
Use per-column indexes for coalesce(a, b) <op> const predicates - #103468
Merged
alexey-milovidov merged 8 commits intoApr 24, 2026
Merged
alexey-milovidov merged 8 commits into
alexey-milovidov merged 8 commits into
Conversation
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.
Contributor
|
Workflow [PR], commit [3de0ba6] Summary: ✅ AI ReviewSummaryThis PR adds a ClickHouse Rules
Final Verdict
|
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]>
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]>
Contributor
LLVM Coverage Report
Changed lines: 97.94% (95/97) · Uncovered code |
alexey-milovidov
approved these changes
Apr 24, 2026
alexey-milovidov
left a comment
Member
There was a problem hiding this comment.
Interesting, and looks reasonable.
Member
|
Hello! Can a performance test be added? |
This was referenced Jun 1, 2026
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #103194.
Rewrites
coalesce(a_1, ..., a_N) <op> constandifNull(...) <op> constpredicates atKeyConditiontime intoso per-column primary-key and skip indexes on each
y_ican prune granules through the existinguse_skip_indexes_for_disjunctionspath. The arguments are normalized mirroringFunctionCoalesce::getReturnTypeImpl(drop NULL literals, truncate at first non-Nullable), so the rewrite is always semantically equivalent to the originalcoalesce. Onlyequals,less,greater,lessOrEquals,greaterOrEqualsare 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Rewrite
coalesce(a, b, ...) <op> constandifNull(a, b) <op> constpredicates before index analysis so per-column primary key and skip indexes on each argument can prune granules. Controlled by the new settingallow_key_condition_coalesce_rewrite(on by default).Documentation entry for user-facing changes
Version info
26.5.1.62