Skip to content

Fix NaN rows dropped by CNF folding of negated ordering comparisons - #112989

Open
asdf2014 wants to merge 4 commits into
ClickHouse:masterfrom
asdf2014:fix-cnf-negation-float-nan
Open

asdf2014 wants to merge 4 commits into
ClickHouse:masterfrom
asdf2014:fix-cnf-negation-float-nan

Conversation

@asdf2014

@asdf2014 asdf2014 commented Aug 2, 2026 •

Copy link
Copy Markdown

Closes: #112036

With convert_query_to_cnf = 1, the CNF converter rewrote NOT (x < c) into x >= c (and similarly for <=, >, >=). For floating-point values this is not an equivalent transformation: NaN fails every ordered comparison, so NOT (x < c) is true for x = NaN while x >= c is false. Rows containing NaN silently disappeared from the result, in both the new and the old analyzer.

The fix makes the folding type-aware in the Analyzer CNF (src/Analyzer/Passes/CNF.cpp): ordering comparisons are folded only when every argument type is known to be totally ordered (integers, Decimal, Enum, Date/DateTime/Time families, String/FixedString, UUID, IPv4/IPv6, also inside Nullable/LowCardinality). For floating-point, Dynamic, composite and unknown types the atom keeps its explicit negation, so with the Analyzer the existing constraint optimizations (e.g. the A AND NOT A elimination in 01622_constraints_simple_optimization) are preserved for totally ordered types. The old TreeCNFConverter works on bare ASTs without type information and now keeps the negation for all ordering comparisons. As a consequence, with enable_analyzer = 0 the CNF resolution step no longer recognises x > c and x <= c as complementary, so optimize_using_constraints performs fewer eliminations than before even for integer columns; the updated 01622_constraints_simple_optimization.oldanalyzer.reference reflects that (the row counts asserted by the test are unchanged, only the rewritten WHERE in EXPLAIN SYNTAX keeps more conjuncts). One of the affected EXPLAIN SYNTAX statements also stops hitting a separate pre-existing defect where a filter reduced to a contradiction is dropped entirely instead of becoming WHERE 0; that defect remains reachable through the Analyzer and will be reported separately.

A constraint whose negated ordering atom cannot be folded (e.g. ASSUME NOT (x < c) over a Float64 column) is skipped when building the comparison graph instead of hitting the assertion there. Since negated ordering atoms can now survive CNF normalization, the constraint-driven index hint derivation (optimize_append_index) learned to give up on them: it derives the hint relation from the function name alone, so consuming a negated atom would produce an indexHint of the opposite range and prune valid granules.

The equals/notEquals, in/notIn, like/notLike, empty/notEmpty pairs are still always folded, since they remain complementary for NaN.

Two related degenerate cases are covered by the same guard. A comparison of a non-string operand with a string constant that cannot be converted (e.g. u < '257' for UInt8, or an Enum compared with a non-member literal) also returns false for <, <=, >, >= alike, so such mixed comparisons are not folded either. And the tautology elimination under optimize_using_constraints no longer treats x >= c OR x < c over a Float64 column as always true (both sides are false for NaN).

The fix is scoped to the CNF rewrite. The primary key index analysis (KeyCondition) applies the same kind of negation folding independently of convert_query_to_cnf; that is a separate pre-existing issue and will be reported and fixed separately. The constraint-driven index hint derivation also has a pre-existing gap unrelated to negation: it silently skips atoms that are not two-argument comparisons instead of giving up on the group, which can produce an over-strong indexHint; that is left untouched here and will be reported separately as well.

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):

Fix dropping of rows under convert_query_to_cnf = 1 when a negated ordering comparison was rewritten into the opposite comparison although the two are not complementary. This affected floating-point columns, where NaN fails both x < c and x >= c, and comparisons with an unconvertible string constant (e.g. NOT (u < '257') for UInt8), which fail both sides the same way. As a side effect, with the old analyzer (enable_analyzer = 0) the CNF converter no longer normalises ordering comparisons at all, so optimize_using_constraints may eliminate fewer conditions than before, including for non-floating-point columns.


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

With convert_query_to_cnf = 1, NOT (x < c) was rewritten into x >= c
(and similarly for the other ordering comparisons). For floating-point
values this is not an equivalent transformation: NaN fails every
ordered comparison, so NOT (x < c) is true for x = NaN while x >= c is
false, and rows containing NaN silently disappeared from the result.

In the Analyzer CNF the ordering comparisons are now folded only when
every argument type is known to be totally ordered (integers, Decimal,
Enum, Date/DateTime/Time, String, UUID, IPv4/IPv6, also inside
Nullable and LowCardinality); for floating-point, Dynamic, composite
and unknown types the atom keeps its explicit negation. Comparisons
mixing a string operand with a non-string one are not folded either:
when the string constant cannot be converted, <, <=, >, >= all return
false, which breaks the complementarity the same way NaN does (e.g.
NOT (u < '257') for UInt8, or an Enum compared with a non-member
literal). The old TreeCNFConverter works on bare ASTs without type
information, so it keeps the negation for all ordering comparisons.

A constraint whose negated ordering atom is not folded, e.g.
ASSUME NOT (x < c) over a Float column, stays negative, and the
comparison graph stores unnegated relations only, so it is skipped
when building the graph instead of failing the pre-existing
assertion. The constraint-driven index hint derivation
(optimize_append_index) now also gives up on a negated ordering atom:
the hint relation is derived from the function name alone, so
consuming such an atom would produce an indexHint of the opposite
range and prune valid granules.

With the old analyzer the CNF resolution step consequently no longer
recognises x > c and x <= c as complementary, so
optimize_using_constraints performs fewer eliminations there even for
integer columns; the oldanalyzer reference of
01622_constraints_simple_optimization is regenerated accordingly
(query results are unchanged, only the rewritten WHERE in
EXPLAIN SYNTAX keeps more conjuncts).

The equals/notEquals, in/notIn, like/notLike and empty/notEmpty pairs
are still always folded: they remain complementary for NaN.
@CLAassistant

CLAassistant commented Aug 2, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@zlareb1 zlareb1 added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f651a3b]

Summary: ❌

job_name test_name status info comment
Stress test (arm_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb
Possible deadlock on shutdown (see gdb.log) FAIL cidb

AI Review

Summary

This PR fixes the main analyzer-side CNF bug around folding negated ordering comparisons over NaN and updates the constraint and indexHint consumers consistently on that path. I still see one remaining wrong-result hole in the old analyzer: enable_analyzer = 0 keeps the unconditional atom OR NOT atom tautology rule for nullable predicates, so the same class of query can still lose NULL rows there.

Findings

❌ Blockers

  • [src/Interpreters/WhereConstraintsOptimizer.cpp:93] [dismissed by author -- https://github.com/Fix NaN rows dropped by CNF folding of negated ordering comparisons #112989#discussion_r3886654642] checkIfGroupAlwaysTrueAtoms still drops x < c OR NOT (x < c) unconditionally in the old-analyzer path. For Nullable(Float64) both branches evaluate to NULL on the NULL row, so WHERE x < 65.5 OR NOT (x < 65.5) SETTINGS convert_query_to_cnf = 1, optimize_using_constraints = 1, enable_analyzer = 0 is still rewritten to no filter and returns 4 instead of 3. The analyzer version of this rule is now null-aware, so leaving the old path untouched keeps a live wrong-result bug in a still-selectable execution mode.
    Suggested fix: make the old-analyzer atom OR NOT atom elimination prove that the predicate result is non-nullable before firing, or conservatively disable that rule there when the old analyzer cannot prove non-nullability.
Final Verdict

Not ready to merge until the remaining enable_analyzer = 0 wrong-result path is fixed or that mode is explicitly taken out of the supported contract for this optimization.

LLVM Coverage Report

Measured on commit f651a3b.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 104/114 (91.23%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 5, 2026
…oat-nan

# Conflicts:
#	tests/queries/0_stateless/01622_constraints_simple_optimization.oldanalyzer.reference
Master removed all old-analyzer stateless test coverage: the
oldanalyzer reference files are gone and tests no longer carry
SETTINGS enable_analyzer = 0. Follow that policy here:
04669_cnf_not_ordering_comparison_nan now pins enable_analyzer = 1 and
keeps only the Analyzer variants of its queries, and the merge already
dropped the regenerated oldanalyzer reference of
01622_constraints_simple_optimization together with the mechanism.

The TreeCNFConverter part of the fix is unchanged: the old analyzer
code path still exists and keeps its conservative no-fold behavior, it
is just no longer exercised by stateless tests, matching the rest of
the test suite.
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f651a3be0 with master 691db87c8 (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.

Object file sizes

19 object files changed (+60.20 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/ArrowIPC/ArrowIPCBlockInputFormat.cpp.o 499.02 KiB 522.79 KiB +23.77 KiB (+4.76%)
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp.o 1.09 MiB 1.11 MiB +17.47 KiB (+1.56%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

The syntactic "atom OR NOT atom" elimination in
checkIfGroupAlwaysTrueAtoms is not sound in three-valued logic: for a
NULL value both sides are NULL, so the group is not always true and
the filter must stay. The Analyzer version now treats the pair as
mutually exclusive only when the atom cannot produce NULL; the old
analyzer works on bare ASTs without type information and keeps the
existing behavior, which is now documented in a comment.

The defect itself predates this pull request: on current master the
folding of the negated atom and its later unfolding inside the
constraint optimizer restore the literal pair, so the group is dropped
the same way. It is fixed here because the review flagged it and the
fix belongs to the same family of type-aware CNF equivalences.
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026

This branch has not been deployed

No deployments
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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

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

4 participants