Repository navigation
Fix wrong count() over a Tuple primary key that holds a NaN - #118683
alexey-milovidov merged 3 commits into
Conversation
…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.
|
Reviewed before publication by an independent model plus a cold re-review of the resulting tree A nested NaN in the constant is a separate hole, and this PR does not close it. One control I chose not to add. Nothing pins the second conjunct of The four in-range controls are each mutation-proved to be the sole detector of one guard: dropping the |
|
Workflow [PR], commit [ee30c43] Summary: ✅
AI ReviewSummaryThis PR fixes the Findings
Tests
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit ee30c43.
Changed lines: Changed C/C++ lines covered: 39/41 (95.12%) · Uncovered code |
|
cc @nihalzp @amosbird, could you review this? A |
CI finish ledger - 060cd58Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
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()) |
There was a problem hiding this comment.
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)?
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units334 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. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is a weird corner case. We can accept the change though.
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]>
Closes: #117819
Related: #107074
Related: #116763
Changelog category (leave one):
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 aMergeTreeprimary key is aTupleholding a floating point element and the key data contains anan. For example, withORDER BY tovert Tuple(Float64, Int32),SELECT count() FROM t WHERE t >= (5., 3)returned6whileSELECT * FROM t WHERE t >= (5., 3)returned 2 rows. Anannested 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 anannested in aTuplegranule bound is invisible to the leaf NaN corrections inKeyCondition::checkInHyperrectangle.Fieldcomparison orders a NaN last, soRange::containsRangeaccepts the all-nangranule as wholly inside[(5., 3), +Inf),can_be_falsestays false, and the granule becomes an exact range whose rows_exact_count_projectionsums 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
Float64key. 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_RANGEatoms over such a key column.relaxedonly forcescan_be_false = true, socan_be_trueand 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-keyKeyConditionconstructions only:PartitionPruneruses the same overload withstrict = true, where relaxing would disable partition pruning.ArrayandMapkeys are unaffected: their equal-type comparison usescompareAt, 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 thenanrows instead, because the negation is folded tolessbefore any atom exists. #107074 blocks that fold; measured, neither change closes that leg alone.Workflow [PR]
Sync PR [sync-upstream/pr/118683]