Skip to content

Repair an inverted key boundary pair holding a nested NULL - #118945

Merged
alexey-milovidov merged 8 commits into
masterfrom
pk-tuple-nullable-element-bounds-117820
Oct 2, 2026
Merged

alexey-milovidov merged 8 commits into
masterfrom
pk-tuple-nullable-element-bounds-117820

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

A boundary mark of a Tuple key column can hold a NULL inside the tuple (Tuple(Nullable(Float64), Int32) with allow_nullable_key = 1). The key stores NULLs last, while Field order puts Null below every value, so the mark that follows a run of non-NULL rows compared below the mark that precedes it. The granule between the two looked empty, and primary-key analysis dropped it - together with the matching rows it held. SELECT * FROM tn WHERE t >= (5., 3) returned nothing while two rows match, with EXPLAIN indexes = 1 showing Parts: 0/1, Granules: 0/2. A flat Nullable key is exact here: its NULL bound is mapped to +inf, which is where the key stores it.

A nested NULL puts a bound below where the key stores it in Field order. For the lower bound that only widens the range. For the upper bound it does not, even when the pair stays ordered: in Tuple(UInt8, Nullable(UInt8)) the granule (1, 5) .. (2, NULL) holds (2, 3), but Field order puts (2, 3) above (2, NULL). So KeyCondition::checkInHyperrectangle widens an upper bound holding a nested NULL to +inf for Range-based atoms, and never claims that such a granule matches wholly. Sets are compared in the key's own order (IColumn::compareAt with NULLs last), so they keep the exact bounds and pruning is unaffected: 03733_has_function_key_condition_explain keeps its granule count. A flat Nullable column is untouched and keeps its exact +inf mapping.

Where a granule spans the boundary between non-NULL and NULL values, the pair comes out inverted, and the range would look empty before any atom is evaluated. markRangesFromPKRange replaces such a pair with the extremes of its own sides. In the sparse key representation this also clears equal_boundaries_mask for the column. The debug-only exact-continuity check is skipped when an upper bound holds a nested NULL.

Closes: #117820

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 rows silently missing from a query over a table whose primary key is a Tuple with a Nullable element holding NULL: primary-key analysis dropped whole granules of matching rows.


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

Version info

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

A boundary mark of a `Tuple` key column can hold a `NULL` inside the
tuple (`Tuple(Nullable(Float64), Int32)` with `allow_nullable_key = 1`).
The key stores NULLs last, while `Field` order puts `Null` below every
value, so where a granule spans the boundary between non-`NULL` and
`NULL` values the mark that follows compared *below* the mark that
precedes it. The granule looked empty and primary key analysis dropped
it - together with the matching rows it held: `SELECT * FROM tn WHERE
t >= (5., 3)` returned nothing while two rows match, with `EXPLAIN
indexes = 1` reporting `Granules: 0/2`.

Only such an inverted pair is replaced, by the extremes of its own
sides, which claim nothing about that column. A pair that is still
ordered keeps its exact bounds, because for it `Field` order and the
key's order agree on everything the range algebra asks - a table whose
every key value holds a `NULL` in one element keeps its granule count.
A flat `Nullable` column is untouched: its `NULL` bound is already
mapped to `+inf`, which is where the key stores it. In the sparse key
representation the replacement also clears `equal_boundaries_mask` for
the column, because a replaced pair no longer stands for the equal
boundaries the mask reports.
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ab9da1b]

Summary: ✅


AI Review

Summary

This PR fixes the false-negative pruning that happened when a primary-key Tuple boundary carries a nested NULL, by widening unsafe upper bounds in KeyCondition, repairing physically inverted mark pairs before range enumeration, and adding good stateless coverage for loaded, sparse, partition-minmax, and DESC cases. I still see one remaining correctness hole in the same surface: getExtremes()-derived tuple bounds with hidden nested NULLs are still treated as exact for can_be_false, so the exact-range / trivial count() path can over-count rows that comparisons should filter out.

Findings
❌ Blockers
  • [src/Storages/MergeTree/KeyCondition.cpp:6726] The new fieldHasNullInside() widening only covers mark bounds that still carry a real nested NULL. The exactness guard in mayReadNullKeyValue() still recognizes only top-level Nullable key types, so a dropped-suffix / partition-minmax-only Tuple(Nullable(...), ...) bound produced by getExtremes() as (+inf, ...) can still report can_be_false = false for comparison atoms even though every row evaluates to NULL. That feeds exact_ranges / trivial count() optimization and can return an over-count without reading rows.
  • Suggested fix: extend the hidden-NULL exactness check to tuple/minmax bounds as well, analogous to the NaN-hiding tuple handling, and add a count() regression where the tuple key is available only through partition-minmax / dropped-suffix analysis.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: make mayReadNullKeyValue() / its range probe recognize nested NULLs hidden inside tuple bounds from getExtremes(), then add a regression that exercises exact count() on that path.

LLVM Coverage Report

Measured on commit ab9da1b.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 75/83 (90.36%) · Uncovered code

Full report · Diff report

@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. labels Sep 9, 2026
The `t <= (5., 3)` count is answered by the implicit projection, which
claims a granule whose bound holds a NULL nested in the tuple matches
wholly - a separate defect of the range algebra, fixed by the
`KeyCondition` change in #118944, not by the boundary repair here. Turn
the projection off for that one query so the test witnesses only what
this change fixes.
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ab9da1b9e with master d046101ce (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

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

Job report

alexey-milovidov and others added 3 commits September 9, 2026 06:43
The debug-only cross-check after the binary search asserts that a
condition describing one continuous key range analyses every interior
granule as wholly matching. A repaired boundary pair breaks that by
construction: the granule between two marks that `Field` order cannot
compare is analysed as the whole universe, so it may hold rows the
filter rejects. That is the intended outcome - the pair claims nothing
about the column, which can only widen `can_be_true`, and the mark range
the binary search returns stays sound - but the assertion has no way to
know, and the AST fuzzer found it on a `Tuple(Nullable(...))` key.

Only the exactness of the analysis is affected. A release build already
drops the exact range in the same situation, and the exact range is
dropped here too; the check is simply skipped for a part whose
boundaries had to be replaced.
…d `NULL`

The review asked whether the partition-minmax bound of the same key column can arrive at
`KeyCondition` inverted as `[non-NULL, nested-NULL]` the way a per-mark pair can. It cannot:
`ColumnTuple::getExtremes` takes each element's extremes with the NULLs filtered out (all-NULL
gives `+inf`), so the bound is ordered and contains every value without a NULL - it prunes
nothing a comparison matches. The test now pins that for a key column that also feeds the
partition key, both when the column is loaded in the in-memory index and when it is a dropped
suffix column whose partition-minmax bound is the only information the analysis has.

The test is also renumbered: master gained other `05162_` tests meanwhile.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@groeneai groeneai mentioned this pull request Sep 19, 2026
1 task done
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118945&sha=3ce4d8c45c7d9d989edb21cb26cfcb3f00d943bf&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29 (GroupingAggregatedTransform pushed bucket A twice, STID 3994-4c1d, tracked in #115986) and provide a fix in a separate PR. If the fix is already in progress, link it here. The other red, Build profile diff, was a CI logs cluster query error. Master has been merged at a59683b.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. Same root cause as #119814 (yours, open), so there is no new PR from me.

The abort on 3ce4d8c4 is query ab537d5d-2c2c-449b-b127-a81dd54b691b (2026-09-17 11:14:02), log_comment = 04878_distributed_plan_shuffle_bucket_order_promise.sql-test_5, query 26 at line 82:

SELECT k, sum(v) FROM remote('127.0.0.{2,3}', currentDatabase(), t_shuffle_bucket_order) GROUP BY k FORMAT Null
    SETTINGS distributed_plan_force_shuffle_aggregation = 1;

Its recorded settings carry enable_cascades_optimizer = 1 (the stress runner turns it on) next to the test's own make_distributed_plan = 1, distributed_plan_execute_locally = 1, distributed_plan_default_shuffle_join_bucket_count = 2, and distributed_aggregation_memory_efficient = 1, enable_memory_bound_merging_of_aggregation_results = 1, group_by_two_level_threshold = 10000, prefer_localhost_replica = 0. The shard ran as a single stream at distributed_depth = 1 (SELECT __table1.k, sum(__table1.v) FROM test_5.t_shuffle_bucket_order GROUP BY __table1.k), and the frames are the familiar set: pushData at MergingAggregatedMemoryEfficientTransform.cpp:63 under tryPushTwoLevelData() (:95, :123) from prepare() (:237), on bucket 5.

That is what #119814 fixes, and its test change lands on this exact file: it adds SET enable_cascades_optimizer = 0 to 04878 and pins the Cascades plans in the new 05210 instead.

Fix-presence check on the failing head: #119814's tip 5cbdfc36 is not an ancestor of 3ce4d8c4 (diverged, merge base 718e603a), so this run was expected to red. The signature is still live (CIDB, last 14 days: 18 master hits and 151 hits across 137 PRs, most recent 2026-09-24 05:58Z), so a59683b7 can red the same way until #119814 lands.

alexey-milovidov and others added 2 commits October 2, 2026 13:14
Address review: a boundary pair that stays ordered in `Field` order can still
exclude rows the key stores inside the granule. For `Tuple(UInt8, Nullable(UInt8))`
the granule `(1, 5)` .. `(2, NULL)` holds `(2, 3)`, but in `Field` order
`(2, 3)` is above `(2, NULL)`, so `t = (2, 3)` pruned the granule.

A nested `NULL` is stored above every value of its element, while `Field`
order puts it below them, so only the upper bound in value space comes out
too low; a lower bound holding such a `NULL` only widens the range.
`KeyCondition::checkInHyperrectangle` now widens such an upper bound to `+inf`
for `Range`-based atoms and never claims the granule matches wholly. Sets are
compared in the key's own order (`IColumn::compareAt` with NULLs last), so they
keep the exact bounds and `03733_has_function_key_condition_explain` keeps its
granule count. The inverted-pair replacement in `markRangesFromPKRange` stays
for a granule whose range would otherwise look empty before any comparison, and
the debug continuity check is skipped whenever an upper bound holds a nested
`NULL`.

The test covers a `NULL` in a later tuple element and a descending key column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// rows the key stores under it: `(2, 3)` is above `(2, NULL)`. The upper bound is widened to
/// `+inf`, which claims nothing about the column. A lower bound holding such a NULL only
/// comes out lower and needs no widening.
const bool upper_bound_widened = fieldHasNullInside(key_range_ptr->right);

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 fixes the false-negative pruning path for mark bounds, but the exact-range side is still blind to nested NULLs that arrive through a getExtremes()-derived tuple bound.

mayReadNullKeyValue() still decides solely from isNullableOrLowCardinalityNullable(key_type), so a sparse / partition-minmax-only key Tuple(Nullable(Float64), Int32) can still be analyzed through a bound like [(+inf, 2), (+inf, 5)] when the first element is all NULL (ColumnNullable::getExtremes() does exactly that). On a count() query, a predicate such as t >= (0., 0) can then still come back with can_be_false = false even though every row actually evaluates to NULL and must be filtered out.

That flows into exact_ranges / trivial count optimization, so we can still over-count without reading rows. Please extend the hidden-NULL exactness guard to tuple/minmax bounds too, and add a regression for the dropped-suffix / partition-minmax path.

@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.

Acceptable.

@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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants