Skip to content

Do not prune a partition when a function of the partition key returns NULL for it - #124041

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-partition-pruning-null-chain-result
Oct 10, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-partition-pruning-null-chain-result

Conversation

@groeneai

@groeneai groeneai commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #110006
Related: #121154

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 partition pruning skipping a partition whose rows match a filter like NOT (c <=> f(partition_key)) when f returns NULL for that partition's key value (for example moduloOrNull or nullIf). Such queries returned fewer rows than with use_partition_pruning = 0.

Description

On 26.8.2.7 a partitioned table returns one row less than the same filter without partition pruning:

CREATE TABLE t (x Int32) ENGINE = MergeTree PARTITION BY x ORDER BY tuple();
INSERT INTO t SELECT number FROM numbers(15);
SELECT count() FROM t WHERE NOT (-5 <=> moduloOrNull(7, x));                                  -- 14, expected 15
SELECT count() FROM t WHERE NOT (-5 <=> moduloOrNull(7, x)) SETTINGS use_partition_pruning = 0; -- 15

26.3.33.24 returns 15; 26.6.2.158, 26.7.6.57, 26.8.2.7 and master return 14. Found by the AST fuzzer on master: https://github.com/ClickHouse/ClickHouse/actions/runs/37295117105/job/111742340948

Root cause. Partition pruning analyzes a single point, so any deterministic key function enters the chain, including one returning NULL for a non-NULL argument. For x = 0, applyMonotonicFunctionsChainToRange turned the point into the range [NULL, NULL]. A real NULL has no position in the Range order, so that range both intersects and is contained in [-5, -5]: the atom was reported always true. This was harmless while every atom was NULL for a NULL argument; isNotDistinctFrom (#110006) is a definite 0 there, so NOT turned "always true" into "always false" and the partition was skipped.

Fix. When a chain function returns NULL for a bound, the range is reported as not analyzable, the rule applyFunctionChainToColumn already applies to the constant side. Only the partition whose value maps to NULL loses pruning. The primary key, minmax and set-index analysis and the Iceberg, Delta Lake and Paimon partition pruners share this function.

Validation. New stateless test: the <=>, IS NOT DISTINCT FROM, nullIf and IS TRUE spellings against an unpartitioned copy, the pruned parts in EXPLAIN, and the fuzzer's TLP identity; red before, green after. #121154 covers the neighbouring case of a bound that already enters the loop as a NULL stand-in.


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

Version info

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

Partition pruning builds its KeyCondition with single_point = true, so
any deterministic function of the key may enter the monotonic chain,
including functions that return NULL for a non-NULL argument
(moduloOrNull, positiveModuloOrNull, nullIf, ...). For such a partition
applyMonotonicFunctionsChainToRange produced a range with a real NULL
bound. A real NULL has no position in the Range order (accurateLess and
accurateEquals are false against it), so both intersectsRange and
containsRange returned true and the atom was reported always true for
the partition.

That was harmless while every range atom was NULL for a NULL argument.
The isNotDistinctFrom atom (ClickHouse#110006) is a definite 0 for NULL <=> c and
is not in inverse_relations, so NOT turned "always true" into "always
false" and the partition was pruned although its rows match:

    CREATE TABLE t (x Int32) ENGINE = MergeTree PARTITION BY x ORDER BY tuple();
    INSERT INTO t SELECT number FROM numbers(15);
    SELECT count() FROM t WHERE NOT (-5 <=> moduloOrNull(7, x)); -- 14, expected 15

Return {} (cannot analyze) when a chain function returns NULL for an
applied bound, the same rule applyFunctionChainToColumn already applies
to the constant side. All callers map {} to an unknown mask, so only the
partition whose value maps to NULL loses its analysis.

Found by the AST fuzzer TLP WHERE oracle on master:
https://github.com/ClickHouse/ClickHouse/actions/runs/37295117105/job/111742340948

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 5, 2026
@groeneai

groeneai commented Oct 5, 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 (2 nits).

# Sev Finding Verdict Evidence / action
1 💡 SET parallel_replicas_local_plan = 1 has no effect next to the no-parallel-replicas tag (test .sql line 6) AGREE noted, not blocking; harmless pin
2 💡 the no-replicated-database tag may be unnecessary for an EXPLAIN filtered to Partition/Parts: lines AGREE noted, not blocking

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-10:20261005-142800

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 5, 2026
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Default settings, clickhouse local over the new test: the partitioned count is 14 instead of 15 on every run (master, 26.6.2.158, 26.7.6.57, 26.8.2.7).
b Root cause explained? Yes. Single-point partition pruning lets a NULL-returning function into the key chain; applyMonotonicFunctionsChainToRange produced the bound NULL, which is incomparable in Range, so the atom was claimed always true; NOT isNotDistinctFrom flipped it to always false and pruned the partition.
c Fix matches root cause? Yes. The un-analyzable bound is rejected where it is produced (return {}, the function's existing "cannot analyze" result), not guarded at a consumer.
d Test intent preserved / new tests added? Yes. New stateless test: four spellings against an unpartitioned copy, EXPLAIN of pruned parts, and the fuzzer's TLP identity.
e Both directions demonstrated? Yes. Fails on the unfixed build and on a mutant with the two checks removed (10/10), passes with the fix; 50/50 randomized runs green.
f Fix is general across code paths? Yes. One producer shared by partition, primary key, minmax and set-index analysis and by the Iceberg, Paimon and DeltaLake pruners; the constant side already had this rule.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. *OrNull and nullIf, a two-function chain, a nested link (IS TRUE), both operand orders; LowCardinality is stripped before the chain; Nullable key values enter as infinity stand-ins, covered by #121154.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or default change; only wrong answers change.
i Invariants and contracts preserved? Yes. A bound returned by the function is a comparable value or an infinity stand-in, never a real NULL; all four callers already map the empty result to "unknown".

Session id: cron:clickhouse-impl-slot-5:20261005-135000

@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [44b8c8e]

Summary: ✅


AI Review

Summary

This PR fixes a real partition-pruning correctness bug in KeyCondition: when a single-point monotonic-function chain produced a real NULL bound for a non-NULL partition key value, range analysis could treat that bound as orderable and prune a matching partition. The change now treats such chain applications as unevaluable and falls back to the safe "unknown" answer, and the added stateless regression covers the reported NOT (<=>) / IS NOT DISTINCT FROM cases plus the fuzzer's TLP identity. I did not find any unresolved correctness, test-evidence, or PR-metadata issues in the current head.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 5, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 44b8c8ea732fadec0166a52ac64188872d5fbf57 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@PedroTadim PedroTadim self-assigned this Oct 8, 2026
# Conflicts:
#	src/Storages/MergeTree/KeyCondition.cpp
@nihalzp nihalzp self-assigned this Oct 8, 2026
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 234db3e

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
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Inconsistent KeyCondition behavior (STID: 5182-4365) not from this PR: the fuzzer query filters on divide(a, nan) IN (5), and divide claims monotonicity for a constant that yields NaN, which aborts the same check on master. This PR only changes the case where a chain function returns a real NULL bound #118720 (external, open)
Stateless tests (arm_asan_ubsan, azure, sequential) job timeout: the job hit its 9000 s limit at test 1158 of 1175 with no failed test. The same job-level timeout hit 19 to 22 pull requests a day, plus master, since 2026-10-05 #123849 (mine, open): splits this job into 2 batches
PR rollup, red only because of the rows above #118720, #123849

All 152 check runs completed, Finish Workflow, Mergeable Check and CH Inc sync are green, and CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261008-210014

@PedroTadim
PedroTadim enabled auto-merge October 9, 2026 15:43
@PedroTadim
PedroTadim added this pull request to the merge queue Oct 10, 2026
Merged via the queue into ClickHouse:master with commit 9416200 Oct 10, 2026
163 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 22, 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-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default 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.

4 participants