Skip to content

Skip not-comparison rewrite for float operands (issue #106533) - #106568

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-106533-partition-pruning-nan-not
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-106533-partition-pruning-nan-not

Conversation

@groeneai

@groeneai groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

KeyCondition::cloneDAGWithInversionPushDown (used by partition pruning, primary-key analysis, min-max indexes, and skip indexes) rewrites not(greater(x, c)) into lessOrEquals(x, c) via the inverse_relations table. This algebraic identity is invalid under IEEE-754: when x is NaN, not(NaN > c) is not(false) = true, while the candidate inverse NaN <= c is false.

With ORDER BY c0 PARTITION BY c0 on INSERT INTO t VALUES (1), (-1), partition pruning translated not(sqrt(c0) > 10) into sqrt(c0) <= 10 and incorrectly dropped the c0 = -1 partition where sqrt(c0) is NaN. The metamorphic equivalence in the issue body broke as a result:

SELECT c0 FROM t GROUP BY c0
HAVING NOT ((SUM(c0) > 0) OR (sqrt(c0) > 10))
SETTINGS aggregate_functions_null_for_empty=1, enable_optimize_predicate_expression=0;
-- correct: returns -1

SELECT c0 FROM t GROUP BY c0
HAVING NOT (SUM(c0) > 0)
INTERSECT DISTINCT
SELECT c0 FROM t GROUP BY c0
HAVING NOT (sqrt(c0) > 10)
SETTINGS aggregate_functions_null_for_empty=1, enable_optimize_predicate_expression=0;
-- before fix: empty (incorrect)
-- after fix:  -1

The fix skips the inverse rewrite for the six comparison ops (<, >, <=, >=, =, !=) when an operand can be NaN: either a non-constant floating-point column, or a constant NaN value. The fallback not() wrapper at the end of cloneDAGWithInversionPushDown preserves the correct semantics; the inner comparison still drives index analysis. Plain literal cases like c <= 5.5 (Int column vs Float literal) keep their full inversion since neither operand can be NaN. Decimal is unaffected: it has no NaN.

Closes: #106533

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 wrong-results bug where partition and primary-key pruning rewrote NOT (f(x) > c) into f(x) <= c for floating-point operands, dropping rows where f(x) is NaN. After the fix the inversion is skipped for the six comparison operators when an operand can be NaN, so WHERE NOT (sqrt(c0) > 10) keeps rows whose sqrt(c0) is NaN as IEEE-754 requires.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

`KeyCondition` (and partition pruning, primary-key analysis, min-max,
skip indexes - all paths sharing `cloneDAGWithInversionPushDown`)
rewrote `not(greater(x, c))` into `lessOrEquals(x, c)` via the
`inverse_relations` table. This algebraic identity is invalid under
IEEE-754: when `x` is NaN, `not(NaN > c)` is `not(false) = true`, while
the candidate inverse `NaN <= c` is `false`. With `ORDER BY c0
PARTITION BY c0` and `c0 = -1`, partition pruning translated `not(sqrt(c0)
> 10)` into `sqrt(c0) <= 10` and incorrectly dropped the partition
where `sqrt(c0)` is NaN, returning empty results from queries that should
keep that row.

Skip the inverse rewrite for the six comparison ops (`<`, `>`, `<=`,
`>=`, `=`, `!=`) when an operand can be NaN - either a non-constant
floating-point column, or a constant `NaN` value. The fallback `not()`
wrapper at the end of the function preserves the correct semantics; the
inner comparison still drives index analysis. Plain literal cases like
`c <= 5.5` (Int column vs Float literal) keep their full inversion since
neither operand can be NaN.

Closes: ClickHouse#106533

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

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes - exact reproducer from issue #106533. The Q2 INTERSECT query returns empty before fix, returns -1 after fix. 100% reproducible.
b Root cause explained? Yes - in cloneDAGWithInversionPushDown, when handling not(comparison), the code looks up the comparison in inverse_relations and rewrites e.g. not(greater(x, c)) to lessOrEquals(x, c). The algebraic identity holds for total orders but is INVALID under IEEE-754: not(NaN > c) = true but NaN <= c = false. Partition pruning then evaluates the wrong condition and drops the partition where the value is NaN.
c Fix matches root cause? Yes - directly skips the inverse_relations rewrite for the six comparison ops (<, >, <=, >=, =, !=) when an operand could be NaN (non-constant float column, or constant NaN value). The fallback at line 1129-1130 wraps the result with not(), preserving correct semantics. Constant non-NaN floats and non-float types (Int, String, Decimal) still get inverted (full optimization preserved).
d Test intent preserved / new tests added? New test 04318_106533_partition_pruning_nan_inversion.sql covers: the exact metamorphic pair from the issue, the direct probe count() WHERE NOT (sqrt(c0) > 10) on (1), (-1) (returns 2 - both rows, correct), Float column NaN behavior (NOT(f > 5) keeps NaN row vs f <= 5 drops it), and Decimal still being inverted (no regression for non-NaN types).
e Both directions demonstrated? Yes. Without fix: Q2 INTERSECT returns empty; count() WHERE NOT (sqrt(c0) > 10) returns 1. With fix: Q2 returns -1; count() WHERE NOT (sqrt(c0) > 10) returns 2. Verified locally with the same ASan binary, same data.
f Fix is general, not a narrow patch? Yes - covers all six comparison ops, not just >. Handles LowCardinality(Nullable(Float)) via removeLowCardinalityAndNullable. Distinguishes constant floats (NaN-checkable at compile time) from runtime float columns (must be guarded). Same fix applies to all index paths (partition, primary key, min-max, skip indexes) since they share cloneDAGWithInversionPushDown. The AST-based cloneASTWithInversionPushDown is dead code (only called recursively from itself) so doesn't need patching.

Session id: cron:clickhouse-ci-task-worker:20260605-120200

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @CurtizJ — could you review this? It fixes wrong-results in partition and primary-key pruning where not(f(x) > c) was algebraically rewritten to f(x) <= c, dropping rows whose value is NaN (not equivalent under IEEE-754). The fix is scoped to KeyCondition::cloneDAGWithInversionPushDown and skips the inversion only when an operand can be NaN.

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

clickhouse-gh Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [62cb6e6]

Summary: ❌

job_name test_name status info comment
AST fuzzer (arm_asan_ubsan) FAIL
Logical error: Column identifier A is already registered (STID: 4697-4326) FAIL cidb

AI Review

Summary

This PR fixes an invalid not-comparison inversion in KeyCondition for floating-point operands that can produce NaN, preserving correct partition and key pruning semantics for predicates such as NOT (sqrt(c0) > 10). I did not find any blocker or major issue in the current diff.

Final Verdict

Status: ✅ Approve

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

clickhouse-gh Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 18/20 (90.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA: 62cb6e6

CI fully finished (Finish Workflow + Mergeable Check completed at 17:48:23Z, >20 min buffer).

Check Test Disposition
AST fuzzer (arm_asan_ubsan) Logical error: Column identifier A is already registered (STID 4697-4326) Chronic trunk bug, already tracked. 30-day cross-PR query: 7 master hits + 30+ unrelated PRs (incl. PR #105249 ×5, PR #99980 ×4, PR #100397 ×3, PR #95355 ×3, etc.). Tracked in our existing task with fix PR #106025 (planner old-analyzer pivot, currently on review). Not caused by this PR (this PR only touches KeyCondition::cloneDAGWithInversionPushDown, no analyzer/Planner code).
Mergeable Check (meta) Derivative — fails because the AST fuzzer arm_asan_ubsan check failed.
PR (meta) Derivative aggregator.

No PR-caused failures. 144 pass / 19 skip / 1 chronic-tracked + 2 derivative.

Ball with reviewers (@KochetovNicolai, @CurtizJ).

Session: cron:our-pr-ci-monitor:20260605-190000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #107074.

While fixing #106948 (minmax skip index dropping NaN granules under a negated float range, flagged as a possible duplicate of #106533), I found that issue needs both this KeyCondition fix and a separate fix in the minmax index aggregator. #107074 contains both and closes #106533 and #106948 together, so I'm consolidating here to avoid two PRs touching KeyCondition.cpp. This PR's change is included verbatim in #107074 (now as test 04328).

@groeneai groeneai closed this Jun 10, 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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Metamorphic equivalence violation in HAVING clauses due to buggy partition pruning on NaN values

2 participants