Skip to content

Use primary key and skip indexes for boolean-position ifNull/coalesce predicates - #106272

Merged
nihalzp merged 26 commits into
ClickHouse:masterfrom
andyzzhao:keycondition-ifnull-boolean-pushdown
Jun 19, 2026
Merged

nihalzp merged 26 commits into
ClickHouse:masterfrom
andyzzhao:keycondition-ifnull-boolean-pushdown

Conversation

@andyzzhao

@andyzzhao andyzzhao commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Extends the allow_key_condition_coalesce_rewrite rewrite to the boolean-position null wrapper.

Problem

tryRewriteCoalesceComparison (added in #103468) lets primary-key and skip indexes prune for <cmp>(coalesce|ifNull(col, ...), const), where the coalesce/ifNull is an argument of the comparison. It does not handle the complementary shape where ifNull/coalesce wraps the comparison result:

WHERE ifNull(equals(k, 0), 0)        -- or coalesce(equals(k, 0), 0)

Query generators emit this to turn SQL three-valued logic into a two-valued boolean (k = 0 becomes ifNull(k = 0, 0) so a NULL operand yields a definite false). For such predicates KeyCondition builds no range on k (the atom becomes FUNCTION_UNKNOWN), so neither the primary key nor skip indexes prune granules, even though the predicate is applied correctly as a prewhere/row filter. The result is a full-part read where WHERE k = 0 would prune.

Repro on a key column (ORDER BY (team_id, k, s)):

WHERE team_id = 1 AND k = 0                     -> Condition: (k in [0,0]) AND (team_id in [1,1])   Granules: 5/24
WHERE team_id = 1 AND ifNull(equals(k, 0), 0)   -> Condition: (team_id in [1,1])                    Granules: 24/24
WHERE team_id = 1 AND coalesce(equals(k, 0), 0) -> Condition: (team_id in [1,1])                    Granules: 24/24

Fix

cloneDAGWithInversionPushDown (src/Storages/MergeTree/KeyCondition.cpp) gains tryRewriteCoalesceBoolean, next to the existing tryRewriteCoalesceComparison and behind the same allow_key_condition_coalesce_rewrite setting. It rewrites ifNull(X, 0) / coalesce(X, 0) to X for key analysis when the wrapper is used as a condition (only whether it is true matters, never its value): ifNull(X, 0) is truthy exactly when X is truthy, for any X, so there is no whitelist of inner functions (comparisons, the IN family, has, and the analyzer LIKE-affix startsWith/endsWith all benefit). Runtime filtering still uses the original predicate.

Guards:

  • need_inversion == false: under NOT the wrapper is not equivalent to X on NULL rows, so it falls through to FUNCTION_UNKNOWN.
  • boolean_context == true: a flag threaded through cloneDAGWithInversionPushDown, true at the filter root, propagated through and/or/not and transparent wrappers, false inside value arguments, so a value-position wrapper like equals(ifNull(equals(k, 0), 0), 0) is left alone. ActionsDAGWithInversionPushDown takes the initial flag per caller and defaults to false (conservative, no unwrap); the main MergeTree read path (ReadFromMergeTree::buildIndexes, which covers the primary key and all skip indexes) opts in with true, and value-expression canonicalization such as captured-lambda name reconstruction (RPNBuilder::appendLambdaColumnName) stays false.
  • The fallback must be a falsy constant (numeric zero); ifNull(X, 1) is left alone.

Scope: the two-argument form, which is what generators emit; multi-argument coalesce(pred, ..., 0) is left for a follow-up.

Changelog category (leave one):

  • Performance Improvement

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

The MergeTree primary key and skip indexes can now prune granules for filters where ifNull or coalesce wraps a condition, such as ifNull(key = 0, 0) or coalesce(key = 0, 0). Such predicates — often emitted by query generators to turn a possibly-NULL comparison into a definite boolean — were previously opaque to index analysis and could not skip granules. This extends the existing allow_key_condition_coalesce_rewrite setting (enabled by default). Closes #106264.

Documentation entry for user-facing changes

  • No new setting; extends the behavior of the existing allow_key_condition_coalesce_rewrite, whose generated description is updated accordingly.

Verification

New stateless test asserting with EXPLAIN indexes = 1 that the wrapped forms build the same key conditions as the bare predicates (none of which happens on master): the primary-key range for ifNull/coalesce around equals, the set forms for globalNullIn and has, the analyzer LIKE-affix form (s LIKE 'foo%' rewritten to startsWith), and granule pruning through bloom_filter, tokenbf_v1 and text skip indexes (which consume the same canonicalized predicate via ReadFromMergeTree::buildIndexes). It also asserts the guards: a truthy fallback is not rewritten; on an indexed nullable key, NOT ifNull(equals(k, 0), 0) builds no range and keeps the NULL row (the need_inversion guard); and the value-position wrapper equals(ifNull(equals(k, 0), 0), 0) is not unwrapped and keeps both k = 1 and k = NULL (the boolean_context guard).

Version info

  • Merged into: 26.6.1.1024

… predicates

KeyCondition could not see through an outer ifNull(<cmp>, 0) / coalesce(<cmp>, 0)
wrapper, so primary key and skip indexes did not prune for such predicates, even
though allow_key_condition_coalesce_rewrite already handles the inner
coalesce(col, ...) shape. Query generators emit the wrapper to turn SQL
three-valued logic into a two-valued boolean.

Add tryRewriteCoalesceBoolean, invoked next to tryRewriteCoalesceComparison and
gated on the same allow_key_condition_coalesce_rewrite setting. In non-inverted
boolean context it rewrites ifNull(X, 0) / coalesce(X, 0) to X for key analysis,
since a row passes a WHERE/PREWHERE only when the filter is truthy and
ifNull(X, 0) is truthy exactly when X is. Guarded to a falsey constant fallback
and a boolean-producing wrapped function; the inverted branch falls through to
FUNCTION_UNKNOWN.

Closes ClickHouse#106264

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@CLAassistant

CLAassistant commented Jun 2, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@andyzzhao
andyzzhao marked this pull request as ready for review June 2, 2026 03:36
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jun 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [622acc0]

Summary: ✅


AI Review

Summary

This PR extends allow_key_condition_coalesce_rewrite so ifNull/coalesce wrappers used directly as boolean filters can be canonicalized for index analysis, while preserving value-position expressions through the new boolean_context plumbing. The current revision addresses the prior inline findings I checked, including skip-index entry points, nullable/inverted guards, value-context guards, setting documentation, and the analyzer constant-expression path.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 2, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
…rewrite

Assert bloom_filter, tokenbf_v1 and text skip indexes prune granules through ifNull and coalesce wrappers via the shared canonicalized predicate, like the bare comparison, and that a truthy fallback does not prune.
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Add the null-aware global IN variants to the boolean-producing whitelist so ifNull/coalesce wrappers around them prune like the other IN atoms (KeyCondition already indexes globalNullIn/globalNotNullIn; the analyzer emits them for GLOBAL IN/NOT IN under transform_null_in). Rework the NOT-ifNull guardrail onto an indexed nullable key (granularity 1) so it actually exercises the need_inversion guard instead of relying on the row filter.
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
tryRewriteCoalesceBoolean fired whenever need_inversion was false, but cloneDAGWithInversionPushDown also visits value arguments of ordinary functions with need_inversion == false, where dropping the wrapper is not semantics-preserving: equals(ifNull(equals(k, 0), 0), 0) keeps k = NULL, but rewriting the child to equals(equals(k, 0), 0) lets KeyCondition prune the NULL granule on a functional key. Track a boolean_context flag separate from inversion, propagated only through and/or/not, aliases and transparent wrappers, and rewrite only when the wrapper itself is truth-tested. Add a value-context regression test.
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
andyzzhao added 2 commits June 2, 2026 20:17
allow_key_condition_coalesce_rewrite now also gates the boolean-position ifNull/coalesce wrapper rewrite, so note it in the setting description that generates the user-facing docs.
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
optimize_rewrite_like_perfect_affix (default on with the analyzer) rewrites s LIKE 'foo%' to startsWith(s, 'foo') before key analysis, so ifNull(like(...), 0) became ifNull(startsWith(...), 0) and was missed. Add startsWith and startsWithUTF8 (KeyCondition atoms) and endsWith (text-index builders) to isBooleanProducingFunction so the wrapped affix form prunes like the bare predicate. Add a LIKE-affix EXPLAIN regression test.
@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 4 query(s) improved out of 38 analysed

This PR is a narrowly scoped index-analysis optimization: it teaches MergeTree primary-key and skip-index pruning to unwrap coalesce/ifNull predicates (e.g. ifNull(a=5,0)) in filter position, gated by allow_key_condition_coalesce_rewrite. It only changes which granules are read for queries that use coalesce/ifNull in WHERE/PREWHERE; query results and the execution hot path are otherwise unchanged. The ClickBench and TPC-H queries here use no such predicates, so the flagged deltas cannot plausibly come from this change. Most flags were downgraded as run-to-run variance; a handful of large, consistent improvements (clickbench Q22/Q23, tpch Q7/Q20) are left standing on the strength of their size and consistency, but they sit off the PR's code path and more likely reflect baseline differences between the two builds than this change.

clickbench

🟢 2 improved · ⚠️ 6 inconclusive

Flagged queries (8 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 22 improvement 334 242 -27.5% <0.0001 Large, consistent improvement; the coalesce-pruning change doesn't touch Q22, so likely a baseline shift.
🟢 23 improvement 297 202 -32.0% <0.0001 -32% is a clear, consistent shift; PR path is coalesce/ifNull only, so likely build-baseline difference.
⚠️ 4 not_sure 264 234 -11.4% <0.0001 PR only adds coalesce/ifNull granule pruning; Q4 has no such predicate. Off-path, run-to-run variance.
⚠️ 10 not_sure 170 207 +21.8% <0.0001 Flagged regression off-path: PR scope is coalesce/ifNull index pruning, which Q10 does not exercise.
⚠️ 14 not_sure 385 345 -10.4% <0.0001 No coalesce/ifNull in Q14; the change cannot touch its execution path. Variance.
⚠️ 15 not_sure 246 197 -19.9% <0.0001 Q15 has no coalesce/ifNull predicate; PR's pruning path is untouched. Run-to-run variance.
⚠️ 18 not_sure 1403 1327 -5.4% 0.0002 Small -5% delta off PR path (no coalesce/ifNull); consistent with variance, not this change.
⚠️ 28 not_sure 7016 6642 -5.3% <0.0001 Small -5% delta off PR path (no coalesce/ifNull). Variance, not this change.

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

🟢 2 improved

Flagged queries (2 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 7 improvement 113 72 -36.3% <0.0001 Large delta but query is intrinsically noisy and off the PR path; likely a baseline difference.
🟢 20 improvement 248 129 -48.0% <0.0001 -48% on a noisy, high-variance query off the PR path; large but likely baseline, not this change.

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.

Debug info
  • StressHouse run: 5608c068-2b3c-450d-9fdd-d2fb5415100a
  • MIRAI run: 626298eb-45bc-4a95-a5b6-4d2b7469af7f
  • PR check IDs:
    • clickbench_33058_1781791449
    • clickbench_33071_1781791449
    • clickbench_33077_1781791449
    • tpch_adapted_1_official_33083_1781791448
    • tpch_adapted_1_official_33093_1781791449
    • tpch_adapted_1_official_33110_1781791448

@alexey-milovidov

Copy link
Copy Markdown
Member

The failures of 00175_obfuscator_schema_inference and 00096_obfuscator_save_load in Stateless tests (amd_tsan, parallel) are NOT caused by this PR.

They were introduced by #104690 ("Add UntrackedMemory asynchronous metric"), which made clickhouse-obfuscator abort (SIGABRT) on process teardown: the query results are correct, but the Aborted line on stderr fails the test. #104690 has now been reverted (#106365).

#104690 was merged in violation of the ClickHouse team rules: its own CI already showed these two tests failing (10 times between May 12 and June 1) before it was merged.

Please update your branch to pick up the revert; the tests should pass again.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
ActionsDAGWithInversionPushDown is also used to reconstruct captured-lambda column names (RPNBuilder::appendLambdaColumnName), where the input is a value expression rather than a truth-tested filter. Give the constructor an explicit boolean_context flag (default true for filter predicates) and pass false on the lambda-name path so the truthiness-only unwrap cannot alter reconstructed names. Drop isBooleanProducingFunction entirely: ifNull(X, 0) is truthy exactly when X is truthy for any X, so with boolean_context tracked the whitelist only narrowed coverage (it already missed has and the token/map predicates); the falsy-fallback and non-inverted boolean-position guards remain. Add a has regression test.
@andyzzhao

Copy link
Copy Markdown
Contributor Author

Hey @PedroTadim, are you able to review this? Thank you!

@PedroTadim

Copy link
Copy Markdown
Member

LGTM! @alexey-milovidov can we merge?

@nihalzp nihalzp self-assigned this Jun 9, 2026

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

Thanks for working on it. I have made some improvements to the test file. I will take a deeper look later.

Comment thread src/Storages/MergeTree/KeyCondition.h Resolved
@andyzzhao
andyzzhao requested a review from nihalzp June 9, 2026 16:45
@andyzzhao

Copy link
Copy Markdown
Contributor Author

@nihalzp I addressed your comment, let me know if there's anything else

@nihalzp

nihalzp commented Jun 15, 2026

Copy link
Copy Markdown
Member

Hi! Thanks for the patience. I have a look Tuesday or Wednesday.

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

The idea looks good to me! I have made improvements in the implementation and enabled the optimization in various other scenarios.

@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.40% 77.50% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 174/200 (87.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 7 line(s) · Uncovered code

Full report · Diff report

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.

ifNull(col = X, 0) cannot use PK or skip index (boolean-position ifNull/coalesce wrapper)

6 participants