Skip to content

Do not invert an ordered comparison that can see a NaN in the CNF form - #118216

Merged
alexey-milovidov merged 4 commits into
masterfrom
cnf-nan-ordered-comparison-112036
Sep 20, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
cnf-nan-ordered-comparison-112036

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

convert_query_to_cnf = 1 rewrote NOT (x < c) into x >= c and NOT (x > c) into x <= c. NaN fails every ordered comparison, so NOT (nan < c) is true while nan >= c is false: the two operators are complementary over a totally ordered domain only, and the rewrite silently dropped every NaN row from the result.

CREATE TABLE t_nan (x Float64) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t_nan VALUES (nan), (1), (100);

SELECT count() FROM t_nan WHERE NOT (x < 65.5);                                   -- 2
SELECT count() FROM t_nan WHERE NOT (x < 65.5) SETTINGS convert_query_to_cnf = 1; -- 1 before, 2 now

The analyzer knows the argument types, so it keeps inverting a comparison that cannot see a NaN: an argument that is a floating point column - or holds one inside an Array, Tuple, Map, Nullable or LowCardinality - declines the inversion, and a floating point literal declines it only when it really is a NaN. The legacy AST stage in TreeCNFConverter has no types, so it cannot tell a floating point comparison from an integer one and now leaves every ordered comparison alone; the equality, IN, LIKE and empty operators keep being inverted there, since those answer false, not NULL, for a NaN.

Closes: #112036
Related: #111939

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Fixed convert_query_to_cnf = 1 silently dropping rows with a NaN in a floating point column: the conversion rewrote NOT (x < c) into x >= c, which is not an equivalent condition for NaN.


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

Version info

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

`convert_query_to_cnf = 1` rewrote `NOT (x < c)` into `x >= c` and `NOT (x > c)`
into `x <= c`. `NaN` fails every ordered comparison, so `NOT (nan < c)` is true
while `nan >= c` is false: the two operators are complementary over a totally
ordered domain only, and the rewrite silently dropped every `NaN` row from the
result of a query whose `WHERE` used the negated form.

The analyzer knows the argument types, so it keeps inverting a comparison that
cannot see a `NaN`: an argument that is a floating point column - or holds one
inside an `Array`, `Tuple`, `Map`, `Nullable` or `LowCardinality` - now declines
the inversion, and a floating point literal declines it only when it really is a
`NaN`. The legacy AST stage in `TreeCNFConverter` has no types, so it cannot
tell a floating point comparison from an integer one and now leaves every
ordered comparison alone; the equality, `IN`, `LIKE` and `empty` operators keep
being inverted there, since those answer false, not NULL, for a `NaN`.

Closes: #112036

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

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f119d14]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes the main NaN row-loss in CNF inversion for ordinary filters and adds solid coverage for Float64 and Dynamic, but it also removes an invariant that both constraint comparison-graph builders still rely on. Negated ordered CHECK / ASSUME constraints are now recorded with the opposite meaning, so constraint-driven rewrites can still optimize queries incorrectly.

Findings

❌ Blockers

  • [src/Storages/ConstraintsDescription.cpp:142-148] The legacy AST constraint graph still assumes pushNotIn turns ordered comparisons into non-negative atoms before they are inserted. After this PR, CHECK NOT (i < 5) reaches buildGraph as {negative = true, ast = less(i, 5)}; in release builds the chassert is compiled out, so the graph records plain less(i, 5) and loses the negation. Every AST consumer of metadata_snapshot->getConstraints().getGraph() (WhereConstraintsOptimizer, SubstituteColumnOptimizer, AddIndexConstraintsOptimizer) can then reason from the opposite invariant and drop, weaken, or synthesize filters incorrectly. Suggested fix: skip still-negative ordered atoms when populating the graph, or teach ComparisonGraph to represent negated atoms explicitly instead of passing raw AST nodes.
  • [src/Storages/ConstraintsDescription.cpp:286-293] The analyzer-side graph has the same stale precondition. Analyzer::CNF::pushNotIntoFunction now correctly leaves NOT (f < 5) negative for Float*, Dynamic, and JSON, but QueryTreeData::buildGraph still strips that atom down to the underlying less(f, 5) node after only a debug-time chassert. On current master this is the active constraint-optimization path, so a negated ordered floating-point constraint can make optimize_using_constraints prove the opposite predicate and misoptimize filters. Suggested fix: apply the same handling as above in the query-tree builder, and keep both graph builders behaviorally aligned.
Tests
  • ⚠️ The new stateless test only covers plain WHERE CNF conversion. Add a focused regression for negated ordered constraints under optimize_using_constraints so both graph builders are exercised: one AST-backed case for CHECK NOT (i < 5), and one analyzer-backed case for a Float64 / Dynamic constraint that must keep the negation.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: preserve or explicitly reject still-negative ordered atoms in both constraint comparison-graph builders, and add regression coverage for constraint-based optimization on negated ordered comparisons.

LLVM Coverage Report

Measured on commit f119d14.

Metric Baseline Current Δ
Lines 88.50% 88.40% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 40/41 (97.56%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 5, 2026
Comment thread src/Analyzer/Passes/CNF.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 5, 2026
@zlareb1

zlareb1 commented Sep 5, 2026

Copy link
Copy Markdown
Member

TL;DR: the new guard misses Dynamic (and JSON dynamic paths), so the exact row-loss shape this PR fixes survives for a Dynamic column holding nan — analyzer leg only.

  1. typeCanHoldNaN decides by WhichDataType(type).isFloat() plus a forEachChild sweep. DataTypeDynamic does not override forEachChild (the IDataType base is a no-op) and is not a float, so argumentCanBeNaN returns false for a Dynamic argument and tryInvertFunction still folds NOT (d < c) into d >= c. DataTypeObject::forEachChild enumerates typed paths only, so a JSON dynamic path (where a Float64 lands by default) has the same gap. Variant(Float64, ...) is covered, since DataTypeVariant::forEachChild enumerates the variants.

  2. The shape is live, not theoretical — comparisons over Dynamic are excluded from the total-order compareAt path and execute the typed IEEE comparison per inner type, so a nan inside Dynamic fails ordered comparisons exactly like a plain Float64 nan. On a current pre-fix dev build:

CREATE TABLE t (d Dynamic) ENGINE = Memory;
INSERT INTO t VALUES (nan::Float64), (1.0::Float64), (100.0::Float64);
SELECT count() FROM t WHERE NOT (d < 65.5) SETTINGS convert_query_to_cnf = 0; -- 2, correct
SELECT count() FROM t WHERE NOT (d < 65.5) SETTINGS convert_query_to_cnf = 1; -- 1, the nan row is dropped

With this PR the second query keeps returning 1: both arguments pass argumentCanBeNaN = false (Dynamic is not a float and has no children; 65.5 is a non-NaN literal), so the inversion proceeds. The legacy AST leg is immune post-fix because ordered comparisons were removed from both maps there.

  1. Suggested one-liner in typeCanHoldNaN: also return true for types that can carry an arbitrary inner type, i.e. isDynamic(type) || isObject(type) — fail-open is the right polarity for a guard whose miss silently drops rows.

@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit f119d147f703c24e2f61ed87fcd6958b7419e777 with master failed: RuntimeError: CI logs cluster query failed: SELECT file, detail, sumIf(dur, side = 'pr'….

See the job log for details.

alexey-milovidov and others added 2 commits September 16, 2026 10:36
…d, drop the old analyzer from the test

`typeCanHoldNaN` judged a type by its own floating point kind and by the kinds of its children, which
missed `Dynamic` and `JSON`: `DataTypeDynamic::forEachChild` enumerates nothing and
`DataTypeObject::forEachChild` enumerates only the typed paths, yet both carry values of any type, and a
comparison over a `Dynamic` value is executed per inner type, so a `Float64` `NaN` inside it fails the
ordered comparison the same way a plain `Float64` does. `NOT (d < c)` over a `Dynamic` column was still
inverted into `d >= c` and dropped the `NaN` rows. Both types are now judged by the type itself, also
when nested in a carrier such as `Array(Dynamic)`.

The test used `enable_analyzer = 0` for the legacy path and `EXPLAIN QUERY TREE` without forcing the
analyzer, which failed in the old analyzer CI job: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118216&sha=0f068278873adb476e3487270d8e43a9815269c9&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%201%2F3%29
`enable_analyzer = 0` is rejected on master since 26.9, so those queries are removed, and the
`EXPLAIN QUERY TREE` checks set `enable_analyzer = 1` explicitly. `Dynamic` and `Array(Dynamic)`
cases are added; a `NaN` cannot be stored in a `JSON` path (the conversion drops it), so `JSON` is
covered by the guard only.

#118216

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, @zlareb1 — adopted in 4ebcb44: typeCanHoldNaNItself returns true for a floating point type, Dynamic and JSON, and typeCanHoldNaN applies it to the type and to its children, so Array(Dynamic) and the like are covered too. Your Dynamic repro is now part of test 05084 and returns 2 rows with convert_query_to_cnf = 1. The JSON half is guarded but has no runtime test, because a NaN cannot be stored in a JSON path: the conversion drops it or turns it into 0. The branch is also merged with master; enable_analyzer = 0 is rejected on master since 26.9, so the legacy-path queries were removed from the test and EXPLAIN QUERY TREE sets enable_analyzer = 1 explicitly, which was the cause of the red old-analyzer job.

@@ -323,14 +328,10 @@ void pushNotIn(CNFQueryAtomicFormula & atom)

static const std::unordered_map<std::string, std::string> inverse_relations = {

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.

ConstraintsDescription::buildGraph still assumes pushNotIn leaves ordered comparisons non-negative before they are added to the ComparisonGraph (src/Storages/ConstraintsDescription.cpp:142-148). After removing the ordered entries here, a constraint like CHECK NOT (i < 5) stays as {negative = true, ast = less(i, 5)}; in release builds the chassert(!atom.negative) is compiled out and we push plain less(i, 5) into the graph. That inverts the meaning of the constraint, so WhereConstraintsOptimizer can treat i < 5 as always true and drop or weaken filters incorrectly.

The graph builder needs a real if (!atom.negative) guard (or another safe representation for negated ordered comparisons) before inserting the atom, and this path needs a focused regression test with a negated ordered CHECK.

return true;

for (const auto & argument : function_node.getArguments())
if (argumentCanBeNaN(argument))

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.

The analyzer-side constraint graph still relies on the stronger precondition that pushNotIntoFunction returns a non-negative ordered comparison before ConstraintsDescription::QueryTreeData::buildGraph inserts it (src/Storages/ConstraintsDescription.cpp:286-293). Once this new NaN guard declines NOT (x < 5) for a Float64, Dynamic, or JSON constraint, the atom stays negative; in release builds the chassert(!atom.negative) disappears and we still push plain less(x, 5) into the ComparisonGraph.

That records the opposite invariant from the actual CHECK and lets constraint-based rewrites misoptimize queries over floating-point data. Please either skip still-negative ordered atoms when building the graph or teach the graph to represent them explicitly, and add a regression test for a negated ordered floating-point constraint.

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

Tolerable.

@alexey-milovidov alexey-milovidov self-assigned this Sep 20, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 20, 2026
Merged via the queue into master with commit 7d9939d Sep 20, 2026
175 of 177 checks passed
@alexey-milovidov
alexey-milovidov deleted the cnf-nan-ordered-comparison-112036 branch September 20, 2026 21:37
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 25, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 119274 118919 Revert "Carry the mutation version onto a rewritten lightweight `DELETE`"
Changelog-revert: 119306 119274 Revert "Revert "Carry the mutation version onto a rewritten lightweight `DELETE`""
Changelog-revert: 119334 117356 Revert "Unify the spill trigger for hash joins"
Changelog-revert: 119335 119334 Revert "Revert "Unify the spill trigger for hash joins""
Changelog-revert: 121135 118279 Revert "Test the ESCAPE route into the ngram LIKE-pattern tokenizer"
Changelog-revert: 121136 121135 Revert "Revert "Test the ESCAPE route into the ngram LIKE-pattern tokenizer""
Changelog-revert: 121258 118216 Revert "Do not invert an ordered comparison that can see a `NaN` in the CNF form"
Changelog-revert: 121298 117578 Revert "Bound the docker buildx retry ladder by wall clock, not by the timeout divisor"
Changelog-revert: 121443 114465 Revert "Fix an error reading an Iceberg table whose `current-snapshot-id` is JSON null"
Changelog-revert: 121477 121096 Revert "Trim `test_max_bytes_ratio_before_external_distinct` to fit the client timeout"
Changelog-revert: 121901 121869 Revert "docs(managed-postgres): updated Private Service Connect"
Changelog-revert: 122110 118223 Revert "Correct nightly coverage selection and share PR test manifests"
Changelog-revert: 122140 120312 Revert "Refuse a `Set` table on the right side of `IN` when a row policy applies to it"
Changelog-deleted-entry: 114465 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed an error when reading an Iceberg table whose `current-snapshot-id` is JSON null, which some writers emit for a table with no current snapshot. [#114465](#114465) ([Shaohua Wang](https://github.com/tiandiwonder)).
Changelog-deleted-entry: 118216 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed `convert_query_to_cnf = 1` silently dropping rows with a `NaN` in a floating point column: the conversion rewrote `NOT (x < c)` into `x >= c`, which is not an equivalent condition for `NaN`. [#118216](#118216) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog-deleted-entry: 118223 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Correct nightly coverage selection and share PR test manifests. [#118223](#118223) ([Nikita Fomichev](https://github.com/fm4v)).
Changelog-deleted-entry: 120312 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * A row policy on a `Set`-engine table was accepted but never applied: the right side of `IN` read the prebuilt set directly and returned the rows the policy hides. Such a query now fails with `ACCESS_DENIED`, because the `Set` engine has no read path that could filter the rows. Queries that used a `Set` table covered by a database-wide row policy ran unfiltered before and now throw. [#120312](#120312) ([Harikrishnan Prabakaran](https://github.com/harikrishnan94)).
Changelog-deleted-entry: 121096 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Sized `test_max_bytes_ratio_before_external_distinct` to fit the integration harness's 600 second per-query timeout. [#121096](#121096) ([Groene AI](https://github.com/groeneai)).
alexey-milovidov added a commit that referenced this pull request Oct 3, 2026
…graph test

#118216 was reverted by
#121258, so the CNF conversion
inverts `NOT (a < b)` into `a >= b` again even for `Float64`. The result of
`WHERE a >= b` on the table with a `NaN` row depends on that, which is not what
this test is about, so it is no longer checked.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121255&sha=4ce0e19ad7da1a501b440283b2607270955e32b7&name_0=PR&name_1=Fast%20test
PR: #121255

Co-Authored-By: Claude Opus 5.5 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 3, 2026
`NOT (x < c)` is not `x >= c` when an argument can be a `NaN`, so
ClickHouse#118216 stopped the CNF conversion
from inverting an ordered comparison. `pushNotIn` and
`Analyzer::CNF::pushNotIntoFunction` can therefore return an atom that is still
negative, which the two places that build the constraints comparison graph did
not expect: they asserted `!atom.negative` and then took the atom in as if it
were positive.

So `CREATE TABLE t (a Int64, b Int64, CONSTRAINT c ASSUME NOT (a < b))` is an
exception in a build with assertions, and in a release build it puts `a < b`
into the graph for a constraint that states the opposite - after which
`optimize_using_constraints` answers `WHERE a < b` from the graph as always true
and `WHERE a >= b` as always false.

The comparison graph stores plain relations and has nowhere to put a negation,
so such an atom is now left out of it. For the same reason the index-hint
groups, which read the relation off the function name, no longer derive a hint
from a negated atom.

Found by BuzzHouse on master:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=a78f42eea9cea494806b50ec12b74dc72367944e&name_0=MasterCI&name_1=BuzzHouse%20%28amd_msan%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=ed38f61d0941cf0a81dd0b410b3a01afbd60eba0&name_0=MasterCI&name_1=BuzzHouse%20%28amd_debug%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=3c54270f07bd67f052bc900f371312f59f73505f&name_0=MasterCI&name_1=BuzzHouse%20%28arm_asan_ubsan%29

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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.

convert_query_to_cnf = 1 rewrites NOT (x < c) to x >= c, silently dropping NaN rows

3 participants