Skip to content

Optimizer: Add index pruning for nullIf(key, sentinel) predicates (#107209) - #107308

Merged
KochetovNicolai merged 18 commits into
ClickHouse:masterfrom
adityaksolves:feature/107209-nullif-pruning-clean
Jul 29, 2026
Merged

KochetovNicolai merged 18 commits into
ClickHouse:masterfrom
adityaksolves:feature/107209-nullif-pruning-clean

Conversation

@adityaksolves

@adityaksolves adityaksolves commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #107209

Changelog category (leave one):

  • Performance Improvement

Changelog entry

Optimize nullIf(key, sentinel) = const predicates to build key ranges and enable primary key, partition, and skip-index pruning.

Description

This PR introduces a rewrite mechanism (tryRewriteNullIfComparison) inside KeyCondition to optimize exact equality lookups on nullIf expressions. When a query filters using nullIf(col, sentinel) = const, the optimizer now safely unwraps it to a core key range atom on col, provided that sentinel != const.

To prevent architectural and correctness regressions, this implementation integrates the following safeguards based on code review feedback:

  1. DAG Invariant Preservation: Operands are explicitly cloned into the inverted DAG via cloneDAGWithInversionPushDown before appending the rewritten function node. This ensures downstream analysis paths (such as StatisticsPartPruner) accurately resolve required column dependencies.
  2. Strict SQL Type Matching: To avoid correctness traps introduced by ClickHouse's zero-padded string comparison logic (e.g., String vs FixedString), the rewrite is conservatively restricted. It requires the underlying SQL data types of the nullIf first argument (col_node), the sentinel_node, and the target const_node to structurally match exactly.

This optimization is gated under the existing allow_key_condition_coalesce_rewrite setting, and its source-level setting documentation in src/Core/Settings.cpp has been updated accordingly.

Verification & Performance Impact

Tested locally using clickhouse local:

CREATE TABLE t_nullif_pruning (team UInt64, k UInt8) ENGINE = MergeTree ORDER BY (team, k) SETTINGS index_granularity = 8192;
INSERT INTO t_nullif_pruning SELECT 1, number % 200 FROM numbers(2000000);
OPTIMIZE TABLE t_nullif_pruning FINAL;

EXPLAIN indexes = 1 SELECT count() FROM t_nullif_pruning WHERE team = 1 AND nullIf(k, 255) = 5;

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.

  • Condition: and((k in [5, 5]), (team in [1, 1]))
  • Granules Read: 2/245

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.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jun 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [16884fb]

Summary: ✅


AI Review

Summary

This PR adds a conservative nullIf(key, sentinel) = const -> key = const rewrite inside KeyCondition and a focused stateless regression. The earlier correctness blockers look addressed, but I do not think the review is done yet: the PR still auto-closes a broader issue than it actually fixes, and the remaining regression coverage still misses one important recursive skip-index path while the newest test-only change removes SharedMergeTree coverage entirely.

PR Metadata
  • Changelog category: Performance Improvement matches the change.
  • Changelog entry: specific and acceptable for the implemented equality-only optimization.
  • The PR body should not say Closes: https://github.com/ClickHouse/ClickHouse/issues/107209, because #107209 also covers range predicates like nullIf(ts, sentinel) >= const and the view path. This PR still implements only equality. Exact replacement:
    Related: https://github.com/ClickHouse/ClickHouse/issues/107209
Tests
  • ⚠️ [tests/queries/0_stateless/03005_nullif_index_pruning.sql:1] no-shared-merge-tree removes the only regression coverage from --replace-replicated-with-shared / SharedMergeTree runs. The 244 vs 245 difference is a merged-part layout detail, not the contract this PR needs to prove. Please make the test stable across both layouts instead of skipping that engine surface.
  • ⚠️ [tests/queries/0_stateless/03005_nullif_index_pruning.sql:67] The recursive nullIf(coalesce(a, b), 255) = 5 case is still validated only by the final row count. That would still pass if the recursive normalization were removed and the engine fell back to a full scan. Please make this case itself use EXPLAIN indexes = 1 and assert the idx_b skip index condition plus reduced granules.
Final Verdict

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

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

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

This PR adds a KeyCondition rewrite that lets primary/partition/skip indexes prune granules for nullIf(key, sentinel) = const predicates; it only fires when a query actually contains such a predicate. None of the three flagged queries use nullIf, so none execute the changed path. ClickBench Q4 (-27.9%) and Q18 (-5.5%) both show flat CPU and are correctly held within the master variance envelope. The one directional flag, tpch_adapted_1_official Q7 (+12.1%), is off-path and its source side had fewer and noisier runs, so it is downgraded to not_sure rather than treated as a real regression.

clickbench

🟢 No significant changes

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 560 628 +12.1% <0.0001 cpu: TPC-H Q7 is join-heavy with no nullIf predicate, so it can't hit the added index-pruning path. The +12.1% came from few, noisier source runs and looks like host contention, not a PR effect.

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
  • StressHouse run: 1732d7a4-d316-4e46-a51d-80089914ae4d
  • MIRAI run: 531cd6f2-b9c9-4948-832c-b37fa4e8a8b1
  • PR check IDs:
    • clickbench_694786_1785257933
    • clickbench_694793_1785257933
    • clickbench_694804_1785257933
    • tpch_adapted_1_official_694810_1785257934
    • tpch_adapted_1_official_694828_1785257933
    • tpch_adapted_1_official_694855_1785257933

if (nullif_node->children.size() != 2)
return nullptr;

if (canonical_op != "equals")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
@adityaksolves
adityaksolves marked this pull request as draft June 12, 2026 17:24
@adityaksolves
adityaksolves marked this pull request as ready for review June 12, 2026 17:31
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@adityaksolves

Copy link
Copy Markdown
Contributor Author

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!

@adityaksolves
adityaksolves force-pushed the feature/107209-nullif-pruning-clean branch 3 times, most recently from 78c34cc to 432ecd0 Compare June 26, 2026 18:25
@adityaksolves
adityaksolves force-pushed the feature/107209-nullif-pruning-clean branch from 432ecd0 to c4fa15a Compare June 27, 2026 15:50
@adityaksolves

Copy link
Copy Markdown
Contributor Author

@KochetovNicolai All failures are pre-existing flaky infrastructure issues,
unrelated to this PR's changes (KeyCondition.cpp, Settings.cpp, stateless test):

  1. Stress test (amd_msan): Logical error: 'removed' in
    DatabaseCatalog::dropTablesParallel — CIDB confirms this fires on
    master (pull_request_number = 0) on multiple dates including 2026-06-26.

  2. Stress test (amd_asan_ubsan): Hung check failed, possible deadlock
    — CI automatically marked this as flaky (known issue Hung check failed, possible deadlock found #107941).

  3. CH Inc sync, Mergeable Check, PR: All downstream consequences
    of the above flaky failures.

Could you please trigger re-runs for the two stress tests so the
Mergeable Check can pass?

@adityaksolves

Copy link
Copy Markdown
Contributor Author

Hi @KochetovNicolai — following up on this after a few weeks. This PR still has
the approving review, but is blocked purely by the two stress test failures I
flagged earlier (both appear to be pre-existing infra flakiness, not related to
this PR's changes — details in my comment above).

No pressure at all, just want to make sure this hasn't fallen through the cracks.
If you get a chance to trigger a re-run for the two stress tests, that would
unblock the merge. And if there's anything else you'd like me to address before
that, please let me know — happy to make any further changes.

Thanks for your time on this!

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

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.

@adityaksolves

Copy link
Copy Markdown
Contributor Author

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.
The only blockers are two flaky infrastructure failures unrelated to this PR's diff (KeyCondition.cpp, Settings.cpp, stateless test only):
Stress test (amd_msan) — Logical error: 'removed' in DatabaseCatalog::dropTablesParallel, confirmed reproducible on master (pull_request_number = 0) across multiple dates.
Stress test (amd_asan_ubsan) — "Hung check failed, possible deadlock found", already tracked as a known flaky issue (
#107941).

Could someone with write access please:

Reassign this PR for final review/merge, and
Trigger a re-run of the two stress test jobs above?

Happy to make any further changes if needed. Thanks for your time!

KochetovNicolai and others added 2 commits July 28, 2026 12:16
…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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.10% +0.10%
Branches 78.30% 78.40% +0.10%

Changed lines: Changed C/C++ lines covered: 37/44 (84.09%) · Uncovered code

Full report · Diff report

@adityaksolves

Copy link
Copy Markdown
Contributor Author

Hi @KochetovNicolai — quick update after the latest run:

New failure (Integration tests (amd_tsan, 1/6)): This is unrelated to this PR's diff. The failing test is test_postgresql_replica_database_engine/test_1.py::test_merge_table_over_materialized_postgresql_database, which has nothing to do with KeyCondition.cpp / nullIf pruning. The actual error is a teardown-time NetException: Connection refused (172.16.3.4:9000) — the server was unreachable during DROP DATABASE ... SYNC cleanup, which is a container/infra-level issue, not a logic regression. The runner itself flagged it as non-blocking (Failed 1 tests - do not block pipeline, exit with 0), consistent with the other flaky infra failures reported earlier on this PR.

On the no-shared-merge-tree tag: I see the AI review flagged that this drops SharedMergeTree coverage entirely — fair point, skipping the engine surface isn't ideal for what's really just a 244 vs 245 merged-part layout difference. Happy to help reshape the test data/granularity to keep it stable across both layouts if that's the preferred direction — just let me know and I can push a follow-up commit.

Thanks for driving the re-runs so far — flagging this mainly so we're not stuck reading the new failure as a real regression.

@KochetovNicolai
KochetovNicolai added this pull request to the merge queue Jul 29, 2026
Merged via the queue into ClickHouse:master with commit 1b39fee Jul 29, 2026
352 of 353 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 29, 2026
Ergus pushed a commit to Ergus/ClickHouse that referenced this pull request Nov 11, 2026
…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]>
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.

nullIf(key, sentinel) predicates build no key range — primary key / partition / skip indexes not used (mirror of #94754)

4 participants