Skip to content

Set skip index: route NULL-constant atoms to UNKNOWN so granules are not wrongly pruned - #111604

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-set-index-null-const-unknown-103103
Jul 30, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-set-index-null-const-unknown-103103

Conversation

@groeneai

@groeneai groeneai commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed wrong results when a query has a set skip index and a predicate of the shape (x AND <null-value>) OR y, where the NULL is produced by a function (e.g. toInt64OrNull('x'), nullIf(1, 1), CAST(NULL AS Nullable(Int64))). Such a value was wrapped by __bitWrapperFunc and propagated NULL instead of the "unknown" mask, so the set index could prune granules that actually match and the query returned fewer rows than it should.

Description

Closes #103103

When building the set-index condition, MergeTreeIndexConditionSet::traverseDAG wraps each integer atom with __bitWrapperFunc to turn a boolean into a BoolMask (the 0b01/0b10/0b11 "can be false / can be true / unknown" bits).

A NULL value with an integer element type (a Nullable(Int64) NULL from toInt64OrNull('x'), nullIf(1, 1), CAST(NULL AS Nullable(Int64)), or a nullable comparison result such as CAST(NULL, 'Nullable(String)') = 'VALUE1') passes the integer test and gets wrapped. __bitWrapperFunc uses the default NULL implementation, so a NULL input yields a NULL mask instead of the 0b11 unknown mask. That NULL then propagates through __bitBoolMaskAnd/__bitBoolMaskOr, the result column becomes NULL, and both granule-analysis paths read NULL & 1 == 0 and prune granules that should match, producing fewer rows: the per-granule mayBeTrueOnGranule and the bulk getPossibleGranules (whose onlyNull() guard only catches a whole all-NULL mask column, not a NULL mixed into a per-set-element mask).

Fix: when the bit-wrapped atom is nullable, coalesce a NULL mask to UNKNOWN_FIELD (0b11) with ifNull. NULL is mapped to UNKNOWN, which is the correct BoolMask meaning, so the AND/OR/NOT operators and both granule paths are covered at the source. This handles the NULL regardless of whether it folds to a constant column, so it also covers values hidden behind functions that suppress constant folding (identity, materialize), and it does not evaluate the atom during index analysis. A bare NULL literal and non-integer typed NULLs were already routed to UNKNOWN_FIELD and are unaffected.

03707_set_index_bad_get_null_bug asserted the old (incorrect) pruning for exactly this shape: its single row matches via the second disjunct, so the correct result is 1 row, not 0; its reference is updated to the corrected plan and gains count assertions. New test 04627_set_index_null_const_no_prune asserts that the set index does not change the result for the affected predicate shapes (including the identity/materialize wrappers and a NOT form) across both granule-filtering paths, and that legitimate pruning is preserved.

Version info

  • Merged into: 26.8.1.443-master (included in 26.8 and later)

@groeneai

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

Pre-publication review by an independent model (engine: codex; 2 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ Test did not prove the index still prunes, nor discriminate the fix: the old positive controls (lc='1'→33, lc='999'→0) matched even with skip indexes globally disabled (a full scan yields the same counts), and the old NOT line returned the expected value on the pre-fix binary too. AGREE — fixed Confirmed via EXPLAIN indexes = 1: lc='999'→Granules: 0/3 (pruned), lc='1'→Granules: 3/3 (kept). Rewrote the test: kept the discriminating count asserts (pre-fix returns 0, post-fix 50 — reconfirmed both-directions on pristine vs fixed binaries) and added two EXPLAIN indexes = 1 granule-count liveness asserts proving the index still prunes.
2 💡 Draft PR description mis-described the bulk path (claimed getPossibleGranules's onlyNull() guard avoids the bug) and named a stale test number. AGREE — fixed Verified on a 10k-row multi-granule table: the pre-fix bulk path getPossibleGranules also returns the wrong count (ColumnNullable::onlyNull() is false for a materialized all-null Nullable(UInt8)), so both granule paths were affected — which is exactly why the fix belongs in traverseDAG (covers both). Corrected the description; fixed the test name to 04627 (the 04626 slot was taken by a newer master test). Description-only; no source change.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-author-slot-1:20260723-091900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM m1 WHERE (v = 1 AND toInt64OrNull('x')) OR v < 50 returns 0 (should be 50) on pristine master; equals the use_skip_indexes=0 result (50) with the fix. Reproduces every run, no randomization needed.
b Root cause explained? traverseDAG wraps an integer-typed atom with __bitWrapperFunc. A function-produced NULL constant (toInt64OrNull('x') → Nullable(Int64) NULL) passes the is_integer_atom test and gets wrapped; __bitWrapperFunc/__bitBoolMask* use the default-null impl → propagate NULL instead of the 0b11 unknown mask → both granule paths read NULL & 1 == 0 and prune matching granules.
c Fix matches root cause? Yes. Extends the existing wrap-decision (which already routes non-integer atoms to UNKNOWN_FIELD) to also route an only-null constant to UNKNOWN_FIELD, stopping the NULL at the exact point it would enter the __bit* algebra — the owning function, not a consumer guard.
d Test intent preserved / new tests added? New test 04627_set_index_null_const_no_prune. Weakens no existing test. Asserts index-vs-expected parity for the buggy shapes AND, via EXPLAIN indexes = 1 granule counts, that the index still prunes real matches (Granules: 0/3 for a non-matching value, 3/3 for a matching one).
e Both directions demonstrated? Yes. Pristine binary FAILS the test (integer-NULL-const cases return 0); fixed binary PASSES. Verified by reverting the source, rebuilding, and diffing against the reference.
f Fix is general across code paths? Yes. The NULL is stopped at the source, so all consumers are covered uniformly: __bitWrapperFunc (atoms), __bitBoolMaskAnd/Or (AND/OR), __bitSwapLastTwo (NOT), and both mayBeTrueOnGranule (per-granule) and getPossibleGranules (bulk, verified separately to have been affected too).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. onlyNull() is type-agnostic: matches Nullable(Int64), Nullable(Float64) (already via non-integer path), LowCardinality-wrapped and bare NULL (Nullable(Nothing), already handled). Matrix verified: toInt64OrNull, nullIf(1,1), CAST(NULL AS Nullable(Int64)), toUInt8OrNull, LC-column-in-AND all → correct; plus 50/50 randomized runs (analyzer/prewhere/skip-index/MergeTree settings) → 0 mismatches.
h Backward compatible? Yes. No setting default, on-disk/wire/metadata format, or new validation changed. The change only makes the index prune less (restores correct, more-inclusive results). No SettingsChangesHistory.cpp change needed.
i Invariants and contracts preserved? Yes. Upholds the invariant the __bit* algebra relies on — every wrapped atom resolves to a non-null BoolMask UInt8 — now enforced for only-null constants (routed to the valid 0b11 unknown mask). No block-structure, ordering, or concurrency contract touched.

Session id: cron:clickhouse-author-slot-1:20260723-091900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @shankar-iyer — could you review this? A function-produced NULL constant (e.g. toInt64OrNull(\x27x\x27)) in a (x AND <null-const>) OR y predicate was wrapped by __bitWrapperFunc and propagated NULL instead of the unknown mask, so the set skip index pruned matching granules and returned fewer rows. Fix routes only-null constant atoms to UNKNOWN_FIELD in traverseDAG.

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d100a52]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue

AI Review

Summary

This PR fixes MergeTreeIndexSet so nullable atoms are coerced to UNKNOWN_FIELD before the BoolMask operators see them, which prevents set skip indexes from pruning matching granules when a predicate contains a function-produced NULL. I traced the new ifNull(__bitWrapperFunc(atom), UNKNOWN_FIELD) path through both mayBeTrueOnGranule and getPossibleGranules, checked the updated stateless coverage and prior discussion, and did not find any new correctness, compatibility, or test-evidence gaps.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 23, 2026
A NULL value reaching the set skip index (e.g. `toInt64OrNull('x')`,
`nullIf(1, 1)`, `CAST(NULL AS Nullable(Int64))`, or a nullable comparison
result) is wrapped by `__bitWrapperFunc`, which returns NULL for a NULL
input instead of a BoolMask. That NULL propagates through
`__bitBoolMaskAnd`/`__bitBoolMaskOr`, so a disjunction such as
`(v = 1 AND toInt64OrNull('x')) OR v < 50` evaluates to a NULL granule
mask and the granule is wrongly pruned, silently returning fewer rows
than the same query with `use_skip_indexes = 0`.

When the bit-wrapped atom is nullable, coalesce a NULL mask to
`UNKNOWN_FIELD` (0b11, "can be true or false") with `ifNull`. NULL is
mapped to UNKNOWN, the correct BoolMask meaning, so the granule is no
longer excluded. Unlike inspecting a folded constant column, this also
covers NULLs hidden behind functions that suppress constant folding
(`identity`, `materialize`, ...), without evaluating the atom during index
analysis.

03707_set_index_bad_get_null_bug asserted the old (incorrect) pruning: its
single row matches via the second disjunct, so the correct result is 1 row,
not 0. Its reference is updated to the corrected plan and gains count
assertions. New test 04627 covers the constant/identity/materialize/NOT
shapes across both granule-filtering paths
(`secondary_indices_enable_bulk_filtering` 0 and 1) and confirms legitimate
pruning is preserved.

Closes: ClickHouse#103103

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-set-index-null-const-unknown-103103 branch from d91fe67 to a3e097d Compare July 23, 2026 15:21
@groeneai

Copy link
Copy Markdown
Collaborator Author

Internal second-model review (maintenance round, ci-fix for 03707)

Adjudication of Gate B findings (click to expand)

This round widened the fix (see below) and updated the regression tests. Independent
second-model review findings, all verified locally and addressed:

# Severity Finding Verdict Resolution
1 major The set-index NULL fix based on a folded constant column missed NULLs hidden behind constant-folding-suppressing wrappers (identity, materialize), so (v = 1 AND identity(toInt64OrNull('x'))) OR v < 50 still returned wrong results AGREE (reproduced: 0 vs 50) Re-implemented the fix as ifNull(__bitWrapperFunc(atom), UNKNOWN_FIELD) on nullable bit-wrapped atoms. Covers constants, folding-suppressed wrappers, and nullable comparison results uniformly, without evaluating the atom during index analysis (so no new side effects)
2 major A NOT (... AND v >= 50) regression assertion was non-discriminating (the inner conjunction is always false) AGREE (returned 100 with the fix reverted) Replaced with NOT ((lc = '1' AND toInt64OrNull('x')) OR v >= 50) (33 fixed / 0 buggy)
3 major The Granules: 3/3 liveness assertion was flaky under randomized min_bytes_for_wide_part (Wide part -> 4/4) AGREE (reproduced) Made the pruning assertions format-agnostic (no hard-coded total) and moved the keeps-granules check onto the affected NULL-atom shape

Both regression tests were confirmed to FAIL on a pristine (pre-fix) build and PASS on the
fixed build, across both granule-filtering paths and a randomized-settings sweep.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a3e097d

The earlier PR-caused Fast test / 03707_set_index_bad_get_null_bug failure is now FIXED on this head (the reference was updated to the corrected, non-wrongly-pruned plan). Every remaining red is an unrelated trunk/infra failure with an owner; none is caused by this PR (diff = MergeTreeIndexSet.cpp set-index NULL-const fix + set-index tests).

Check / test Reason Owner
Fast test / 03707_set_index_bad_get_null_bug PR-caused (our fix changed set-index pruning; reference asserted a latent wrong prune) PR-caused -> fixed in this PR @ a3e097d (reference updated + count asserts)
Upgrade check (amd_release) / New+Changed settings not in history (join_runtime_filter_min_probe_rows) trunk regression: introducing PR #104860 placed the history entry in the 26.7 section, so it flags on every PR fixing PR #111671 (ours, open)
Stateless (amd_asan_ubsan, distributed plan, parallel) / 02477_single_value_data_string_regression + 02481_i43247_ubsan_in_minmaxany host memory pressure: both fail with Code 241 MEMORY_LIMIT_EXCEEDED (expected 33), non-reproducible on rerun (02481 40/40 pass) a fix task is tracking the distributed-plan-variant runner OOM at full effort
Stress test (amd_tsan) / Cannot start clickhouse-server + Check failed chronic host-memory-pressure server-startup flake a fix task is tracking it

Session id: cron:our-pr-ci-monitor:20260723-213000

@PedroTadim PedroTadim self-assigned this Jul 30, 2026
@PedroTadim
PedroTadim enabled auto-merge July 30, 2026 13:22
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

@PedroTadim
PedroTadim added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit 58a7912 Jul 30, 2026
177 of 179 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 Jul 30, 2026
alexey-milovidov pushed a commit to fastio/ClickHouse that referenced this pull request Oct 6, 2026
`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]>
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 11, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 11, 2026
PedroTadim added a commit that referenced this pull request Nov 12, 2026
The backport of #111604 used `ColumnConstPtr` and the three-argument
`ActionsDAG::addColumn(column, type, name)` overload, neither of which exists
in 26.3. Build failed with:
  error: unknown type name 'ColumnConstPtr'
  error: no viable conversion from 'ColumnPtr' to 'ColumnConst'
Rewrite the NULL-mask mapping to build a `ColumnWithTypeAndName` and call the
single-argument `addColumn`, matching the adjacent `else` branch in the same
function.

Build log: https://s3.amazonaws.com/clickhouse-test-reports/PRs/130735/4dc280f0a6520269e1bc114481c6d319f80319d4/build_amd_debug/build_clickhouse/build_clickhouse.log
PedroTadim added a commit that referenced this pull request Nov 12, 2026
Backport #111604 to 26.3: Set skip index: route NULL-constant atoms to UNKNOWN so granules are not wrongly pruned
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…o UNKNOWN so granules are not wrongly pruned
leshikus pushed a commit that referenced this pull request Nov 13, 2026
The backport of #111604 used `ColumnConstPtr` and the three-argument
`ActionsDAG::addColumn(column, type, name)` overload, neither of which exists
in 26.3. Build failed with:
  error: unknown type name 'ColumnConstPtr'
  error: no viable conversion from 'ColumnPtr' to 'ColumnConst'
Rewrite the NULL-mask mapping to build a `ColumnWithTypeAndName` and call the
single-argument `addColumn`, matching the adjacent `else` branch in the same
function.

Build log: https://s3.amazonaws.com/clickhouse-test-reports/PRs/130735/4dc280f0a6520269e1bc114481c6d319f80319d4/build_amd_debug/build_clickhouse/build_clickhouse.log
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v25.12-must-backport v26.4-must-backport

Projects

None yet

5 participants