Skip to content

Do not treat a key range as exact when the constant reaches the key transform as a NaN - #117501

Merged
nihalzp merged 7 commits into
ClickHouse:masterfrom
groeneai:keycondition-nan-normalized-constant
Sep 8, 2026
Merged

nihalzp merged 7 commits into
ClickHouse:masterfrom
groeneai:keycondition-nan-normalized-constant

Conversation

@groeneai

@groeneai groeneai commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator

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 wrong results for a comparison between a floating point column and a string constant such as 'nan' when the sorting key, partition key or a minmax skip index applies an injective transform to that column, for example ORDER BY toString(f). Index analysis converted the constant to the column's type, producing a NaN, mapped it through the transform, and then treated the resulting range as exact, so f != 'nan' skipped the granule holding the NaN row and count() for f = 'nan' could be answered from a projection as a match.

Description

Related: #106262

#116763 fixes a constant that already holds a NaN; this hole was found reviewing it.

KeyCondition guards NaN constants before key analysis and again after the transform, and the constant
is the String 'nan' at both. The NaN exists only in between, created in
canConstantBeWrappedByDeterministicFunctions when the constant is converted to the type the key
expression consumes, then erased again by toString.

The atom is then built as toString(f) != 'nan', an exact point exclusion in String space, so the
granule holding the NaN row is dropped: the comparison reads the constant in the column's domain, where
a NaN equals nothing, while the index compares key values in a total order where 'nan' = 'nan'.

CREATE TABLE q (f Float64) ENGINE = MergeTree ORDER BY toString(f) SETTINGS index_granularity = 1;
INSERT INTO q VALUES (nan), (2);
SELECT count() FROM q WHERE f != 'nan';                              -- 1, wrong
SELECT count() FROM q WHERE f != 'nan' SETTINGS use_primary_key = 0; -- 2, correct

Index analysis now converts the constant, checks the converted value, then applies the transform, so
the atom is kept but marked relaxed. notEquals is in no_relaxed_atom_functions, but
that list guards only the monotonic-chain branch, which widens the range; here the range is unchanged
and relaxed only forces can_be_false before the inversion, so the atom stops pruning rather than
pruning more. The deep-NaN walk lives in Field as anyFieldSatisfies, shared with
MergeTreeData's containsOrderInconsistentValue.

Not done: f IN ('nan', 7) also loses the NaN row, but it reproduces with ORDER BY tuple(), a
different layer, and is issue #116927, closed by #117453. A signed zero (#115970) and a nested NULL
in a tuple constant break the same assumption and need different remedies. #116763 and #117453 each
copy that walk and should adopt the shared one.

Validation

The new test reads 2 2 2 2 0 1 0 1 2 2 1 0 2 2 with this change and 1 2 1 2 1 1 1 1 1 2 1 1 1 2
on a pristine master binary built from the same tree, so seven of its rows are wrong without it.

31 further probes: the 13 that were wrong are now correct (Float32, BFloat16,
LowCardinality(Float64), a tuple key, toFixedString, PARTITION BY, a minmax index,
NOT (f = ...), the 'NaN'/'-nan' spellings), and the 18 that must not change do not, including a
non-NaN 'inf' constant, a Nullable key, a Decimal column and the IN/NOT IN set path.

Pruning with auto_statistics_types = '', so the PrimaryKey block is the only pruner:

probe before after
f != 'nan' Granules: 1/2, dropping a matching row 2/2
f = 'nan' Granules: 2/2 2/2, unchanged
f = '2', an ordinary point lookup Granules: 1/2 1/2, unchanged

f = 'nan' never had primary key pruning to lose: with no final mark the first granule's range runs
inclusively up to the next mark, so the point range intersects both granules either way.

Mutation arms each redden a different row set: dropping the new conjunct fails this test and leaves
04950_minmax_count_projection_unusable_bound green, while making the shared walk shallow fails only
the tuple case here and three rows of 04950, so both call sites reach the container walk.
One arm per consumer is pinned: the partition pruner, a minmax skip index forced with
force_data_skipping_indices, and a plan assertion that the exact-count projection is not chosen.

50 of 50 randomized runs of the new test pass. A 301-test sweep over
keycondition|key_condition|nan|minmax|partition_prun|primary_key shows 258 passes and no regression:
the same 34 fail on the pristine binary under the same configuration, all
from the sandbox lacking the stateful dataset, a cluster, ZooKeeper or external lake data.


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

Version info

  • Merged into: 26.9.1.975 (included in 26.9 and later)

groeneai and others added 3 commits September 1, 2026 05:17
…ransform as a NaN

`KeyCondition` checks a constant for a NaN at two points, and for a predicate
such as `f != 'nan'` over `ORDER BY toString(f)` the constant is the `String`
`'nan'` at both of them: once in `extractAtomFromTree` before any key analysis,
and once in `canConstantBeWrappedByDeterministicFunctions` after the key
transform has been applied.

The NaN exists only between those two points.
`applyDeterministicDagToColumn` adapts the constant to the type the key
expression consumes, and `accurateCast(String 'nan' -> Float64)` produces a
NaN; the DAG then applies `toString`, which turns it back into `'nan'`, so it
is gone again before the second check runs.

The atom is therefore built as `toString(f) != 'nan'`, an exact point exclusion
in `String` space, and it is treated as exact because `toString` is injective.
The row holding the NaN has key value `'nan'`, so the atom is false for it and
its granule is dropped, while the predicate is true for that row: the
comparison reads the constant in the column's own domain, where a NaN is equal
to no value, not even itself, whereas the index compares key values under a
total order in which `'nan' = 'nan'`. The atom is stricter than the predicate,
so a matching row is silently lost from primary key analysis, partition
pruning, and `minmax` skip indexes.

The same exactness also let `count()` for `f = 'nan'` be answered from the
implicit minmax-count projection instead of from the filter, reporting the
granule as a match, on tables where the `basic` automatic statistics are not
present to drop the part first.

`applyDeterministicDagToColumn` now reports whether the value it actually
handed to the DAG held a NaN, taken at the single point where that value is
final, and the caller folds it into the exactness it already reports. The atom
is kept and marked `relaxed`, which is the flag the tree already designates for
a condition that can be stricter than the predicate, so pruning is not given
up: an ordinary point lookup on the same key still reads one granule of two,
which declining the atom would have cost.

The nested-value walk is iterative, like the existing
`containsOrderInconsistentValue`, because `Field::isNaN` recognizes a scalar
`Float64` only and a `Field` can nest inside a `Field` without bound.

The set-index caller passes nothing, so set analysis is unchanged: a negative
answer there abandons the whole set analysis with no fallback, and the `IN`
rewrite is sound for a NaN because set membership already uses the same
equality the total order uses.

Related: ClickHouse#106262

Co-Authored-By: Claude Opus 5 <[email protected]>
Covers the scalar case and the case where the NaN sits below the top level of
the constant, so the nested-value walk is required, plus an assertion that an
ordinary point lookup on the same key still reaches only its own granule.

The table pins `auto_statistics_types = ''` so that no second pruner runs and
the granule counts are attributable to key analysis alone.

Co-Authored-By: Claude Opus 5 <[email protected]>
Refinement of the two commits above, from review.

`applyDeterministicDagToColumn` writes `out_transform_input_has_nan` as its first
statement rather than just before the DAG runs, so every return path leaves a
defined value. Behaviour is preserved: the only caller that passes the pointer
already initialized its local to `false`, and the two returns that precede the old
write site are the direct-CAST fast path's success and the failure of
`cast_without_nulls`, both of which previously left that `false` in place. That
fast path is sound on its own account, because it builds the atom through
`FunctionCast` (`FunctionsConversion.h:4963`), which does not override
`isInjective` and so inherits the `false` of `IFunctionBase` (`IFunction.h:263`),
so the atom is never marked exact there to begin with.

The walk is named `fieldContainsNaNAnywhere` and not `fieldContainsNaN` because
two other open pull requests add a same-shaped walk to this file, and this one is
a different implementation: iterative, and it also descends into `Map` and
`Object`.

The test pins `auto_statistics_types = ''` so that the granule counts it asserts
are attributable to key analysis and not to the `basic` statistics pruner, pins
the projection settings on the row that the implicit minmax-count projection would
otherwise answer, and asserts that the key condition is still present in the plan.
That last row is what separates keeping the atom and marking it inexact from
declining it, since declining leaves no key condition at all.

A signed zero reaches the same site with the same shape (`-0` and `0` are equal
under the column's comparison while `toString` separates them), but it is not
covered here: marking the atom inexact widens `can_be_false` only, which repairs
the `!=` direction and leaves `f = '-0'` still dropping a matching granule, and
the direct-CAST fast path is a second entry point that reports nothing. That class
needs a decline or a synthesized range and is tracked separately.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Three review rounds before publication: an independent cold review plus a second model, each held
against the frozen description. Findings and what happened to each:

❌ The new doc comment gave a false reason for leaving the NaN report unset on the direct-CAST
fast path. That path does adapt the input and the cast can produce a NaN; the outcome is safe for two
other reasons, since a bare CAST is never reported injective and a NaN output is declined separately.
The comment now states the parameter's contract only, and the reasoning is in the commit message.

❌ Signed zero was raised as the same defect one value class further out, and the widened guard was
implemented before being reverted on measurement. -0 and +0 are equal under floating point
comparison while toString maps them to '-0' and '0', so f = '-0' over ORDER BY toString(f)
prunes the granule holding +0, whose row matches. Marking the atom inexact does not repair that:
relaxed forces can_be_false, which reaches notEquals through the range inversion but never
equals, whose can_be_true is the intersection test. Measured on four binaries, f != '-0' is
repaired and f = '-0' still returns 1 against a truth of 2, so the half fix would have claimed a
class it does not close. It needs a decline or a synthesized range, which is a different mechanism;
this PR claims the NaN case only, and #115970 owns the negative zero class.

⚠️ The test could not distinguish a retained-and-relaxed atom from a declined one, and one of its
live assertions was blind in the 5% of runs where the implicit-projection settings are randomized off.
Both settings are now pinned at query level, and one assertion checks that the atom is still present in
the plan; a mutant that declines the atom instead of relaxing it reddens exactly that row and nothing
else. A granule count cannot discriminate here: with auto_statistics_types = '' the NaN equality atom
reads 2 granules of 2 either way.

💡 The nested-value walk repeats containsOrderInconsistentValue in MergeTreeData.cpp. Not
deduplicated here: the shared home is src/Core/Field.h, which would pull an unrelated file and a
full-tree rebuild into a bug fix, and #116763 and #117453 each add their own copy to this file, so
consolidating belongs after they land. Disclosed in the description instead.

💡 Two further observations were checked and deliberately not changed: the tuple table does not pin
auto_statistics_types (measured not to matter, since the inequality defect is not masked by the
statistics pruner and extra pruning could only fail the test, not pass it), and the NaN report is
written on entry so its contract does not depend on the caller's initializer.

💡 One assertion the plan proposed was dropped as unsound before it shipped: the granule count for
f = 'nan' was attributed to key analysis when it came from the automatic basic statistics pruner.
With statistics off that shape reads 2 granules of 2 on both binaries, so it never had primary key
pruning to lose, and the preservation assertion is an ordinary point lookup instead.

Session id: cron:clickhouse-review-self-slot-58:20260901-102400

@clickhouse-gh clickhouse-gh Bot closed this Sep 1, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a638b36]

Summary: ✅


AI Review

Summary

This PR fixes the NaN-during-normalization carrier correctly and the Field helper refactor looks sound, but the refactored exactness gate is still incomplete for transformed tuple constants with nested NULL. Because that leaves a wrong-results path on the same modified line, I would keep Changes requested.

Findings

❌ Blockers

  • [src/Storages/MergeTree/KeyCondition.cpp:2528] [dismissed by author -- https://github.com/Do not treat a key range as exact when the constant reaches the key transform as a NaN #117501#discussion_r3951609522] out_atom_is_exact is still keyed only by transform_input_has_nan, so ORDER BY toString(k) with a tuple constant such as '(NULL, 1)' is still treated as an exact one-point range even though tuple-vs-string equals / notEquals over nested Nullable elements can return NULL, not a two-valued equality result. That means PK / partition / minmax pruning and _exact_count_projection can still answer from key space for a predicate that is stricter than the real filter. The author argues this is pre-existing, but this PR now owns the exactness gate at the precise line where that carrier should be cleared.
    Suggested fix: derive exactness from comparison semantics, not just NaN in the transformed input. For tuple-vs-string constants whose equals / notEquals path can yield Nullable(UInt8), clear exactness (or decline the atom) while keeping isNotDistinctFrom exact, and add a focused regression test on ORDER BY toString(k).
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit a638b36.

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: 109/118 (92.37%) · 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 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand, no randomization: CREATE TABLE q (f Float64) ENGINE = MergeTree ORDER BY toString(f) SETTINGS index_granularity = 1; INSERT INTO q VALUES (nan), (2); SELECT count() FROM q WHERE f != 'nan'; returns 1 against a truth of 2. Both analyzers.
b Root cause explained? The NaN guards run before key analysis and after the transform, and the constant is the String 'nan' at both. accurateCast(String 'nan' -> Float64) inside applyDeterministicDagToColumn creates the NaN, toString erases it, so neither guard observes it. The atom is built as toString(f) != 'nan', an exact point exclusion, and is treated as exact because toString is injective. The row holding NaN has key value 'nan', so its granule is dropped while the predicate is true for it.
c Fix matches root cause? Yes. The exactness flag is now computed from the value the DAG actually consumed, at the single point where that value is final, so the guard tests the domain the comparison reads rather than the domain the index compares. Not a widened bound, not a test tag, not a guard at the symptom site: the atom is still built and still prunes wherever it soundly can, which is what relaxed exists to express.
d Test intent preserved / new tests added? New 05055_key_condition_nan_normalized_constant: three scenarios plus two preservation assertions, 7 asserted rows. Four mutation arms each redden it, and each reddens a different set of rows: dropping the exactness conjunct (rows 1, 3, 5); making the nested-value walk shallow (row 3 only, which is what proves the container walk is reached and the tuple scenario is not redundant); moving the probe before the type conversion (rows 1, 3, 5); declining the atom instead of relaxing it (row 6 only, which is what makes row 6 discriminate the chosen mechanism from the rejected one). No existing test weakened or removed; the sibling guard's own 04306_keycondition_nan_equality still passes.
e Both directions demonstrated? Yes, on two Build-ID-asserted debug binaries, same query file, reference 2 2 2 2 0 1 1: pristine master gives 1 2 1 2 1 1 1, the fix gives 2 2 2 2 0 1 1. The base binary's source was asserted byte-identical to the base commit, and those two files are the only src/ files the diff touches. Also OK through the test runner, and 50 of 50 under randomized settings with the server's buildId asserted equal to the binary's Build ID, randomization proven live from system.query_log (51 distinct max_block_size, 4 max_threads, 7 session_timezone over 51 runs).
f Fix is general across code paths? The report is emitted where the value handed to the transform is final, so every consumer of that RPN inherits it: measured on primary key analysis, PARTITION BY, a minmax skip index, NOT over the atom, and the implicit projection / exact count path. The IN set caller deliberately passes nothing: a false there abandons set analysis with no fallback, and the set rewrite is sound for a NaN anyway (measured unchanged). The NaN class is complete: 13 carriers measured fixed, and the container walk covers the complete set of nesting Field types (Array, Tuple, Map, Object). A signed zero reaches the same site with the same shape but is a different class with a different remedy: marking the atom inexact widens can_be_false only, which repairs f != '-0' and leaves f = '-0' still dropping a matching granule, and the direct-CAST fast path is a second entry point that reports nothing. It needs a decline or a synthesized range, is out of this changelog's claim, and is tracked separately.
g Fix generalizes across inputs (params/datatypes/wrappers)? Of 31 probes, 13 were wrong and are now correct: Float32, Float64, BFloat16, LowCardinality(Float64), Tuple(Float64, Float64) with a String element and with a bare NaN element, PARTITION BY toString(f), INDEX ... toString(f) TYPE minmax, ORDER BY (toString(f), g), toFixedString, NOT (f = ...), and the 'NaN' and '-nan' spellings. The other 18 must not change and do not, including the non-NaN 'inf' control, Nullable(Float64), Decimal64, Map(String, Float64), reinterpretAsUInt64, concat, the direct CAST fast path, the identity key, < and >=, and IN/NOT IN. Two further controls confirm the guard does not reach paths whose equality already is identity: an Int64 key under toString and an identity float key both keep their pruning and their exact-count path, byte-identically to master, with a same-channel sensitivity control (f != 'nan' moving 1/2 to 2/2) so those controls are not vacuous.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added, no default changed, no serialization or on-disk format change, no public API change, so nothing for SettingsChangesHistory.cpp (grep of the diff for Settings: zero hits). The only behaviour change is that a range derived from such a constant stops being trusted as exact, which can only widen what is read, never narrow it.
i Invariants and contracts preserved? chassert(!out_value.isNaN()) still asserts the raw constant, a different and still true claim from the adapted one. The new out-param is optional and written as the function's first statement, so it is always defined on every return path; the write-on-entry is behaviour-preserving because the only caller that passes the pointer already initialized its local to false, and the only two returns that precede the old write site left that false in place. The set caller passes nothing, so that path is unchanged. The probe loop is total: the column has been through convertToFullIfWrapped()->convertToFullColumnIfLowCardinality(), the cast may re-apply a LowCardinality or Nullable target, operator[] is defined for both, and a Null field is not a NaN; confirmed by the measured LowCardinality, Nullable and Map arms rather than by reading. The nested-value walk is iterative, so no stack depth contract is at risk. No lock, no new error path, one Field read per constant.

Session id: cron:clickhouse-impl-self-slot-57:20260901-083600

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tiandiwonder @al13n321, could you review this? The NaN exists only between KeyCondition's two NaN guards, while the string constant 'nan' is normalized to the type the key expression consumes, so the range built from it was treated as exact and f != 'nan' over ORDER BY toString(f) pruned the granule holding the NaN row.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a638b3622 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

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

Translation unit Master PR Δ vs median
src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp 23.9 s 32.4 s +9.0 s (+38%)

Slowest changed entities of src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp:

  • InstantiateFunction std::__variant_detail::__move_assignment<std::__variant_detail::__traits<DB::SortingQueueImpl<DB::S…: +0.7 s
  • InstantiateFunction std::__variant_detail::__assignment<std::__variant_detail::__traits<DB::SortingQueueImpl<DB::Specia…: +0.7 s
  • InstantiateFunction std::__variant_detail::__visitation::__base::__visit_alt_at<(lambda at /ClickHouse/contrib/llvm-pro…: +0.7 s
  • InstantiateFunction std::__variant_detail::__visitation::__base::__make_fdiagonal<(lambda at /ClickHouse/contrib/llvm-p…: +0.7 s
  • InstantiateFunction std::__variant_detail::__visitation::__base::__make_fdiagonal_impl<(lambda at /ClickHouse/contrib/l…: +0.7 s
  • InstantiateFunction std::__variant_detail::__move_assignment<std::__variant_detail::__traits<DB::SortingQueueImpl<DB::S…: -0.7 s (-100%)
  • InstantiateFunction std::__variant_detail::__assignment<std::__variant_detail::__traits<DB::SortingQueueImpl<DB::Specia…: -0.7 s (-100%)
  • InstantiateFunction std::__variant_detail::__visitation::__base::__visit_alt_at<(lambda at /ClickHouse/contrib/llvm-pro…: -0.7 s (-100%)

Job report

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 33dba0420192d1e4281e6e5f23bde57514ae93d8

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
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) the shard's nested containers breach the /docker cgroup leaf, the kernel OOM-kills processes inside it and the job errors with no test attributed #117412 (external, merged 2026-09-01T11:31:33Z)
Docs examples / Documentation examples the documented output of Function/toYYYYMM#0 was pinned to 202608, so the example self-broke at the month boundary #117459 (mine, merged 2026-09-01T13:55:50Z)
Bugfix validation (functional tests, amd64 / aarch64), Finish Workflow / Post Hooks both per-arch jobs abort on assert build_urls, "Could not find master builds in S3", so nothing could validate and new_tests_check.py then reds the post hook #117433 (mine, open)

The /docker breach is a job-level condition, not a test result. I measured #117412 ABSENT from the tree that ran, from the job's own environment rather than from git ancestry: this job was launched with CI_DIND_INIT_RESERVE=17179869184 (the 16 GiB share #117412 replaces), and so were all ten failing legs I read this tick. The probe discriminates, with a positive control: two shards launched at 14:53Z and 14:59Z carry CI_DIND_INIT_RESERVE=8589934592 (the flat 8 GiB reserve #117412 introduces) and both passed. So this is rule 3c and not rule 3d, and #117411 is not a co-owner: it was closed unmerged at 11:11:48Z in favour of #117412, whose own diff comment states the causal link.

The docs example is a trunk-wide, date-dependent break, not something specific to this PR: 226 distinct pull requests and 10 true-master runs carry it. I measured #117459 ABSENT from the tree that ran, from the failure text itself: the reported query is still the old toYYYYMM(now(), ...) form, and the string the fix introduces appears in 0 of the 164 Docs examples failure rows recorded in the last day. The control is master's own line - Docs examples is FAIL at d8aa6cab7800, which is 4 commits behind the fix and has 0 occurrences of the new string, and OK at 8627fa22f015, which is the fix's own merge commit.

I have not merged master to pick those fixes up yet. It would not clear Mergeable Check on this head, because the Bugfix validation abort is gating too and its fix is still open, so a merge now would cost a full CI cycle and leave the head red on the same count. One master merge picks everything up once the remaining fixes land.

Mergeable Check reports Failed: 3 at this head, which counts only the jobs it gates on. The table above is the complete non-OK, non-SKIPPED node set of the head's praktika report, so it also covers the rows Mergeable Check does not gate.

CH Inc sync was success at this head.

Session id: cron:our-pr-ci-monitor:20260901-163000

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

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

fieldContainsNaNAnywhere belongs in Field, not in KeyCondition. Field already owns this kind of predicate (isNull, isNaN, isNegativeInfinity, isPositiveInfinity, and isNaNField in Field.h), and walking a Field through Array, Tuple, Map and Object is a property of the data structure, not of key analysis. The same walk is already on master as containsOrderInconsistentValue in MergeTreeData.cpp, line for line, differing only in the predicate, and the description says two more copies are pending in #116763 and #117453 and that "sharing them needs a predicate-taking walk in src/Core/Field.cpp". That is the right diagnosis, so please do it here: a predicate-taking walk next to isNaNField, or a FieldVisitor applied with applyVisitor like every other Field traversal, and express containsOrderInconsistentValue and this check through it. The comment that recursion "overflows the native stack" does not hold: FieldVisitorToString and FieldVisitorHash recurse, and a constant's nesting depth is bounded by the parser depth.

The bool * out_transform_input_has_nan = nullptr side channel on applyDeterministicDagToColumn is the second problem. It defaults to null only so the IN call site does not change, although that path has the same hole. The root cause is that the function does two jobs: converting the constant to the transform's input type, which is where the NaN is born, and applying the transform, so the caller never sees the converted value. Split those steps so canConstantBeWrappedByDeterministicFunctions converts first, checks the one converted Field with the shared predicate, and then applies the DAG. That removes the out-parameter and the loop that turns column rows back into Fields for a one-row constant, and the IN path gets the same check when #117453 lands. The direct-CAST fast path is unaffected because it never produces the intermediate value. The rename from "injective" to "exact" is right and should stay.

…e transform

Both changes are review asks.

`fieldContainsNaNAnywhere` was a private copy of a walk `MergeTreeData.cpp` already had as
`containsOrderInconsistentValue`, differing only in its predicate. Walking `Array`, `Tuple`, `Map` and
`Object` is a property of the value, not of key analysis, so the walk moves to `Field` as
`anyFieldSatisfies(field, predicate)`, next to `isNaNField`, and both call sites go through it: key
analysis passes `isNaNField`, the minmax bound check passes `isNull() || isNaNField()`. Only a
declaration is added to `Field.h`; the body lives in `Field.cpp`, where it keeps the explicit worklist
of its neighbours (`Field::destroyContainerIteratively`, the copy constructor) because a bound read
from a part is not depth-bounded by the parser. The claim that a recursive walk overflows the stack is
gone from the comment.

`applyDeterministicDagToColumn` did two jobs: it converted the constant to the type the transform
consumes, which is where a NaN is born, and then applied the transform, so its caller could not see
the converted value and received it through a `bool *` out-parameter. It is now composed of
`convertColumnForDeterministicDag` and `executeDeterministicDag`, with its two lambdas as
`finalizeTransformedColumn` and `castColumnWithoutNulls`.
`canConstantBeWrappedByDeterministicFunctions` calls the two steps in turn and checks the single
converted `Field` between them, so both the out-parameter and the loop that turned column rows back
into `Field`s for a one-row constant are gone. The `IN` path still calls the composed wrapper, and can
adopt the same check when ClickHouse#117453 lands.

The direct-CAST fast path converts and transforms in one step, so it exposes no intermediate value to
check. Skipping it there costs nothing: `FunctionCast` (`FunctionsConversion.h:4963`) does not override
`isInjective`, so it inherits `false` from `IFunctionBase::isInjective` (`IFunction.h:263`) and an atom
over that path is not exact either way. This is what the removed out-parameter reported.

Behaviour is unchanged. The 31-probe carrier matrix is byte-identical to the published head's, and
05055_key_condition_nan_normalized_constant, 04950_minmax_count_projection_unusable_bound,
02982_minmax_nan_null_order, 00944_minmax_nan, 00944_minmax_null,
01710_minmax_count_projection_count_nullable, 03913_minmax_statistics_nan_ubsan_error,
04306_keycondition_nan_equality and 04401_key_condition_is_not_distinct_from all match their
references.
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Both asks are implemented in 7bab806.

The walk is in Field now. anyFieldSatisfies(field, predicate) is declared next to isNaNField in src/Core/Field.h, with the body in Field.cpp, so the header gains a declaration only. Both call sites go through it: key analysis passes isNaNField, and containsOrderInconsistentValue in MergeTreeData.cpp passes isNull() || isNaNField() and collapses to one line. I kept the explicit worklist instead of recursion, because that is what Field's own container walks a few hundred lines up do (Field::destroyContainerIteratively at Field.cpp:138, and the copy constructor's pending list at :59), and one of the two callers checks a minmax bound read from a part, whose depth is not bounded by the parser. The comment claiming a recursive walk overflows the stack is gone, since that is not the reason.

The out-parameter is gone. applyDeterministicDagToColumn is now composed of convertColumnForDeterministicDag and executeDeterministicDag, with its two lambdas as finalizeTransformedColumn and castColumnWithoutNulls. canConstantBeWrappedByDeterministicFunctions calls the two steps in turn and checks the single converted Field between them, so both the bool * and the loop that turned column rows back into Fields are gone. The IN path still calls the composed wrapper unchanged, so #117453 can add the same check there. You are right about the fast path: it converts and transforms in one step, so it exposes no intermediate value, and FunctionCast (FunctionsConversion.h:4963) does not override isInjective, so it inherits false from IFunctionBase::isInjective (IFunction.h:263) and an atom over that path is not exact either way. The injective to exact rename stays.

Behaviour is unchanged, and measured rather than argued: the 31-probe carrier matrix is byte-identical to the published head's output, and 05055, the other call site's own test 04950_minmax_count_projection_unusable_bound, plus 02982_minmax_nan_null_order, 00944_minmax_nan, 00944_minmax_null, 01710_minmax_count_projection_count_nullable, 03913_minmax_statistics_nan_ubsan_error, 04306_keycondition_nan_equality and 04401_key_condition_is_not_distinct_from all match their references. Two mutation arms show the shared walk is load-bearing for both callers rather than dead weight in one: making it shallow fails only the tuple row of 05055 and three rows of 04950, while dropping the NaN conjunct fails 05055 and leaves 04950 green.

On the coordination question, so the other two are not re-litigated: the shared walk lands here, #116763 is mine and will use it instead of adding a second copy, and #117453 can do the same. The description is updated.

@nihalzp

nihalzp commented Sep 7, 2026

Copy link
Copy Markdown
Member

@groeneai There is a conflict with master. Fix it.

groeneai and others added 2 commits September 7, 2026 14:51
The only conflict is an add/add in src/Core/Field.cpp: master gained
normalizeBoolFields and this branch gained anyFieldSatisfies, both appended
after fieldToString. Both are kept, master's body byte for byte, since the two
walks are independent.

Co-Authored-By: Claude Opus 5 <[email protected]>
The change is one decision inside KeyCondition, but the sorting key, the partition key and a minmax
skip index each build their own condition object, so the test asserts one arm per consumer instead of
inferring the other two from the sorting-key arm. Each arm also pins that its pruner ran: the
partition arm reads the transformed condition out of the plan and asserts no partition was dropped,
and the minmax arm sets force_data_skipping_indices, which throws when the index is not consulted, so
neither can pass by losing its pruner. The equality row could not tell a repaired count from a count
the exact-count projection stopped answering, since both read 0, so the projection's absence is now
read from the plan as well.

Measured on a pristine master binary built from the same tree: 7 of the 14 rows are wrong without the
change, including all three added assertions that are not controls. The additions hold with
enable_analyzer = 0 and across repeated runs.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Conflict resolved by merging master (head dfb4344), and the PR reports mergeable again. I merged rather than rebased, since that is how this branch has taken master before.

The only conflict was an add/add in src/Core/Field.cpp: normalizeBoolFields landed on master in 184a90f while this branch added anyFieldSatisfies in the same place, right after fieldToString. Both are kept, master's body byte for byte, since the two walks are independent. The merge changes nothing else: the merged tree's diff against the new master carries exactly the same +225 / -144 lines in src/ as the reviewed head carried against its own base, the 31-probe carrier matrix output is byte-identical to the pre-merge run, and 05046_minmax_index_nested_bool, master's own test for normalizeBoolFields, matches a master binary's output row for row. The nine related tests still match their references.

The same push also strengthens 05055, because the changelog claims the partition key and a minmax skip index as well as the sorting key, and each of those builds its own KeyCondition: there is now one arm per consumer (PARTITION BY toString(f), and the minmax arm forced with force_data_skipping_indices so it cannot pass by losing the index), plus a plan assertion that _exact_count_projection is no longer chosen, since the row count alone reads 0 whether the count was repaired or the projection simply stopped answering. A pristine master binary built from the same tree reddens 7 of the test's 14 rows, and the added rows hold with enable_analyzer = 0.

/// The comparison reads the constant in the domain of the column the key expression consumes, where a
/// NaN equals no value, not even itself. The transform maps it to an ordinary key value that the index
/// compares as equal, so the atom is stricter than the predicate and its `can_be_false` is not usable.
out_atom_is_exact = isDeterministicTransformInjective(dag.actions->getActionsDAG(), expr_name, dag.output_name)

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.

out_atom_is_exact is still NaN-only here, but transformed tuple constants with nested NULL have the same exactness gap for =. toString is injective for key analysis (src/Functions/FunctionsConversion.h:3157), while tuple-vs-string comparison with nested Nullable elements is nullable rather than an exact boolean (src/Functions/FunctionsComparison.h:1839-1889; tests/queries/0_stateless/04206_tuple_string_compare_nested_nullable_inference.reference shows the tuple-vs-string path returning Nullable(UInt8) / \\N). With ORDER BY toString(k) and k Tuple(Nullable(UInt8)), WHERE k = '(NULL)' can therefore still be treated as a one-point exact range in string space even though the filter result for the (NULL) row is false/NULL, which is enough to let _exact_count_projection answer count() incorrectly. I think the exactness check needs to become operator-aware here and clear exactness at least for equals on transformed tuple constants whose comparison can go nullable because of nested NULL, plus a focused regression test.

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.

Confirmed as a defect, and your citations check out: isInjective at FunctionsConversion.h:3157 is NameToString-only, and the tuple-vs-string path at FunctionsComparison.h:1839-1889 propagates a nested Nullable into the result type, which 04206_tuple_string_compare_nested_nullable_inference.reference pins as Nullable(UInt8) / \N.

It is pre-existing, though, so it is not this PR's to fix. Your exact shape (k Tuple(Nullable(UInt8)), ORDER BY toString(k), rows (NULL) and (3)), one probe file run twice: on this PR's head (Build ID ac0871b1) and on a pristine master build (Build ID 0ccba595), both debug, auto_statistics_types = '' pinned.

probe head ac0871b1 pristine master 0ccba595
k = '(NULL)', use_primary_key = 0 0 0
k = '(NULL)', projections on 1 1
_exact_count_projection in the plan yes yes
k != '(NULL)', use_primary_key = 0 0 0
k != '(NULL)', projections on 1 1
control f != 'nan' (the class this PR fixes) 2 1
control f = 'nan' 0 1

The two controls move between the builds in the same run, so the identical nested-NULL rows are a measurement rather than a dead probe.

Two notes on the fix you propose:

  • It is not equals-only. != on the same shape is equally wrong on both builds (truth 0, one row counted), so clearing exactness for equals alone would leave that direction answering 1 for a truth of 0.
  • The discriminator is not the operator but whether the comparison result can be NULL, which is the tuple-vs-string return type you cited rather than the NaN-in-the-transform-input predicate this PR adds. Same site, different check, and it needs its own before/after numbers.

So this PR stays the NaN class its changelog claims. I have added the nested-NULL carrier to the "Not done" paragraph of the description, next to the IN and signed-zero carriers, and I am fixing it separately.

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

I measured the nested-NULL exactness gap the review bot flags against out_atom_is_exact, on a pure-master debug binary (BuildID 0ccba59591d1..., 26.9.1.1, master e568d262, no part of this branch). It is real, it is pre-existing, and it needs no non-default setting:

CREATE TABLE n6 (k Tuple(Nullable(Float64), Float64)) ENGINE = MergeTree ORDER BY toString(k);
INSERT INTO n6 SELECT tuple(if(number < 8192, NULL, toFloat64(1)), toFloat64(1)) FROM numbers(16384);
SELECT count() FROM n6 WHERE k = '(NULL,1)';                          -- 8192
SELECT count() FROM n6 WHERE k = '(NULL,1)' SETTINGS use_primary_key = 0;   -- 0, the truth

EXPLAIN shows ReadFromPreparedSource (_exact_count_projection). It also reproduces with a native tuple(...) constant, so the NULL does not have to be born in the conversion, and with Tuple(Tuple(Nullable(Float64), Float64)) and Tuple(LowCardinality(Nullable(String)), String).

I am not opening a separate PR for it: after 7bab806d this branch already owns the vehicle (anyFieldSatisfies plus the conversion split), so there the fix is one predicate on the transform_input_has_nan line, and a second PR would only duplicate that refactor.

What I would flag before widening the predicate to isNull() || isNaNField() wholesale: on master these five are already correct, and a walk that enters every container would relax them and cost them their exact-count projection for no correctness gain.

constant truth master answers
Array(Nullable(Float64)), k = '[NULL,1]' 1 1
Map(String, Nullable(Float64)) 1 1
Tuple(Array(Nullable(Float64))) 1 1
Array(Tuple(Nullable(Float64))) 1 1
Map(String, Tuple(Nullable(Float64))) 1 1

Array and Map comparison orders a NULL as a value, so those stay two-valued; only Tuple composes its result from element comparisons and goes to NULL. k IS NOT DISTINCT FROM tuple(CAST(NULL,'Nullable(Float64)'), CAST(1.,'Float64')) is correct today for the same reason (truth 1, answer 1), so the bot's "operator-aware" suggestion matters: equals/notEquals need the relaxation, isNotDistinctFrom does not.

Relaxing rather than declining keeps the pruning: Granules: 1/3 survives, whereas returning false from canConstantBeWrappedByDeterministicFunctions turns the atom into FUNCTION_UNKNOWN and gives Granules: 3/3.

Separately, and not the same defect: with primary-key analysis on, a mixed IN set holding one tuple with a NULL element throws at pure defaults instead of answering, which may be relevant to the IN path you noted has the same hole.

SELECT count() FROM n6 WHERE k IN (tuple(CAST(NULL,'Nullable(Float64)'), toFloat64(1)),
                                   tuple(CAST(3.,'Nullable(Float64)'), toFloat64(1)));
-- Code: 53. DB::Exception: CAST AS Tuple can only be performed between tuple types or from String.
-- with SETTINGS use_primary_key = 0 the same query returns 1

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - dfb4344

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 profile diff RuntimeError: CI logs cluster query failed - the job's has_pr_data probe on default.binary_sizes is refused with ACCESS_DENIED, so it dies before emitting its section rows. Red repo-wide since 2026-09-07 16:06Z across ~20 PRs per hour by many authors, so it is not related to this diff a fix task is moved to pending (investigating at full effort - fixing-PR link to follow on this PR)

No other check failed at this head: the CIDB census returns one row against a 277,960-row ingestion control, and the aggregated PR status only mirrors the row above.

Session id: cron:our-pr-ci-monitor:20260907-233055

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing-PR link-back for the Build profile diff row in the CI finish ledger above: #118685 fixes the repo-side defect that failure exposed, namely that a failing first cluster read left an earlier commit's comparison pinned to the pull request, presenting an older revision as the current one.

The logs-cluster user switch that addresses the ACCESS_DENIED trigger itself is linked from that PR's description. CIDB still shows Build profile diff as error on all 7 runs started after that switch merged, with no success rows in the window, so this row's check may stay red until the cluster side is provisioned.

@nihalzp
nihalzp added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit 1dd29f8 Sep 8, 2026
175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 8, 2026
The branch was based on master at af30b32 (2026-09-08 13:43Z), which predates
ClickHouse#117501 "Do not treat a key range as exact when the constant reaches the key
transform as a NaN". That fix owns the carrier where the query text holds no NaN
and the constant only becomes one while being normalized to the type the key
transform reads, which this branch's two guards do not see: they inspect the
constant as written and the value after the key chain has mapped it back into key
space, not the intermediate one inside the transform helper. Picking the fix up
here puts the whole family under test on one tree.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 8, 2026
ClickHouse#117501 added the check this earlier guard was standing in for: it inspects the
constant after it is normalized to the type the key transform reads, so a
container NaN about to be pushed through the chain makes the atom inexact and the
range is relaxed instead of exact. With that check in the tree, the guard here
declines what the relaxed atom already answers correctly, and declining is
coarser: it leaves no key condition at all, while a relaxed one still prunes.

Measured on this tree with one binary carrying an env-gated bypass per guard, over
16 carriers (ORDER BY, PARTITION BY and a minmax index over toString and
cityHash64; tuple, array and map constants; equals, notEquals, less, its negation,
IN and NOT IN; the whole-string literal form) plus two controls pinning that an
ordinary constant still prunes: disabling the pre-transform guard alone changes no
answer, while disabling the range-endpoint guard alone loses the row of
NOT (f < 'nan') over a Float64 key. 05055 passes either way, so neither guard
interferes with the relaxation it asserts.

The third test arm goes with the guard. It covered the container-plus-transform
carrier that 05055 now owns, and it passes with both guards disabled, so it can no
longer tell this change from master.
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @nihalzp — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

The finding is real, but already reported and already being fixed: #118943 duplicates #116927 (2026-08-28), and #117453 (Closes #116927) implements both arms with a regression test. The mapping, including why the two open risks in #118943 are already inside that fix, is on the issue: #118943 (comment)

Nothing to change here. #118943 is min/max range pruning against a set that matches NaN bit-exactly, which is a different path from the key-transform exactness this PR fixed. I am not closing #118943 while its fix is unmerged.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 9, 2026
Review follow-up on the free helper functions this change introduced.

`fieldMayContainNaN` hand-rolled a recursive walk over `Tuple` to find a NaN
nested inside a set element. ClickHouse#117501 landed `anyFieldSatisfies(field, predicate)`
in `Core/Field` for exactly that, with an explicit worklist instead of native
recursion and covering `Array`/`Map`/`Object` as well, so the local walk is
deleted and the one caller uses `anyFieldSatisfies(field, isNaNField)`. The
extra container types cannot change any verdict here: the scan only runs for a
key column that `typeMayHideNaN` accepts, i.e. a float or a tuple of floats.

`columnContainsNaN` had a single caller inside
`relaxAtomsOverNaNHidingColumns`, so it becomes a local lambda beside the
`column_may_hide_nan` lambda that is already there.

`typeMayHideNaN` was declared at namespace scope in `KeyCondition.h` purely so
`MergeTreeDataSelectExecutor` could reach it. It answers a question about key
analysis against a `getExtremes`-derived bound, which is `KeyCondition`'s own
concern, so it becomes a static member and the header stops exporting a loose
function.

`isFloatComparison` stays a file-local static: it is a predicate over an
`ActionsDAG` node shape used only by `cloneDAGWithInversionPushDown`, with the
same signature as its neighbour `canFoldToInverseRelation`, and it belongs to no
class.

No behaviour change intended. 04327 / 04328 / 04350 and ClickHouse#117501's 05055 pass
(3 runs each); neutralizing the `anyFieldSatisfies` call reddens 04327, whose
`t IN ((nan, 1.), (500., 500.))` arm is the packed-tuple case that needs the
nested walk.
@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-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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

Development

Successfully merging this pull request may close these issues.

4 participants