Skip to content

Decline divide/multiply monotonicity when an endpoint maps to NaN - #118468

Merged
alexey-milovidov merged 1 commit into
masterfrom
arithmetic-monotonicity-nan-endpoint-118121
Sep 7, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
arithmetic-monotonicity-nan-endpoint-118121

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Index analysis models divide and multiply by a constant as monotonic from the constant alone. A Float
key column may hold ±inf, and -inf / inf, inf * 0 and 0 * inf are all NaN, so the transformed range
endpoint became NaN - a range no point compares into - and every part and granule was pruned:

CREATE TABLE t (k Float64) ENGINE = MergeTree ORDER BY k;
INSERT INTO t VALUES (-inf), (1), (2), (3);

SELECT count() FROM t WHERE k / inf = 0;   -- 0, expected 3
SELECT count() FROM t WHERE k * 0 = 0;     -- 0, expected 3

Both pruning layers were affected on their own - the primary key index and the statistics-based part pruning
(use_statistics_for_part_pruning, on by default) - so the query silently returned nothing at default
settings. No NaN appears in the data or in the query: a legal ±inf in the column is enough.

Only the transform can tell, so it is now evaluated at both endpoints - as the plus/minus branches
already do for their own overflow question - and monotonicity is declined when either result is NaN. The
check is restricted to a Float result: no other result type has a NaN, and an integer division by a zero
constant would raise here rather than answer one. Pruning for ranges that stay finite is unchanged, which
the test pins.

Closes: #118121

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 queries silently returning no rows when a Float primary key column holds ±inf and the predicate's
arithmetic maps that endpoint to NaN, e.g. WHERE k / inf = 0 or WHERE k * 0 = 0: index and statistics
pruning dropped every part and granule.


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

Index analysis models `divide` and `multiply` by a constant as monotonic from the constant alone. A
`Float` key column may hold `±inf`, and `-inf / inf`, `inf * 0` and `0 * inf` are all `NaN`, so the
transformed range endpoint became `NaN` - a range no point compares into - and every part and granule
was pruned:

    CREATE TABLE t (k Float64) ENGINE = MergeTree ORDER BY k;
    INSERT INTO t VALUES (-inf), (1), (2), (3);

    SELECT count() FROM t WHERE k / inf = 0;   -- 0, expected 3
    SELECT count() FROM t WHERE k * 0 = 0;     -- 0, expected 3

Both pruning layers were affected on their own, the primary key index and the statistics-based part
pruning, so the query silently returned nothing at default settings.

Only the transform can tell, so it is now evaluated at both endpoints - as the `plus`/`minus` branches
already do for their own overflow question - and monotonicity is declined when either result is `NaN`.
The check is restricted to a `Float` result: no other result type has a `NaN`, and an integer division
by a zero constant would raise here rather than answer one.

Closes: #118121

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

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d3b9acd]

Summary: ✅


AI Review

Summary

The implementation matches the reported NaN-endpoint pruning bug, and the new monotonicity guard itself looks consistent. The remaining gap is evidence: the new stateless test proves variable / constant and multiply, but the patch also changes the distinct const / variable divide path, which is still unpinned.

Tests
  • ⚠️ tests/queries/0_stateless/05113_arithmetic_monotonicity_nan_endpoint.sql:11 Add one focused stateless case for const / variable divide, for example WHERE inf / k = inf over (1), (2), (3), (inf). That branch inverts the transformed range, so a NaN produced from the stored inf endpoint becomes the left bound, which is the exact false-pruning shape this PR is meant to fix.
Final Verdict

Needs one more regression test for the const / variable divide branch before the fix is fully proved.

LLVM Coverage Report

Measured on commit d3b9acd.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.10% -0.10%

Changed lines: Changed C/C++ lines covered: 19/19 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Sep 6, 2026
INSERT INTO t_monotonicity_nan VALUES (-inf), (1), (2), (3);

SELECT 'a stored -inf endpoint mapped to NaN by the transform';
SELECT count() FROM t_monotonicity_nan WHERE k / inf = 0;

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.

This covers the variable / constant divide case, but the new guard also changes the separate const / variable branch. Please add one focused regression such as WHERE inf / k = inf over (1), (2), (3), (inf): after KeyCondition applies the decreasing transform it inverts the range, so a transformed NaN max becomes the left bound, which is the same false-pruning shape this PR is fixing.

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.

🕵 Good catch, and you are right that the guard changes the const / variable branch too — inf / k over a range ending at +inf gives a decreasing transform whose NaN max becomes the left bound after inversion, which is the same false-pruning shape.

This PR had already merged by the time I got here, so I added the coverage in a follow-up: #119461 (test 05182_arithmetic_monotonicity_nan_const_dividend). It pins WHERE inf / k = inf over (1), (2), (3), (inf) as you suggested, plus const * variable (0 * k) and each pruning layer on its own. Verified with controls against a binary built from current master: with the guard, EXPLAIN indexes = 1 reports Granules: 100/100 and the query returns all matching rows, while a finite constant dividend (100 / k > 2) still prunes to Granules: 49/100.

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d3b9acd40 with master 8201c8238 (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

17 object files changed (+96.15 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/divide.cpp.o 10.16 MiB 10.21 MiB +48.61 KiB (+0.47%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/multiply.cpp.o 7.83 MiB 7.88 MiB +47.55 KiB (+0.59%)

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

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

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +32.7 s (+7%) in total before that adjustment.

Job report

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

First of all, the current behavior is not incorrect - we allow implementation specific behavor on NaN even when it is not consistent among different implementations.

But after these changes, it is more consistent, and the changes don't harm.

@alexey-milovidov alexey-milovidov self-assigned this Sep 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 7, 2026
Merged via the queue into master with commit c05a7cb Sep 7, 2026
342 of 344 checks passed
@alexey-milovidov
alexey-milovidov deleted the arithmetic-monotonicity-nan-endpoint-118121 branch September 7, 2026 17:04
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
UberDever pushed a commit to UberDever/ClickHouse that referenced this pull request Oct 9, 2026
```sql
CREATE TABLE t (x Float64) ENGINE = MergeTree ORDER BY x;
INSERT INTO t VALUES (-inf), (1), (2), (3);

SELECT x / inf AS n FROM t ORDER BY n;         -- nan, 0, 0, 0
SELECT x / inf AS n FROM t ORDER BY n LIMIT 2; -- nan, 0
```

No `NaN` is in the data or in the query: the key holds `-inf` and the `ORDER BY`
expression turns it into one. The read-in-order match asks for monotonicity with
Null endpoints (`matchTrees` passes empty fields), `divide` by a positive
constant answers "monotonically increasing", so the forward read of the key is
kept - while the transformed value of the `-inf` row sorts last, and nothing
sorts the stream afterwards.

The check added in ClickHouse#118468 declines when a concrete endpoint maps to `NaN`, and
cannot fire here because the endpoints are unknown. So the constant itself is
examined: `divide`/`multiply` of a `Float` result by `0`, `±inf` or `NaN` can
turn a legal input into `NaN` (`±inf / ±inf`, `0 * ±inf`), and only those
constants can, so an ordinary `x / 2` still reads in order.

Closes: ClickHouse#118472

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov added a commit to raimannma/ClickHouse that referenced this pull request Oct 11, 2026
The `NaN`-endpoint guard added in ClickHouse#118468 declines `divide`/`multiply`
monotonicity for both operand orders, but `05113_arithmetic_monotonicity_nan_endpoint`
only exercised `variable / const`. The `const / variable` branch has its own
false-pruning shape: for `inf / k` over a range whose right end is `+inf` the
transform is decreasing, so `KeyCondition` inverts the range and the
transformed `NaN` becomes the left bound.

Verified against the current binary with positive and negative controls: with
the guard, `EXPLAIN indexes = 1` for `inf / k = inf` reports `Granules: 100/100`
and the query returns all matching rows, while a finite constant dividend
(`100 / k > 2`) still prunes down to `Granules: 49/100`.

Related: ClickHouse#118468

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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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

2 participants