Skip to content

Fix wrong count() over a Tuple primary key that holds a NaN - #118683

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-exact-count-nan-in-tuple-key-117819
Sep 19, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-exact-count-nan-in-tuple-key-117819

Conversation

@groeneai

@groeneai groeneai commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #117819
Related: #107074
Related: #116763

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 SELECT count() returning more rows than the filter accepts when a MergeTree primary key is a Tuple holding a floating point element and the key data contains a nan. For example, with ORDER BY t over t Tuple(Float64, Int32), SELECT count() FROM t WHERE t >= (5., 3) returned 6 while SELECT * FROM t WHERE t >= (5., 3) returned 2 rows. A nan nested in a tuple is not visible in the granule bounds, so primary key analysis reported a granule of non-matching rows as wholly matching and the exact-count optimization counted its rows without evaluating the filter. Closes #117819.

Description

Field::isNaN() is type-tag-gated, so a nan nested in a Tuple granule bound is invisible to the leaf NaN corrections in KeyCondition::checkInHyperrectangle. Field comparison orders a NaN last, so Range::containsRange accepts the all-nan granule as wholly inside [(5., 3), +Inf), can_be_false stays false, and the granule becomes an exact range whose rows _exact_count_projection sums unfiltered.

The bounds cannot answer this. A top-level float NaN is the maximum of the domain, so it always shows in the granule's upper bound, which is why the existing leaf guard is complete for a flat Float64 key. Inside a tuple a NaN orders above only the values sharing its prefix, so it can sit strictly between two bounds that hold none.

This relaxes right-unbounded FUNCTION_IN_RANGE atoms over such a key column. relaxed only forces can_be_false = true, so can_be_true and every drop decision are unchanged and no row can be dropped; a range bounded above by an ordinary value cannot hold such a row and keeps exact counting (measured). Applied to the three primary-key KeyCondition constructions only: PartitionPruner uses the same overload with strict = true, where relaxing would disable partition pruning. Array and Map keys are unaffected: their equal-type comparison uses compareAt, the same NaN-last order the index uses. Cost, as for any relaxed atom: index-only counting is given up, and index analysis makes more checks because a matching range is no longer accepted whole (44 to 434 on 1000 granules), with the marks selected unchanged at the default step budget.

Not fixed here, separate and pre-existing: NOT (t >= (5., 3)) drops the nan rows instead, because the negation is folded to less before any atom exists. #107074 blocks that fold; measured, neither change closes that leg alone.


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

…d a NaN

SELECT count() over a MergeTree whose primary key is a packed Tuple containing a
float counts rows the WHERE rejects when the key data holds a nan. Issue ClickHouse#117819
returns 6 where the same predicate selects 2 rows; sum(x) over the same predicate,
and count() with optimize_use_implicit_projections = 0, are both correct.

Field::isNaN() is type-tag-gated (Core/Field.h), so a nan nested in a Tuple granule
bound is invisible to the leaf NaN corrections in KeyCondition::checkInHyperrectangle.
Field comparison orders a NaN last, so Range::containsRange reports an all-nan granule
as wholly inside [(5., 3), +Inf), can_be_false stays false, and markRangesFromPKRange
records the granule as an exact range whose rows _exact_count_projection then counts
without ever evaluating the filter.

Inspecting the bounds cannot fix it. For a top-level float a NaN is the maximum of the
whole domain, so it always appears in the granule's upper bound; that is why the
existing leaf guard is complete for a flat float key. Inside a tuple the order is per
element, so a NaN orders above only the values sharing its prefix and can sit strictly
between two bounds that hold none: with key Tuple(Int32, Float64) and rows
(5,1.0),(5,nan),(6,1.0),(6,2.0) the granule bounds are (5,1.0) and (6,2.0), neither a
NaN, while (5,nan) >= (5,0.0) is false. The rule therefore keys on the key column's
type, not on the endpoint values.

Relax the right-unbounded FUNCTION_IN_RANGE atoms that read such a key column instead.
The relaxed flag only ever forces can_be_false = true, so can_be_true and with it every
pruning decision are bit-for-bit unchanged and no row can be dropped; isRelaxed() then
nulls exact_ranges upstream of the debug consistency re-check. Only right-unbounded
ranges need it: a row whose first differing position holds a NaN compares greater than
the constant, so it falls outside any range bounded above by an ordinary value and a
granule that containsRange accepts cannot hold one. Measured, t <= C over the same key
keeps exact counting (read_rows = 1), and t >= C AND t <= D still relaxes because
BoolMask::operator& ORs can_be_false.

Applied to the three primary-key KeyCondition constructions explicitly rather than in
the KeyDescription-taking constructor: PartitionPruner initialises its member from that
same overload and evaluates isRelaxed() with strict = true, so a hook there would
silently disable partition pruning for the virtual-column path.

Array and Map keys are unaffected and deliberately untouched: an equal-type comparison
of those goes through IColumn::compareAt with a nan_direction_hint, the same NaN-last
order the index uses, so their bounds and their rows already agree.
…'s open range

The relaxation is guarded by two independent conditions, and the test as first written
exercised neither in isolation, so either could be dropped without reddening it.

typeCanHideNaNInsideTuple requires both that the unwrapped key type is a Tuple and that
a float is reachable inside it. Only the second condition was covered: both existing
controls read an Int32 key column, so replacing the whole predicate with the inner
floatReachableThroughTupleElements call left the test green while relaxing every v >= C
over an ordinary Float64 key and losing exact counting on the commonest float-key shape.
t_float_key covers it with a flat Float64 key.

Every tuple-key predicate in the test was right-unbounded, so deleting the
isPositiveInfinity() test relaxed every matching atom with the test still green, which
is the narrowness the reasoning above rests on. t_tuple_key_no_nan covers it with an
upper-bounded tuple range.

Both new tables hold no nan by construction. With a nan present the last granule's
bounds fall outside the range and exactness is legitimately lost, which would make the
control pass for the wrong reason. Both read read_rows = 1 before and after the fix:
they detect over-reach, they do not restate the defect.

Also count() over the filtered subquery, the second arm the issue reports, which the
trivial-count rewrite answers from the same exact range.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Reviewed before publication by an independent model plus a cold re-review of the resulting tree
(two rounds; the second returned no findings). Four findings were fixed before publishing: two
missing exactness controls, the issue's second reported arm, one over-long comment. Two are worth
stating here rather than leaving to be re-derived.

A nested NaN in the constant is a separate hole, and this PR does not close it. t <= (6, nan)
and t = (5, nan) still over-count, with no nan in the key data at all: the constant guard
if (const_value.isNaN()) in extractAtomFromTree is leaf-only, so a nan inside a tuple constant
slips past it. This PR keys on the key column's type and never touches atom construction, so it
could not cover that case. #116763 fixes it with a recursive field walk that declines the atom at both
endpoint sites; the two diffs are textually disjoint and compose, since both only ever widen.

One control I chose not to add. Nothing pins the second conjunct of typeCanHideNaNInsideTuple
(a float-free Tuple key such as Tuple(Int32, Int32)) or the Array / Map exclusion, so replacing
the reachability walk with return true would over-relax those shapes with the test still green. The
only consequence is a lost _exact_count_projection, never a wrong result, because relaxed forces
can_be_false = true and leaves can_be_true alone. Say the word and I will add it.

The four in-range controls are each mutation-proved to be the sole detector of one guard: dropping the
top-level Tuple requirement moves only 05136_float_key (1 -> 8 read rows), and deleting the
isPositiveInfinity() restriction moves only 05136_tuple_upper_bound.

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ee30c43]

Summary: ✅


AI Review

Summary

This PR fixes the count() overcount when a MergeTree primary key is a single Tuple column whose data can hide a nan between granule bounds by relaxing lower-bounded range atoms before exact-count optimization. The correctness direction looks right, but the current implementation reuses the global relaxed bit on the ordinary primary-key condition, which weakens primary-key pruning for non-exact reads too.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/KeyCondition.cpp:1615] The new helper fixes an exact-count bug by setting element.relaxed = true, but that bit is consumed globally, not just by exact-count code. markRangesFromPKRange already uses isRelaxed() to drop exact_ranges, which is the correctness fix you need, but GenericExclusionSearch also treats !can_be_false as an exact subrange and stops splitting there. On normal reads over tuple-float keys, any predicate that falls back to generic exclusion search, for example a disjunction with one lower-bounded arm, will therefore read more marks even on NaN-free data, because the lower-bounded arm can no longer prove a subrange exact. Suggested fix: keep the “hidden tuple nan breaks exact-count exactness” state separate from element.relaxed, or gate it only where callers intend to trust can_be_false as “every row matches” (exact_ranges / _exact_count_projection).
Tests
  • ⚠️ Add one focused stateless case that exercises a non-continuous predicate over a tuple-float key, for example an OR that forces GenericExclusionSearch, and asserts the selected or read marks do not regress on NaN-free data. The current test only covers the count() exact-count path, so it would not catch the pruning regression above.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit ee30c43.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 39/41 (95.12%) · 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 8, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @amosbird, could you review this? A nan nested in a Tuple primary key is invisible to the leaf Field::isNaN() guards in KeyCondition, so containsRange accepts an all-nan granule as wholly matching, can_be_false stays false and _exact_count_projection counts rows the WHERE rejects; the fix relaxes only right-unbounded range atoms over such a key column, which drops exact_ranges without touching can_be_true, and leaves PartitionPruner alone since it evaluates isRelaxed() with strict = true.

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

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 060cd58

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
Build (arm_tidy) / Build ClickHouse trunk regression: master 2be1edf87853 left a duplicate #include <DataTypes/DataTypeLowCardinality.h> in src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:36, and readability-duplicate-include is -Werror #118680 (external, open); same one-line fix in #118661
Finish Workflow / new_tests_check.py cascade of the same gate: Bugfix validation reports DROPPED (Dropped due to previous failure [Build (arm_tidy)]) #118680 (external, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260908-013052

if (key_column >= key_types.size() || !typeCanHideNaNInsideTuple(key_types[key_column]))
continue;

if (element.range.right.isPositiveInfinity())

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 _exact_count_projection bug by setting element.relaxed, but that bit is broader than the exact-count contract. markRangesFromPKRange already consults isRelaxed() to drop exact_ranges, which is the correctness fix you need here, but GenericExclusionSearch also treats !can_be_false as “this whole subrange is exact” and stops splitting there.

That means any ordinary read over a tuple-float key that falls back to generic exclusion search, for example a disjunction with one lower-bounded arm, will now prune less even on NaN-free data: the lower-bounded arm can no longer prove a subrange exact, so the search keeps splitting or accepts larger ranges under the step limit. Can we keep the hidden-nan state separate from element.relaxed, or gate it only where callers actually interpret can_be_false as “every row matches” (exact_ranges / _exact_count_projection)?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Citation checked and right: searchUnlimited and searchLimited both read !can_be_false as exact and stop splitting there (GenericExclusionSearch.cpp:83, :144). It costs splitting work, but not pruning. Two binaries from this commit, the control with the three relaxRangeAtomsOverNaNHidingTupleColumns calls removed, NaN-free data, Tuple(Float64, Int32) key, 1000 granules, t >= (3000., 0) OR t = (5., 5), EXPLAIN reporting generic exclusion search:

control this PR
marks selected, default budget 252/1000 252/1000
index checks 44 434
marks read by count() 2 252
marks at merge_tree_generic_exclusion_search_max_steps = 100 252 265

Marks are equal at the default unlimited budget by construction: a range is dropped on can_be_true, which relaxation leaves alone, so splitting an all-matching range converges on the same marks. The extra checks are the cost, and a finite budget between the two step counts is the one place they become reads, which is what that setting trades.

The same numbers appear on the control with none of my change: s LIKE '003%5' over a String key gives 44 to 434 checks and count() 2 to 252 marks, since a non-perfect LIKE prefix sets the same bit.

On separating the state, I would rather not: can_be_false = false here is factually wrong rather than imprecise, since Range::containsRange accepts a granule whose every row fails the filter. relaxed is the one channel that says so to all readers: exact_ranges = nullptr (MergeTreeDataSelectExecutor.cpp:1999), extractPlainRanges bailing out (KeyCondition.cpp:5773, whose comment places that guard to cover "any future atom that introduces relaxation handling"), PartitionPruner in strict mode (PartitionPruner.cpp:20). A bit read only at the exact-count site leaves a known-false can_be_false for every other reader. The search's own use stays sound either way, since accepting a range whole is always a superset.

The cost is now noted in the PR description.

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ee30c438c with master 55c256363 (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, 3178 s compile time in total, 334 of them have a recent master baseline.

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a weird corner case. We can accept the change though.

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit e84ff7b Sep 19, 2026
174 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Sep 20, 2026
Two conflicting hunks, both in `KeyCondition`, and both from master's ClickHouse#118683
("Do not trust an exact primary-key range over a Tuple key that can hold a
NaN"), which added its own NaN relaxation next to this branch's.

The two are complementary and both are kept. `relaxAtomsOverNaNHidingColumns`
weakens the four conditions evaluated against a `getExtremes`-derived
hyperrectangle, and this branch keeps the primary key out of it on purpose,
because that path feeds the exact-range machinery.
`relaxRangeAtomsOverNaNHidingTupleColumns` is exactly that primary-key case,
relaxing only a right-unbounded `FUNCTION_IN_RANGE` over a `Tuple` key so the
exact ranges stay usable everywhere else. Different call sites, no overlap:
this branch's call is on the part-minmax condition inside
`buildPartitionPruningIndexes`, master's three are on the primary-key
condition.

Master's `floatReachableThroughTupleElements` is deleted: it is
`KeyCondition::typeMayHideNaN` spelled a second time, so
`typeCanHideNaNInsideTuple` now calls the member and keeps only the part that
is its own, the requirement that the key column itself be a `Tuple`.

Co-Authored-By: Claude Opus 5 (1M context) <[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-request PR origin: a maintainer pinged or directed groeneai 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