Repository navigation
Use primary key and skip indexes for boolean-position ifNull/coalesce predicates - #106272
Conversation
… 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]>
|
Workflow [PR], commit [622acc0] Summary: ✅
AI ReviewSummaryThis PR extends Final VerdictStatus: ✅ Approve |
…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.
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.
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.
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.
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.
|
📊 Cloud Performance Report 🟢 AI verdict: 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 · Flagged queries (8 of 43)
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)
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
|
|
The failures of They were introduced by #104690 ("Add #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. |
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.
|
Hey @PedroTadim, are you able to review this? Thank you! |
|
LGTM! @alexey-milovidov can we merge? |
nihalzp
left a comment
There was a problem hiding this comment.
Thanks for working on it. I have made some improvements to the test file. I will take a deeper look later.
|
@nihalzp I addressed your comment, let me know if there's anything else |
|
Hi! Thanks for the patience. I have a look Tuesday or Wednesday. |
nihalzp
left a comment
There was a problem hiding this comment.
The idea looks good to me! I have made improvements in the implementation and enabled the optimization in various other scenarios.
LLVM Coverage Report
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 |
88e2e1d
Extends the
allow_key_condition_coalesce_rewriterewrite 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 thecoalesce/ifNullis an argument of the comparison. It does not handle the complementary shape whereifNull/coalescewraps the comparison result:Query generators emit this to turn SQL three-valued logic into a two-valued boolean (
k = 0becomesifNull(k = 0, 0)so a NULL operand yields a definitefalse). For such predicatesKeyConditionbuilds no range onk(the atom becomesFUNCTION_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 whereWHERE k = 0would prune.Repro on a key column (
ORDER BY (team_id, k, s)):Fix
cloneDAGWithInversionPushDown(src/Storages/MergeTree/KeyCondition.cpp) gainstryRewriteCoalesceBoolean, next to the existingtryRewriteCoalesceComparisonand behind the sameallow_key_condition_coalesce_rewritesetting. It rewritesifNull(X, 0)/coalesce(X, 0)toXfor 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 whenXis truthy, for anyX, so there is no whitelist of inner functions (comparisons, theINfamily,has, and the analyzerLIKE-affixstartsWith/endsWithall benefit). Runtime filtering still uses the original predicate.Guards:
need_inversion == false: underNOTthe wrapper is not equivalent toXon NULL rows, so it falls through toFUNCTION_UNKNOWN.boolean_context == true: a flag threaded throughcloneDAGWithInversionPushDown, true at the filter root, propagated throughand/or/notand transparent wrappers, false inside value arguments, so a value-position wrapper likeequals(ifNull(equals(k, 0), 0), 0)is left alone.ActionsDAGWithInversionPushDowntakes 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.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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The
MergeTreeprimary key and skip indexes can now prune granules for filters whereifNullorcoalescewraps a condition, such asifNull(key = 0, 0)orcoalesce(key = 0, 0). Such predicates — often emitted by query generators to turn a possibly-NULLcomparison into a definite boolean — were previously opaque to index analysis and could not skip granules. This extends the existingallow_key_condition_coalesce_rewritesetting (enabled by default). Closes #106264.Documentation entry for user-facing changes
allow_key_condition_coalesce_rewrite, whose generated description is updated accordingly.Verification
New stateless test asserting with
EXPLAIN indexes = 1that the wrapped forms build the same key conditions as the bare predicates (none of which happens on master): the primary-key range forifNull/coalescearoundequals, the set forms forglobalNullInandhas, the analyzerLIKE-affix form (s LIKE 'foo%'rewritten tostartsWith), and granule pruning throughbloom_filter,tokenbf_v1andtextskip indexes (which consume the same canonicalized predicate viaReadFromMergeTree::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 (theneed_inversionguard); and the value-position wrapperequals(ifNull(equals(k, 0), 0), 0)is not unwrapped and keeps bothk = 1andk = NULL(theboolean_contextguard).Version info
26.6.1.1024