Skip to content

Fix Parquet pruning dropping NULL rows that ifNull, coalesce or a transform_null_in set matches - #128575

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-parquet-null-matching-pruning
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-parquet-null-matching-pruning

Conversation

@groeneai

@groeneai groeneai commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #128505
Related: #128570

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 Parquet row group and page index filtering skipping rows with NULL when the filter maps NULL to a matching value through ifNull, coalesce or a set holding NULL, such as ifNull(x, 42) IN (42, 43) or intDiv(x, 10) IN (NULL, 5) with transform_null_in = 1. Primary key analysis of a Nullable MergeTree key skipped such rows too when a decreasing function is applied first, such as ifNull(-x, 42) IN (42, 43).

Description

On 26.8.34.13 (also 26.3.60.2), SELECT count() FROM file('t.parquet') WHERE ifNull(id, toInt64(42)) IN (42, 43) returns 0 instead of 1 for a row group holding a NULL and otherwise only -1; it returns 1 with input_format_parquet_filter_push_down = 0, input_format_parquet_page_filter_push_down = 0.

The Parquet reader represents a NULL in a row group or page range as -inf (adjustRangeFromIndexIfNeeded). The two consumers that match a NULL against a key range assumed it is +inf: ifNull, coalesce and assumeNotNull getMonotonicityForRange checked only the right bound, and MergeTreeSetIndex::checkInRange compares a NULL set element only as equal to +inf. A decreasing step such as -id moves the +inf NULL of a Nullable MergeTree key to -inf too.

Both consumers now treat an infinite bound on either side as a possible NULL: the three functions are not monotonic when either bound is infinite, and the set index widens a range with an included -inf up to +inf when the set holds a NULL in that position (both checkInRange overloads). The reader is unchanged, so ordinary predicates (id > 0) still prune row groups and pages that hold NULLs. Both changes only make index analysis more conservative.

Not covered: the Parquet bloom and dictionary filters can still drop a plain x IN (NULL, 5) with transform_null_in = 1; that separate mechanism is fixed in #128570.

Validation: the new test fails on master in 19 NULL-matching lines and passes with the fix, 50/50 randomized runs. ParquetPrunedRowGroups, ParquetPrunedPages and SelectedMarks checks confirm that row groups, pages and granules are still pruned where no NULL can match. gtest_monotonic.cpp now covers both bounds.

🤖 Generated with Claude Code


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

groeneai and others added 6 commits November 2, 2026 01:25
…match

Parquet filter push-down stands a NULL in a row group or page min/max range
in as `-inf` (`Parquet::Reader::adjustRangeFromIndexIfNeeded`), while the two
consumers that match a NULL against a key range assumed it is always `+inf`:

- `ifNull`, `coalesce` and `assumeNotNull` `getMonotonicityForRange` checked
  only the right bound, so a range `[-inf (NULL), -1]` was reported monotonic
  and `ifNull(id, 42) IN (42, 43)` pruned a row group whose NULL row gives 42.
- `MergeTreeSetIndex::checkInRange` compares a NULL set element (kept under
  `transform_null_in`) only as equal to `+inf`, so the set `{NULL, 5}` never
  intersected a range that holds its NULL at `-inf`.

The `+inf` assumption does not hold inside index analysis either: a
decreasing step (`Range::invert`) moves the `+inf` NULL of a MergeTree key to
`-inf`, so `ifNull(-id, 42) IN (42, 43)` on a Nullable key lost its NULL row
the same way.

Both consumers now treat an infinite bound on either side as a possible
NULL. The three functions are not monotonic when either bound is infinite,
and the set index widens a range with an included `-inf` up to `+inf` when the
set holds a NULL in that position (both `checkInRange` overloads). The
Parquet producer is unchanged, so ordinary predicates such as `id > 0` keep
pruning row groups that hold NULLs; the test checks that through
`ParquetPrunedRowGroups`.

Not changed here: Parquet bloom and dictionary filters hash a NULL set
element as the nested default, which is a separate mechanism.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in 05496

`gtest_monotonic.cpp` pinned the old right-only contract of `ifNull`,
`coalesce` and `assumeNotNull` `getMonotonicityForRange`: a Nullable range
with an infinite left bound was expected to be monotonic. It now passes both
bounds and expects a range with an infinite bound on either side to be
non-monotonic for Nullable and LowCardinality(Nullable) arguments.

05496 gains a Nullable MergeTree key under a decreasing step (`-id`), which
moves the key's `+inf` NULL to `-inf` and is the only test line that needs
the widening in the sparse `checkInRange` overload, and
`ParquetPrunedRowGroups` checks over the all-NULL file, so a fix that stops
pruning altogether for these shapes fails the test too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…edPages

With the default 1 MiB data page size each column chunk was a single page,
so the page arm only asserted counts: a page push-down that silently stopped
pruning left every expected value unchanged. Both files are now written with
`output_format_parquet_data_page_size = 1`, `output_format_parquet_batch_size
= 1000` and no dictionary, giving 10 pages per 10000-row group, and the final
section records `ParquetPrunedPages` next to `ParquetPrunedRowGroups` for an
`id > 0` check and the all-NULL `ifNull` / `transform_null_in` queries of the
page arm (20 / 10 / 10 pages pruned).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The two Nullable MergeTree key queries only asserted counts, so primary key
analysis that stopped pruning (an unconditional set widening in the sparse
`checkInRange` overload, or `ifNull` treated as never monotonic) left them
unchanged. Both queries now carry a `log_comment`, and the final section
checks `SelectedMarks < SelectedMarksTotal` for them in `system.query_log`:
with the fix only the granule holding the NULL is read. This does not depend
on the granule layout, which varies under randomized MergeTree settings
(1 of 2 or 1 of 3 granules read over 50 randomized runs).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The MergeTree arm of the test exercises the sparse
MergeTreeSetIndex::checkInRange overload, which primary key analysis
takes only when use_lightweight_primary_key_index_analysis = 1. The
runner randomizes that setting (False in ~40% of runs), and then the
dense overload is used, which the Parquet arms already cover. Pin the
setting to 1 with a per-setting random limit so the MergeTree arm always
reaches the sparse overload.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reword the NULL-as-infinity line in the ifNull, coalesce and assumeNotNull monotonicity comments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 2, 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; 5 rounds, 6 findings) plus my own review (5 rounds, 7 findings); 10 distinct below. The last round on b94e3e09684a raised nothing.

# Sev Finding Verdict Evidence / action
1 ❌ gtest_monotonic.cpp still expected a range with an infinite left bound to be monotonic for Nullable AGREE, fixed helper takes both bounds; Monotonicity.* passes, fails with the ifNull check reverted
2 ⚠️ Count-only assertions cannot see an over-conservative fix (row groups, pages) AGREE, fixed ParquetPrunedRowGroups / ParquetPrunedPages guards over pinned 1000-value pages; redden with an unconditional ifNull check or dense widening
3 ⚠️ The sparse checkInRange overload's widening had no reddening case AGREE, fixed Nullable MergeTree key arm under a decreasing step reddens with it disabled
4 ⚠️ The MergeTree arm asserts only counts AGREE, fixed SelectedMarks < SelectedMarksTotal guards (layout-independent, not an exact granule count); redden with an unconditional ifNull check or sparse widening
5 ⚠️ The MergeTree arm reaches the sparse checkInRange overload only when the randomized use_lightweight_primary_key_index_analysis is drawn 1 AGREE, fixed Random settings limits clamp to 1; the sparse-widening mutations now fail 20/20 randomized runs (13/20 without the clamp); the dense overload stays guarded by the Parquet arms
6 💡 has([NULL, 5], x) not tested DISAGREE same set-index path as x IN (NULL, 5), already reddened
7 💡 Pruning price on a Nullable non-first MergeTree key column DISAGREE conservative only, boundary piece of forAnyHyperrectangle; existing EXPLAIN tests unchanged
8 💡 Description over-claimed which over-conservative variants the guards catch; the entry listed assumeNotNull(x) = 0, whose NULL result is documented as arbitrary AGREE, fixed description and entry rewritten
9 💡 The bloom/dictionary half was not linked AGREE, fixed Related: #128570
10 💡 Set index constructor scans every set element for NULL DISAGREE follows a sort of the same columns in the same constructor; once per set

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-self-slot-58:20261102-044100

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A 20000-row Parquet file, row groups of 10000, every row group holding NULLs and otherwise -1: ifNull(id, toInt64(42)) IN (42, 43), toFloat64(ifNull(...)) = 42, toInt64(coalesce(...)) = 42, intDiv(id, 10) IN (NULL, 5) / id IN (NULL, 5) with transform_null_in = 1 return 0 on every run with push-down on, and the true count with it off.
b Root cause explained? The Parquet reader represents a NULL in a row group or page range as -inf. ifNull/coalesce/assumeNotNull getMonotonicityForRange checked only the right bound for NULL, so [-inf (NULL), -1] was monotonic and stayed [-inf, -1], which excludes 42. MergeTreeSetIndex::checkInRange compares a NULL set element only as equal to +inf, so {NULL, 5} never intersected [-inf (NULL), 0] or the all-NULL [-inf, -inf].
c Fix matches root cause? Yes. The consumers that match a NULL now treat an infinite bound on either side as a possible NULL; the producer and every other predicate keep their pruning.
d Test intent preserved / new tests added? New 05496_parquet_pruning_null_matching_predicates: row group and page arms, a mixed file and an all-NULL row group, a Nullable MergeTree key under a decreasing step, and ParquetPrunedRowGroups, ParquetPrunedPages and SelectedMarks lines pinning that pruning is kept where no NULL can match. gtest_monotonic.cpp now checks both bounds (it pinned the old right-only contract).
e Both directions demonstrated? Yes. Master build: 19 NULL-matching lines return 0 and the all-NULL set query prunes both row groups. Fix build: the reference matches; 50/50 randomized runs green; Monotonicity.* passes and fails with the ifNull check reverted.
f Fix is general across code paths? Yes. All three functions with the right-only check are changed; the set widening is in both checkInRange overloads (Parquet uses the dense one; the MergeTree line reddens with either one disabled). IS NULL/IS NOT NULL atoms were already direction-agnostic.
g Fix generalizes across inputs (params/datatypes/wrappers)? Covered: function chains around the NULL-substituting call (toFloat64, toInt64), IN and =, sets with NULL and a value, mixed and all-NULL row groups, row group and page index. LowCardinality(Nullable) goes through the same canContainNull/isNullAt.
h Backward compatible? (maintainer-approved exception only) Yes. Index analysis only; no setting, format or stored-data change.
i Invariants and contracts preserved? The set index still sees each range as a superset of the input range (only the right bound grows), so the binary search cannot produce begin > end; the per-call ranges buffer is rewritten on every call. Results can only move from "pruned" to "read".

Session id: cron:clickhouse-impl-self-slot-57:20261102-023100

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5beca7f]

Summary: ✅


AI Review

Summary

The PR prevents Parquet and Nullable key pruning from dropping matching NULL rows by handling either infinity in null-substituting function analysis and set membership checks. No actionable findings. The added regression coverage exercises row groups, pages, and decreasing primary-key expressions while checking that pruning remains effective. Local builds and tests were not rerun.

Final Verdict

Status: ✅ Approve

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @al13n321, could you review this and add the can be tested label so CI runs? The Parquet reader represents a NULL in a row group or page range as -inf, while the ifNull/coalesce/assumeNotNull monotonicity check and MergeTreeSetIndex::checkInRange assumed NULL is +inf, so filters mapping NULL to a matching value pruned the NULL rows; the consumers now treat an infinite bound on either side as a possible NULL.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. can be tested Allows running workflows for external contributors labels Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5beca7fca with master d011c6b84 (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

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

Median compile-time ratio to the baselines is ×1.07 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +382.8 s (+7%) in total before that adjustment.

Job report

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 8, 2026
…s set holds NULL

The data-file partition key is built from removeNullable(source type), and
ManifestFilesPruner evaluates a NULL partition value as the single point +inf.
For a non-Nullable key KeyCondition drops every NULL set element, so
has([NULL, 1], b) became {1}, nothing matched +inf, and the data file of the
NULL partition was skipped. Dropping the NULL element is exact only for a
partition tuple without NULL.

The pruner now also builds the same key over Nullable inputs, with its own
condition, and uses that pair only for a partition tuple holding NULL in a
Nullable key position (a void field has type Tuple() and never selects it).
Every other tuple keeps the existing key and condition.

A Nullable key for every file is not used: for an untyped set holding NULL,
such as [NULL, 5] (Array(Nullable(UInt8))), the has() atom is declined for a
Nullable(Int64) key (not safely castable, and canBeInsideNullable() is false
for a Nullable key), so files of tables without a NULL partition would no
longer be pruned. Accepting a Nullable key at that KeyCondition guard would
give the untyped set the typed shape that the Parquet row-group filter still
gets wrong (ClickHouse#128570, ClickHouse#128575), and is MergeTree-wide.

The manifest-list pruner (master only) is fixed separately by ClickHouse#130158.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 9, 2026
…er's set holds NULL

DeltaLake::PartitionPruner built its partition key over removeNullable(type),
and canBePruned evaluates a NULL partition value (__HIVE_DEFAULT_PARTITION__) as
the point +inf. For a non-Nullable key column KeyCondition drops every NULL
element of a set, so has([NULL, 1], p) or p IN (NULL, 1) with
transform_null_in = 1 became the set {1}, nothing matched +inf, and the data
file of the NULL partition was skipped: its rows were silently lost. Dropping
the NULL element is exact only for a partition tuple without NULL.

The pruner now also builds the same tuple key over the table schema's own
types (Nullable for a nullable Delta field) and evaluates a partition tuple
that holds NULL against it, where NULL is an ordinary value of the key's type.
Tuples without NULL keep the existing condition, so their pruning is
unchanged. A Nullable key for every file would be correct too, but KeyCondition
declines an untyped NULL-holding set such as [NULL, 5] (Array(Nullable(UInt8)))
for a Nullable key, so has([NULL, 5], p) would stop pruning anything on tables
without a NULL partition. Accepting such sets for Nullable keys in KeyCondition
would change MergeTree as well, and would hand untyped NULL sets to the Parquet
row-group filter that still mishandles them (ClickHouse#128570, ClickHouse#128575).

Remaining loss: in a multi-column table a NULL-holding tuple is evaluated with
every nullable column Nullable, so an untyped NULL-holding integer set on
another nullable column no longer prunes that file (rows stay correct;
MergeTree with a Nullable partition key behaves the same).

The Iceberg data-file pruner had the same defect and gets the same design in
ClickHouse#130177.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the conflicts in ifNull.cpp, coalesce.cpp and assumeNotNull.cpp:
keep master's [[nodiscard]] on getMonotonicityForRange together with this
PR's check of both bounds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@clickhouse-gh clickhouse-gh Bot left a comment

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.

AI review approves this commit, see the AI Review comment.

@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026

This branch has not been deployed

No deployments
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-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant