Skip to content

A NULL key value is not a definite match of a negated comparison - #118214

Merged
alexey-milovidov merged 1 commit into
masterfrom
nullable-key-exact-count-112641
Sep 5, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
nullable-key-exact-count-112641

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

SELECT count() answered from the implicit exact-count projection reads a granule's key range instead of its rows. A NULL key value is analysed as the +inf stand-in of the NULLS LAST order, and a comparison against a NULL is NULL - so WHERE rejects the row - which the two-valued range algebra of KeyCondition::checkInHyperrectangle cannot express: "no NULL row lies inside the range" turns, under negation, into "every row lies outside it". A granule of NULLs therefore looked like a definite match of id != '', id NOT IN ('') or id NOT LIKE 'z%', and count() counted rows that SELECT * under the same WHERE does not return - at default settings, on a Nullable primary key:

CREATE TABLE t (id Nullable(String), s Nullable(String)) ENGINE = MergeTree ORDER BY (id, s)
SETTINGS allow_nullable_key = 1;
INSERT INTO t VALUES ('s', 's'), (NULL, 's1'), (NULL, NULL);

SELECT * FROM t WHERE id != '';        -- one row
SELECT count() FROM t WHERE id != '';  -- 3 before, 1 now

The whole analysis now gives up its can_be_false claim as soon as an atom that answers NULL for a NULL argument reads a Nullable key column whose range reaches the NULL stand-in. IS NULL and IS NOT NULL are excluded: they answer true or false for a NULL as well, so the algebra describes them exactly, and the exact count that 04318_sparse_pk_index_analysis_last_mark_null pins keeps working. can_be_true, and with it every pruning decision, is untouched.

Closes: #112641
Related: #112242
Related: #115152

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 to CHANGELOG.md):

Fixed SELECT count() returning too many rows for a negated comparison (!=, NOT IN, NOT LIKE) over a Nullable primary key column: the exact-count optimization counted the NULL-key rows that the WHERE condition rejects.


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

Version info

  • Backported to: 26.8.3.45, 26.7.7.41, 26.6.5.67, 26.3.33.27

`SELECT count()` answered from the implicit exact-count projection reads a
granule's key range instead of its rows. A NULL key value is analysed as the
`+inf` stand-in of the `NULLS LAST` order, and a comparison against a NULL is
NULL - so `WHERE` rejects the row - which the two-valued range algebra of
`KeyCondition::checkInHyperrectangle` cannot express: "no NULL row lies inside
the range" turns, under negation, into "every row lies outside it". A granule
of NULLs therefore looked like a definite match of `id != ''`, `id NOT IN ('')`
or `id NOT LIKE 'z%'`, and `count()` counted rows that `SELECT *` under the same
`WHERE` does not return. At default settings, on a `Nullable` primary key.

The whole analysis now gives up its `can_be_false` claim as soon as an atom
that answers NULL for a NULL argument reads a `Nullable` key column whose range
reaches the NULL stand-in. `IS NULL` and `IS NOT NULL` are excluded: they answer
true or false for a NULL as well, so the algebra describes them exactly, and the
exact count of `04318_sparse_pk_index_analysis_last_mark_null` keeps working.
`can_be_true`, and with it every pruning decision, is untouched.

Closes: #112641

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d9be209]

Summary: ✅


AI Review

Summary

This PR fixes wrong SELECT count() results from _exact_count_projection when a negated comparison is evaluated over a Nullable primary-key range that can include the NULL stand-in. The main idea is correct for ordinary three-valued comparisons, but the new NULL detector is keyed off the coarse RPNElement::Function enum and now disables exact-count exactness for other atom families whose semantics on NULL are already two-valued.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/KeyCondition.cpp:5719] atomIsNullForNullArgument treats every FUNCTION_IN_SET / FUNCTION_NOT_IN_SET and FUNCTION_IN_RANGE atom as NULL-producing on a NULL key, but those enums also back has / notHas, nullIn / notNullIn, and isNotDistinctFrom-derived atoms. Those surfaces are already two-valued on NULL, so a nullable-key range that reaches +inf now forces can_be_false = true and disables _exact_count_projection / exact ranges for queries that remain exact, such as SELECT count() ... WHERE notHas([1], k) on a nullable key or NOT IN under transform_null_in = 1. The fix needs per-atom NULL semantics recorded in RPNElement instead of inferring them from the shared enum.
Final Verdict

⚠️ Changes requested.

LLVM Coverage Report

Measured on commit d9be209.

Metric Baseline Current Δ
Lines 88.80% 88.70% -0.10%
Functions 92.20% 92.20% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 44/45 (97.78%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 5, 2026
{
switch (function)
{
case KeyCondition::RPNElement::FUNCTION_IN_RANGE:

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.

atomIsNullForNullArgument is too coarse here. RPNElement::Function already conflates atom families with different NULL semantics:

  • FUNCTION_IN_SET / FUNCTION_NOT_IN_SET are used not only for ordinary IN / NOT IN, but also for has / notHas and nullIn / notNullIn.
  • FUNCTION_IN_RANGE is also used for isNotDistinctFrom with a non-NULL constant.

Those surfaces are two-valued on NULL, not NULL-producing. We already rely on that elsewhere: 01280_null_in shows nullIn(NULL, ...) / notNullIn(NULL, ...) return a non-NULL boolean, and 04510_not_has_function_explain checks notHas([NULL], x) on a nullable key.

With the current switch, any nullable-key range that reaches the NULL stand-in now forces can_be_false = true even for queries whose semantics stay exact on NULL rows, so _exact_count_projection / exact ranges stop working for cases like SELECT count() FROM ... WHERE notHas([1], k) or ... WHERE k NOT IN (...) SETTINGS transform_null_in = 1.

This needs per-atom NULL behavior recorded in RPNElement (or another way to distinguish these sources) instead of inferring it from the shared enum.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is suboptimal, but still correct.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d9be20967 with master cdc26e3bd (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

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

Job report

@zlareb1

zlareb1 commented Sep 5, 2026

Copy link
Copy Markdown
Member

The wrong count reproduces on the released 26.8 LTS (v26.8.2.7-lts), not just master:

CREATE TABLE t (id Nullable(String), s Nullable(String)) ENGINE = MergeTree ORDER BY (id, s) SETTINGS allow_nullable_key = 1;
INSERT INTO t VALUES ('s','s'), (NULL,'s1'), (NULL,NULL);
SELECT count() FROM t WHERE id != ''; -- 3 on 26.8.2.7, correct answer is 1

so it may be worth a pr-must-backport label — right now the PR carries only pr-bugfix, which is not backported by default.

@alexey-milovidov alexey-milovidov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 5, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 5, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 5, 2026
Merged via the queue into master with commit 4f17421 Sep 5, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the nullable-key-exact-count-112641 branch September 5, 2026 12:59
@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 Sep 5, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 5, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 5, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 5, 2026
Backport #118214 to 26.8: A NULL key value is not a definite match of a negated comparison
robot-ch-test-poll2 added a commit that referenced this pull request Sep 7, 2026
Cherry pick #118214 to 26.3: A NULL key value is not a definite match of a negated comparison
robot-clickhouse added a commit that referenced this pull request Sep 7, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Sep 7, 2026
Cherry pick #118214 to 26.6: A NULL key value is not a definite match of a negated comparison
robot-clickhouse added a commit that referenced this pull request Sep 7, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Sep 7, 2026
Cherry pick #118214 to 26.7: A NULL key value is not a definite match of a negated comparison
robot-clickhouse added a commit that referenced this pull request Sep 7, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 7, 2026
Backport #118214 to 26.6: A NULL key value is not a definite match of a negated comparison
clickhouse-gh Bot added a commit that referenced this pull request Sep 7, 2026
Backport #118214 to 26.7: A NULL key value is not a definite match of a negated comparison
PedroTadim added a commit that referenced this pull request Sep 9, 2026
Backport #118214 to 26.3: A NULL key value is not a definite match of a negated comparison
@groeneai groeneai mentioned this pull request Sep 19, 2026
1 task done
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 19, 2026
…ight PK analysis

With `use_lightweight_primary_key_index_analysis = 1` (the default), a key
column that is neither held by the part's in-memory primary index (it follows
a unique key prefix, see `primary_key_ratio_of_unique_prefix_values_to_skip_suffix_columns`)
nor bounded by the partition minmax is not tracked by the sparse analysis. A set
atom over such a column still evaluates it as `[-inf, +inf]`, so
`b NOT IN (NULL)` / `b NOT IN (<empty subquery>)` / `NOT (b IN ...)` answers
`(true, false)`. The NULL safeguard `mayReadNullKeyValue` (ClickHouse#118214) skipped
every untracked column, so the granule was reported as an exact match and the
exact-count projection counted rows whose `b` is NULL, which `WHERE` rejects:

    CREATE TABLE t (a UInt64, b Nullable(UInt64)) ENGINE = MergeTree ORDER BY (a, b)
    SETTINGS index_granularity = 1, allow_nullable_key = 1;
    INSERT INTO t SELECT number, if(number % 7 = 0, NULL, number) FROM numbers(100);
    SELECT count() FROM t WHERE a >= 10 AND b NOT IN (NULL);  -- 90, must be 77

The non-sparse analysis analyses an unloaded column as the whole universe with
its real type, so its safeguard fires and the result is correct.

The sparse safeguard now checks an untracked key column as the whole universe
with its real type, taken from the full primary key types that the caller
passes down. Range atoms are skipped there: they answer `(true, true)` for an
untracked column, which claims nothing, so e.g. `a >= 10 OR b < 5` keeps its
exact count. Pruning (`can_be_true`) is unchanged.

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

comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... 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 Pull request should be backported intentionally. Use this label with great care! 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Exact-count projection counts NULL key rows: count() WHERE key != '' contradicts SELECT * on a Nullable primary key (default settings)

5 participants