Repository navigation
Optimizer: Add index pruning for nullIf(key, sentinel) predicates (#107209) - #107308
KochetovNicolai merged 18 commits into
Conversation
|
Workflow [PR], commit [16884fb] Summary: ✅
AI ReviewSummaryThis PR adds a conservative PR Metadata
Tests
Final VerdictNeeds another test pass before merge. The core rewrite looks plausible now, but the remaining evidence is still not strong enough for the recursive skip-index path, and the PR metadata should stop auto-closing the broader tracking issue. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds a KeyCondition rewrite that lets primary/partition/skip indexes prune granules for clickbench🟢 No significant changes tpch_adapted_1_officialFlagged queries (1 of 22)
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. Debug info
|
| if (nullif_node->children.size() != 2) | ||
| return nullptr; | ||
|
|
||
| if (canonical_op != "equals") |
There was a problem hiding this comment.
The PR metadata still promises nullIf(key, sentinel) <cmp> const pruning and closes #107209, whose motivating examples include range predicates like nullIf(ts, sentinel) >= const, but this guard only supports equals. As merged, those range predicates keep doing a full scan, so the advertised contract and the linked issue are only partially addressed.
Please either implement the supported range cases conservatively, or narrow the PR body/changelog to nullIf(key, sentinel) = const and do not close the broader issue from this PR.
| CREATE TABLE t_nullif_coalesce (a UInt8, b UInt8, INDEX idx_b b TYPE minmax GRANULARITY 1) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 8192; | ||
| INSERT INTO t_nullif_coalesce VALUES (1, 1), (5, 5); | ||
|
|
||
| EXPLAIN indexes = 1 SELECT count() FROM t_nullif_coalesce WHERE nullIf(coalesce(a, b), 255) = 5; |
There was a problem hiding this comment.
This regression does not exercise the recursive nullIf(coalesce(...)) skip-index path it is meant to protect. a is UInt8 non-Nullable, so coalesce(a, b) normalizes to just a before the comparison; the expected output confirms that no Skip/idx_b entry or disjunctive index condition is used. The test would still pass if the recursive rewrite in tryRewriteNullIfComparison were removed.
Please make the first argument Nullable and shape the data/index so the coalesce(a, b) expansion actually produces a disjunction and uses idx_b, then assert the Skip entry and reduced granules.
There was a problem hiding this comment.
This still does not prove the recursive nullIf(coalesce(...)) skip-index path. The current query has only the three rows inserted at tests/queries/0_stateless/03005_nullif_index_pruning.sql:54, so it creates a single granule, and the reference still records tests/queries/0_stateless/03005_nullif_index_pruning.reference:120 as Condition: true with Granules: 1/1. That would still pass if the recursive rewrite were removed.
Please make this case produce at least one droppable granule and assert a non-trivial idx_b condition/reduced granules.
There was a problem hiding this comment.
The current test still does not exercise that recursive path. The EXPLAIN that asserts idx_b at tests/queries/0_stateless/03005_nullif_index_pruning.sql:59 is for nullIf(b, 255) = 5; the only nullIf(coalesce(a, b), 255) = 5 query is the plain SELECT count() at tests/queries/0_stateless/03005_nullif_index_pruning.sql:62. That checks the final result, but it would still pass if the generated comparison stopped recursively expanding coalesce and the skip-index RPN path were not exercised.
Please make the nullIf(coalesce(a, b), 255) = 5 case itself use EXPLAIN indexes = 1 and assert the idx_b skip-index condition plus reduced granules.
|
Address review: Updated the C++ logic to use recursive cloneDAGWithInversionPushDown and strengthened the stateless test case by making the test column Nullable to properly exercise the coalesce skip-index path. All 128 integration tests are now passing successfully. Ready for review/merge! |
… type and add FixedString regression test
…dexes: Partition section
…f rewrite reaches PartitionPruner
… distributed plan CI
… and skip-index RPNs
78c34cc to
432ecd0
Compare
…ce skip-index path
432ecd0 to
c4fa15a
Compare
|
@KochetovNicolai All failures are pre-existing flaky infrastructure issues,
Could you please trigger re-runs for the two stress tests so the |
|
Hi @KochetovNicolai — following up on this after a few weeks. This PR still has No pressure at all, just want to make sure this hasn't fallen through the cracks. Thanks for your time on this! |
|
Dear @KochetovNicolai, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
Hi @KochetovNicolai — I noticed you were auto-unassigned after 30 days of inactivity on this PR. Could you please take another look, or reassign to someone else if you're unable to continue reviewing? To summarize where things stand: The code changes already have your approving review from earlier. Could someone with write access please: Reassign this PR for final review/merge, and Happy to make any further changes if needed. Thanks for your time! |
…ivate meta-in-keeper jobs The test stably fails only in private CI jobs with 'meta storage in keeper' (clickhouse-test --replace-replicated-with-shared): the merged part of t_nullif_skip_index gets 244 granules instead of 245, while the other 2M-row tables in the same test keep 245. Public CI, including s3 storage and azure jobs, is green on the same commit, so the tag is scoped to shared-merge-tree runs instead of no-s3-storage. CI report: https://d1k2gkhrlfqv31.cloudfront.net/clickhouse-test-reports-private/json.html?PR=60727&sha=c4fa15a695d796f7b01afacf83a5b16a13a8fe37&name_0=PR Private PR: ClickHouse/clickhouse-private#60727 Co-Authored-By: Claude Fable 5 <[email protected]>
Since 26.7 `explain_query_plan_default` defaults to `pretty`, which turns on `actions`, `compact`, and `pretty` for `EXPLAIN` and would change the test output once the branch is merged with current master. The reference is recorded in the legacy format, so pin the setting explicitly. Co-Authored-By: Claude Fable 5 <[email protected]>
| @@ -0,0 +1,69 @@ | |||
| -- Tags: no-distributed-interpreters, no-parallel-replicas, no-replicated-database, no-random-settings, no-random-merge-tree-settings, no-shared-merge-tree | |||
There was a problem hiding this comment.
This tag drops the only regression coverage from the --replace-replicated-with-shared / SharedMergeTree runs even though the rewritten KeyCondition is generic across MergeTree-family engines. The 244 vs 245 difference in private CI is part-layout noise, not the contract this PR needs to prove, so skipping that engine variant means a later regression there will merge unnoticed.
Please make this assertion stable across both layouts instead (for example with smaller deterministic data / granularity, or checks that key off the rewritten condition and reduced granules rather than the exact merged-part granule count) instead of disabling the SharedMergeTree surface entirely.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 37/44 (84.09%) · Uncovered code |
|
Hi @KochetovNicolai — quick update after the latest run: New failure ( On the Thanks for driving the re-runs so far — flagging this mainly so we're not stuck reading the new failure as a real regression. |
1b39fee
…ison is in a disjunction `ReadFromMergeTree::buildIndexes` runs `cloneDAGWithInversionPushDown` once, and the disjunction RPN template (`boolean_context = false`) and the `minmax`/`set` index conditions (`true`) re-run it on that result. `filterMarksUsingIndex` stores each index atom's result under the index's own RPN position and `mergePartialResultsForDisjunctions` reads it by template position, so the first pass must be a fixpoint. Under `NOT`, the boolean-context rewrites were skipped and the comparison was folded into its inverse, e.g. `NOT (coalesce(c, b) > 10)` into `lessOrEquals(coalesce(c, b), 10)`: a non-inverted condition in boolean position that never got those rewrites. The `minmax`/`set` re-pass then expanded it to `c <= 10 OR (isNull(c) AND b <= 10)` while the template kept one atom, so `isNull(c)` landed on the position of `x = 9` and its granule was dropped. Run the folded inverse through the same rewrite chain (coalesce comparison, `!= 0` / IS TRUE, `IN (true)`, nullIf) so every pass produces one layout, as `make_cmp` (ClickHouse#103929) and the nullIf normalization (ClickHouse#107308) already do for their own outputs. Closes ClickHouse#128360 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #107209
Changelog category (leave one):
Changelog entry
Optimize
nullIf(key, sentinel) = constpredicates to build key ranges and enable primary key, partition, and skip-index pruning.Description
This PR introduces a rewrite mechanism (
tryRewriteNullIfComparison) insideKeyConditionto optimize exact equality lookups onnullIfexpressions. When a query filters usingnullIf(col, sentinel) = const, the optimizer now safely unwraps it to a core key range atom oncol, provided thatsentinel != const.To prevent architectural and correctness regressions, this implementation integrates the following safeguards based on code review feedback:
cloneDAGWithInversionPushDownbefore appending the rewritten function node. This ensures downstream analysis paths (such asStatisticsPartPruner) accurately resolve required column dependencies.StringvsFixedString), the rewrite is conservatively restricted. It requires the underlying SQL data types of thenullIffirst argument (col_node), thesentinel_node, and the targetconst_nodeto structurally match exactly.This optimization is gated under the existing
allow_key_condition_coalesce_rewritesetting, and its source-level setting documentation insrc/Core/Settings.cpphas been updated accordingly.Verification & Performance Impact
Tested locally using
clickhouse local:Before Change: Zero pruning, scans all 245/245 granules (Full Table Scan).
After Change: Successfully builds key range, pruning reads down to 2/245 granules.
Integration & Regression Tests Added:
Core index pruning validations: tests/queries/0_stateless/03005_nullif_index_pruning.sql
FixedString zero-padding regression test case added to guarantee safe rewriting paths.