Skip to content

Keep NULL rows in index analysis of a decreasing function of a Nullable key - #124111

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/keycondition-decreasing-nullable-key
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/keycondition-decreasing-nullable-key

Conversation

@groeneai

@groeneai groeneai commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118721

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 index analysis of a decreasing function of a Nullable sorting key, such as intDiv(a, -3): granules with NULL rows that the condition matches, for example intDiv(a, -3) IN (NULL) with transform_null_in = 1, were skipped and the query returned too few rows. Granules that hold only NULL values are now skipped for conditions that cannot match NULL.

Description

On 26.8.2.7 a condition that matches NULL rows through a decreasing function of the key loses them:

CREATE TABLE t (a Nullable(Int64)) ENGINE = MergeTree ORDER BY a SETTINGS allow_nullable_key = 1, index_granularity = 2;
INSERT INTO t SELECT if(number >= 9, NULL, number) FROM numbers(14);
SELECT count() FROM t WHERE intDiv(a, -3) IN (NULL) SETTINGS transform_null_in = 1;  -- 0, expected 5

On debug builds intDiv(a, -3) = -2 over a part with NULL keys throws Inconsistent KeyCondition behavior, the AST fuzzer failure on #118721 (STID 5182-4365): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118721&sha=abb18b7a9a575e3b68dcdb2bc9f1f99f8a0f4045&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Root cause. Index analysis stands a NULL key in as +inf, and applyMonotonicFunctionsChainToRange leaves that bound untransformed. For a decreasing step it then called Range::invert, which rewrites a left +inf as -inf: a granule of only NULLs became the whole universe, so the exact-range binary search spanned granules that do not match, and a granule [8, NULL] became [-inf, intDiv(8, -3)] and lost its NULLs.

Fix. For a decreasing step over a Nullable argument, a range of only NULL is kept, and a range of values and NULL becomes the whole universe; matchesExactContinuousRange no longer claims an exact range for such a chain. The same function serves the primary key, IN sets, minmax skip indexes and statistics-based part pruning.

Also fixed. A size-1 set holding NULL over a Nullable key, e.g. a IN (NULL) or intDiv(a, 3) IN (NULL) with transform_null_in = 1, matches the NULL granules while mayReadNullKeyValue keeps them from matching wholly, so it no longer gets an exact range either. Debug builds threw the same error (AST fuzzer on this PR, STID 5182-6d6b: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124111&sha=8c4386b1f9a5ed22725157d4614f5f325ea97708&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29); release counts were correct.

Validation. The new test aborts the unfixed debug build, six lines differ on 26.8.2.7, and each mutation of the fix reddens it.


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

…le key

Index analysis stands a NULL key value in as `+inf`, and
`applyMonotonicFunctionsChainToRange` leaves that bound untransformed,
because every function it accepts maps NULL to NULL. For a decreasing step
it then called `Range::invert`, which rewrites a left `+inf` as `-inf`:

- a granule of only NULLs became the whole universe, so it "may match"
  `intDiv(a, -3) = -2`, and the exact-range binary search spanned granules
  that do not match (debug `Inconsistent KeyCondition behavior`, the AST
  fuzzer failure STID 5182-4365 on ClickHouse#118721);
- a granule `[8, NULL]` became `[-inf, intDiv(8, -3)]` and lost its NULLs,
  so `intDiv(a, -3) IN (NULL) SETTINGS transform_null_in = 1` returned 0
  instead of 5 on every build (26.8.2.7 included).

For a decreasing step over a Nullable argument, a range of only NULL is
now kept, and a range of values and NULL becomes the whole universe.
`matchesExactContinuousRange` no longer claims an exact range for such a
chain, since the whole-universe image of a `[x, NULL]` suffix would trip
the same check; the generic exclusion search still collects exact ranges
per granule. Non-Nullable keys and increasing functions are unchanged.

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 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; 3 findings), plus 2 nits from my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The all-NULL Granules: 0/5 pin can be met by statistics part pruning instead of the primary key DISAGREE Statistics pruning uses the same applyMonotonicFunctionsChainToRange (the pin reads 5/5 with the NULL point reverted); the matchesExactContinuousRange change is exercised every run by t_mixed (= 0 aborts without it).
2 ⚠️ The IN, minmax skip index and statistics lines check results only DISAGREE Each line is red on 26.8.2.7 or under a mutation (IN (NULL) 0 vs 5, skip index 10 vs 11, statistics 0 vs 11); pruning is pinned by the two EXPLAIN lines.
3 ⚠️ No LowCardinality(Nullable) key in the test DISAGREE The chain runs on the LowCardinality-stripped type (KeyCondition.cpp:6232); measured by hand: 5 = 5 and 3 = 3 (unfixed: 0 vs 5, then the abort).
4 💡 The NULL predicate repeats rangeOfKeyColumnMayHoldNull noted Two sites with different signatures; not changed.
5 💡 Only intDiv and divide by a negative constant are tested noted The change keys on the step direction, not on the function.

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

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

@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. intDiv(a, -3) = -2 on a part of only NULL keys aborts every unfixed debug run at MergeTreeDataSelectExecutor.cpp:2782; intDiv(a, -3) IN (NULL) with transform_null_in = 1 returns 0 instead of 5 on 26.8.2.7.
b Root cause explained? A NULL key is analysed as +inf and left untransformed; for a decreasing step Range::invert rewrote it as -inf, so a NULL-only granule became the whole universe and a [x, NULL] granule lost its NULLs.
c Fix matches root cause? Yes. A decreasing step keeps a NULL-only range and maps values plus NULL to the whole universe; matchesExactContinuousRange no longer claims exactness there. No guard at the throw site.
d Test intent preserved / new tests added? New SQL test, 26 checks: the CI shape, IN sets, DESC key, minmax skip index, statistics part pruning, two EXPLAIN granule counts.
e Both directions demonstrated? Unfixed debug aborts; 26.8.2.7 differs on 6 lines; fixed build passes 50/50 randomized runs; four mutations each redden it.
f Fix is general across code paths? One helper serves the primary key, MergeTreeSetIndex, minmax skip indexes and statistics pruning, each measured.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable Int64/Decimal/Float64/UInt32, LowCardinality(Nullable), intDiv/divide, two chained decreasing steps, DESC key.
h Backward compatible? (maintainer-approved exception only) Yes. Only decreasing steps over Nullable arguments change; ~360 related tests match the base build.
i Invariants and contracts preserved? A step's range contains the image of every input value, NULL included; a chain is exact only when that image is one interval.

Session id: cron:clickhouse-impl-slot-7:20261005-212800

@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d1bf761]

Summary: ✅


AI Review

Summary

This PR fixes incorrect pruning for decreasing monotonic wrappers over Nullable keys and adds focused stateless coverage for the reported wrong-result and debug-only exact-range failures. The main correctness change in applyMonotonicFunctionsChainToRange looks sound, but the new matchesExactContinuousRange guard is too coarse: it also disables the primary-key binary-search fast path for cases that are still one continuous interval, so I think this needs one more iteration.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/KeyCondition.cpp:6678] matchesExactContinuousRange now returns false for any decreasing step whose argument type is nullable. That is broader than the actual bad case: for predicates such as intDiv(a, -3) = -2, the only imprecise mark is the trailing mixed [x, NULL] granule, and MergeTreeDataSelectExecutor already strips inexact first/last granules before keeping exact_ranges (src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp:2767). Falling back to generic exclusion search here turns what used to be an O(log N) binary search over marks into the heavier step-limited search on every part, which is a real regression for large parts.
    Suggested fix: keep the new applyMonotonicFunctionsChainToRange handling, but avoid the blanket nullable-type rejection in matchesExactContinuousRange; rely on the existing boundary-granule stripping for the single mixed suffix granule, or make the guard conditional on actually having an inexact interior range.
Final Verdict

⚠️ Needs changes before merge: the correctness fix is good, but the new exact-range guard regresses primary-key search performance more broadly than necessary.

@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 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

groeneai and others added 2 commits October 6, 2026 01:58
…e key

A size-1 set holding NULL, e.g. `intDiv(a, 3) IN (NULL) SETTINGS
transform_null_in = 1` or `a IN (NULL)`, matches the NULL granules of a
Nullable key, while `mayReadNullKeyValue` keeps them from matching wholly.
`matchesExactContinuousRange` still reported an exact continuous range, so
the binary search spanned NULL granules and the debug check threw
`Inconsistent KeyCondition behavior` (AST fuzzer, STID 5182-6d6b). Release
builds drop the exact range and return the correct count.

Such a set now falls back to the generic exclusion search, which still
collects exact ranges per granule. Sets without a NULL element are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on-decreasing-nullable-key

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

const auto monotonicity = func->getMonotonicityForRange(*arg_type, field, field);
/// A decreasing step maps a range holding NULL to more than one interval.
if (!monotonicity.is_positive && isNullableOrLowCardinalityNullable(arg_type))

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 is broader than the actual bad case. After the change in applyMonotonicFunctionsChainToRange, a decreasing wrapper over a Nullable key only becomes inexact on the trailing mixed [x, NULL] granule; MergeTreeDataSelectExecutor already knows how to strip an inexact first/last granule from exact_ranges before keeping the binary-search result (MergeTreeDataSelectExecutor.cpp:2767-2774).

Returning false here for every decreasing step on a nullable type means predicates such as intDiv(a, -3) = -2 now always fall back to generic exclusion search on every part, even though they are still one continuous mark interval with at most one inexact boundary granule. On large parts that is a noticeable regression from the O(log N) binary-search path.

Can we keep the new range transformation but avoid the blanket Nullable-type rejection here, or at least make it depend on an actually inexact interior range rather than on the column type alone?

@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... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants