Skip to content

Keep the set skip index pruning granules that contain NULL - #123778

Merged
shankar-iyer merged 2 commits into
ClickHouse:masterfrom
groeneai:set-index-nullable-null-element-prune
Oct 6, 2026
Merged

shankar-iyer merged 2 commits into
ClickHouse:masterfrom
groeneai:set-index-nullable-null-element-prune

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #123705
Related: #111604

Changelog category (leave one):

  • Performance Improvement

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

A set skip index on a Nullable column again skips granules whose stored set contains NULL but not the searched value for IN and = conditions, restoring the pruning lost in 26.8. Closes #123705.

Description

Since 26.8, a set index on a Nullable column keeps every granule whose set contains NULL for c IN (...) / c = ..., so it prunes far less (on a 3.67M-row copy of the issue's table: 448/448 granules on 26.8 and master vs 32/448 on 26.6). Results are unchanged, but every such granule is read.

The cause is my #111604. in and equals on a Nullable column return Nullable(UInt8), so the index atom evaluates to NULL on a NULL set element. #111604 mapped every NULL atom mask to "can be true or false" (to keep #103103 fixed), which also makes a granule that merely contains NULL look like a match.

This PR maps a NULL atom mask to "can be false" only. The mask is combined only by AND / OR / NOT / indexHint (three-valued logic), where a NULL atom can never be what makes the condition true, so no granule holding a matching row is pruned; under NOT it stays conservative. The #103103 shapes ((x AND NULL) OR y) still keep the granule.

Validation, on that copy: skip index 448/448 -> 32/448; for the issue's FINAL query SelectedMarks 448 -> 35 and SelectedRows 3670016 -> 360448, the same as 26.6, with identical results. The same restoration holds for Nullable String, Float64, Date, Decimal and Int8 columns. The new test fails on master and passes with the fix; every other stateless test using TYPE set gives the same result on both binaries.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/123778]

Version info

  • Merged into: 26.10.1.1635-master (included in 26.10 and later)

`in` and `equals` on a `Nullable` column return `Nullable(UInt8)`, so the
set index evaluates `c IN (803)` to NULL on a stored NULL set element.
ClickHouse#111604 wrapped every nullable bit-wrapped atom in
`ifNull(mask, UNKNOWN_FIELD)` to stop a constant NULL atom from propagating
NULL through `__bitBoolMaskAnd`/`Or` (ClickHouse#103103). That also turned the NULL
of a NULL set element into "can be true", so every granule holding a NULL
passed `IN`/`=` and nothing was pruned (26.6: 32/448 granules, 26.8 and
master: 448/448 on the issue's data).

Map a NULL atom mask to "can be false" only (0b10). The mask connectives
are only and/or/not/indexHint, i.e. Kleene logic, where a value fixed with
a NULL operand stays the same for any definite replacement of it; so a row
that makes the condition TRUE also makes it TRUE with every NULL atom read
as FALSE, and no granule holding a matching row can be pruned. For a plain
atom this is exact (WHERE treats NULL as not passing); under an un-pushed
NOT it stays conservative. The ClickHouse#103103 shapes stay fixed:
`(x AND NULL) OR y` -> `(x AND false) OR y` = `y`. This also matches how
KeyCondition already reads a NULL hint.

Closes ClickHouse#123705

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (1 nit).

# Sev Finding Verdict Evidence / action
1 💡 The NOT count guards in the new test keep all granules on master and on the fix, so they check result equality only AGREE, noted, not blocking Pruning is asserted by the six EXPLAIN rows (3 -> 1 and 3 -> 0 against master)

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20261003-224503

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A 3.67M-row copy of the issue table (448 granules): the skip-index line of EXPLAIN indexes = 1 for c1 IN (803) reads 448/448 on master, 32/448 with the fix. The new test keeps 3 granules on master in 20/20 randomized runs.
b Root cause explained? in / equals on a Nullable column return Nullable(UInt8), so the atom is NULL on a NULL set element; #111604's ifNull(mask, 0b11) reads that as "can be true", so every granule holding NULL passes.
c Fix matches root cause? Yes, at the site where the wrong mask is made: a NULL atom mask is now 0b10 ("can be false" only).
d Test intent preserved / new tests added? New 05320_set_index_nullable_null_granule_prune.sql; the #103103 guards (03707, 04627) and 04838 pass unchanged.
e Both directions demonstrated? Yes: master 448/448, fix 32/448 on the issue data (SelectedMarks 448 -> 35 for the FINAL query, as on 26.6); the new test fails on master and passes 50/50 randomized runs with the fix.
f Fix is general across code paths? This wrapper is the only producer of the NULL mask; the other fallbacks (non-integer atom, non-atom) are unchanged; bulk and non-bulk granule paths are both covered by the test.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured for Nullable UInt32, Int8, String, Float64, Date, Decimal, plus AND / OR / NOT / IN (5, NULL): each matches 26.6 with the fix. LowCardinality(Nullable) is not pruned on any version (26.6 included) and is unchanged.
h Backward compatible? (maintainer-approved exception only) Yes: index-analysis precision only, no setting, format or stored-data change.
i Invariants and contracts preserved? The mask stays a non-Nullable UInt8 and a sound over-approximation (a NULL atom never makes AND / OR true; under NOT it is conservative); row counts are identical with and without the index in every arm.

Session id: cron:clickhouse-impl-slot-41:20261003-215300

@groeneai
groeneai requested review from al13n321 and rschu1ze October 3, 2026 23:10
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e8ee647]

Summary: ✅


AI Review

Summary

This PR changes MergeTreeIndexSet so a nullable atom in the set skip-index evaluator maps NULL to the “can be false” mask instead of the “can be true or false” mask, which restores pruning for IN / = predicates on Nullable indexed values while remaining conservative in the boolean combinations the set index supports. I reviewed the current diff, the linked issue, and the prior PR discussion, and I did not find any correctness, safety, compatibility, or test-coverage problems in the current version.

Final Verdict

✅ No findings. The change looks correct and the added stateless coverage exercises both bulk and non-bulk set-index pruning paths.

LLVM Coverage Report

Measured on commit e8ee647.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. labels Oct 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e8ee64788 with master 37a251ffa (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 13 s compile time in total, 7 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes only how a set skip index on a Nullable column handles NULL values during granule pruning. In the index condition, a NULL result now means 'can be false only' instead of 'unknown'. The PR also adds a stateless test. Neither ClickBench nor TPC-H defines set skip indexes, so no benchmark query runs the changed code. The flagged ClickBench improvements on Q30 (-14.5%) and Q31 (-12.6%) show almost no CPU change, so they are downgraded to not sure. Q28 (mixed test signals) and Q33 (within master's normal range) need no action, and the Q33 suppression is consistent with the diff.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1072 1013 -5.5% <0.0001 The two tests disagree and the measurements were noisy. ClickBench defines no set skip index, so this PR's change cannot reach this query.
⚠️ 30 not_sure 221 189 -14.5% <0.0001 The -14.5% shift has almost no CPU change behind it. The ClickBench table has no set skip index, so the changed set-index pruning code never runs here.
⚠️ 31 not_sure 269 235 -12.6% <0.0001 The -12.6% shift has almost no CPU change behind it. The ClickBench table has no set skip index, so the changed set-index pruning code never runs here.

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.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 31b9f84a-60f4-438a-a8dc-34a4fee499fb
  • MIRAI run: beb74e30-47c7-4be8-bd8c-60700cbd0ea9
  • PR check IDs:
    • clickbench_3164137_1791095413
    • clickbench_3164143_1791095413
    • clickbench_3164154_1791095413
    • tpch_adapted_1_official_3164171_1791095413
    • tpch_adapted_1_official_3164193_1791095413
    • tpch_adapted_1_official_3164207_1791095413

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 50be039

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (amd_fuzzers) / Build ClickHouse not from this PR: the clickhouse_fuzzer link fails with relocation R_X86_64_PC32 out of range; the same job failed on 181 PRs and 40 master runs in the last 24h, and master is green again from 80f00c857b36 #123738 (external, merged 01:14Z). This run was dispatched at 23:09Z, before it merged, so a master merge to pick it up follows
Performance Comparison (amd_release, master_head, 6/6) / is_valid_utf8 #0 not from this PR, which changes only the set skip index (MergeTreeIndexSet), and this query reads no table: dashboard confirmed_regression, client_time 0.0144 -> 0.0171 s (+19.1%), still +21.1% after the server restart; the same query is red on 3 PRs today on the same master base a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05213_timeseries_metric_families_target, 05218_timeseries_alp_codec not from this PR: on a parallel replica the TimeSeries table functions resolve their targets in default (UNKNOWN_TABLE for default.ts_v3_restored and default.ts_alp32); 75 and 33 PRs in 24h on this job #123763 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant not from this PR: under a Replicated database the replicated CREATE VIEW stores a nested WITH alias qualified with the database, so the view reads the same-named table; 185 PRs in 24h #123790 (external, open): it carries the ApplyWithSubqueryVisitor fix for this alias
Mergeable Check, PR rollups, red only because of the rows above #123738, #123763, #123790 and the fix task above (a fix task is created)

All 160 checks completed, Finish Workflow is green and CH Inc sync passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261004-040438

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for is_valid_utf8 #0 created: #123835

@rschu1ze

rschu1ze commented Oct 4, 2026

Copy link
Copy Markdown
Member

@groeneai Sorry, I won't find time to review.

@shankar-iyer shankar-iyer self-assigned this Oct 6, 2026
@shankar-iyer

Copy link
Copy Markdown
Member

@groeneai I am a bit unclear here :

in and equals on a Nullable column return Nullable(UInt8), so the index atom evaluates to NULL on a NULL set element. #111604 mapped every NULL atom mask to "can be true or false" (to keep #103103 fixed), which also makes a granule that merely contains NULL look like a match.

So let's say column is x Nullable(String) and has a set index and predicate is WHERE x = 'abc'. We need to look for abc in the index granules. Can you now explain what happens next that is the problem cause?

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

The set index does not look 'abc' up in the stored set. MergeTreeIndexConditionSet evaluates the predicate on every element stored for the granule, and keeps the granule if at least one element can make it true.

Take a granule whose set is {'aaa', 'xyz', NULL}:

  1. traverseDAG turns the atom x = 'abc' into __bitWrapperFunc(equals(x, 'abc')), which gives a mask per element: 0b01 = can be true, 0b10 = can be false. Since x is Nullable(String), equals returns Nullable(UInt8), so the mask is nullable too.
  2. mayBeTrueOnGranule (or the bulk getPossibleGranules) runs this on the granule's set block and keeps the granule if any element has mask & 1:
element x = 'abc' __bitWrapperFunc ifNull(mask, 0b11) (#111604) ifNull(mask, 0b10) (this PR)
'aaa' 0 2 2 2
'xyz' 0 2 2 2
NULL NULL NULL 3 2
  1. With Set skip index: route NULL-constant atoms to UNKNOWN so granules are not wrongly pruned #111604, the NULL element reads as "can be true or false", 3 & 1 = 1, so the granule is kept although it has no 'abc'. Any granule with at least one NULL in its set is read, whatever the constant is.
  2. This PR reads it as "can be false only". For rows where x is NULL, x = 'abc' is NULL, and that never satisfies WHERE. So now only an element that really equals 'abc' keeps the granule.

#103103 is still fixed. There the NULL atom was a constant inside an OR (CAST(NULL, 'Nullable(String)') = 'X' OR v = 'X'), and the bug was the raw NULL mask propagating through __bitBoolMaskOr, which erased the v = 'X' disjunct. Any non-NULL mask avoids that: 0b10 OR 0b01 = 0b01, so the matching granule is kept. Under NOT, 0b10 becomes 0b01 (kept), which can only miss a prune, never lose a row.

I checked it on that granule plus {'abc', 'xyz'} and {'aaa', 'xyz'} (index_granularity = 4, set(0)). Master 44b568f reads 2/3 granules and this PR reads 1/3, with secondary_indices_enable_bulk_filtering both 0 and 1. count() is 1 on both binaries, and so is the #103103 shape:

CREATE TABLE t (id UInt32, x Nullable(String), INDEX i x TYPE set(0) GRANULARITY 1)
ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 4, index_granularity_bytes = 0;
INSERT INTO t VALUES (0,'aaa'),(1,'xyz'),(2,NULL),(3,NULL),(4,'abc'),(5,'xyz'),(6,'xyz'),(7,'xyz'),(8,'aaa'),(9,'xyz'),(10,'aaa'),(11,'xyz');
EXPLAIN indexes = 1 SELECT count() FROM t WHERE x = 'abc';

@shankar-iyer
shankar-iyer added this pull request to the merge queue Oct 6, 2026
Merged via the queue into ClickHouse:master with commit 1c8efed Oct 6, 2026
149 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 6, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 7, 2026
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 comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport v26.8-must-backport v26.9-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

set skip index on a Nullable column keeps granules that contain NULL, about 2x slower (26.6 -> 26.8)

5 participants