Skip to content

Decline divide and multiply monotonicity for a constant that yields NaN - #118720

Merged
alexey-milovidov merged 12 commits into
masterfrom
read-in-order-transform-to-nan-118472
Oct 9, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
read-in-order-transform-to-nan-118472

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Closes: #118472
Related: #118468

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 a wrong order (and wrong rows under LIMIT) from the read-in-order optimization when the ORDER BY expression maps a stored inf to NaN, as in ORDER BY x / inf.

Description

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.

#118468 declines monotonicity when a concrete endpoint maps to NaN; that check cannot fire here, because the endpoints are unknown. So the constant itself is examined now: 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 keeps reading in order.


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

Version info

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

```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 #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: #118472

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

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4b8c55f]

Summary: ✅


AI Review

Summary

This PR narrows divide/multiply monotonicity so optimize_read_in_order no longer treats NaN-producing constant transforms as ordered, while preserving the safe cases for UInt64 keys and finite Float64/BFloat16/Decimal mark ranges that were called out during review. I re-checked the current PR head and the previously resolved review threads; the remaining diff and focused stateless coverage are consistent with the stated bug fix, and I did not find unresolved correctness or regression issues in the current change.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 4b8c55f.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 37/38 (97.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 8, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4b8c55f25 with master 22b04d767 (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

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

Job report

alexey-milovidov and others added 2 commits September 16, 2026 16:49
…g operand's type

The early rejection of `divide`/`multiply` monotonicity for a constant of
`0`, `±inf` or `NaN` keyed off the `Float` result alone, so `UInt64 / inf`
and `UInt64 * 0.` were declined too, although an integer domain has no
`±inf` to turn into `NaN`. Now the constant is matched with the inputs that
reach the `NaN`: `0 / 0` and `±inf * 0` with the constant `±inf` happen at a
zero input, which every numeric domain holds, and remain declined; `±inf /
±inf`, `c / ±inf` and `±inf * 0` with the constant `0` need an infinite
input and are declined only for a `Float` varying operand.

The test now checks the read type through `EXPLAIN PLAN` for both a
`Float64` and a `UInt64` key, and that index analysis keeps the matching
rows.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

This PR only changes how divide and multiply by the constants 0, ±inf or NaN are judged monotonic. That check is used only by read-in-order and primary-key index analysis, and the rest of the diff is a new stateless test. ClickBench Q16 shows +14.0%, but it does not use those expressions, and its 604 ms median is inside the range master itself has recently produced, so it stays not_sure and is not attributed to this change. Two of the PR's ClickBench runs shared one machine, which could explain the small CPU increase on this query. No queries on either benchmark show a performance change caused by this PR.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 530 604 +14.0% <0.0001 aggregation: This is a GROUP BY plus ORDER BY count query with no divide or multiply by a constant, so the monotonicity change does not run here. The 604 ms median sits inside master's recent 519-669 ms range.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: dd4512e9-aeb2-4b9c-8a2f-9e4a951272ca
  • MIRAI run: 0f2f94dd-ad68-4c5f-bbd6-41b0705c1b99
  • PR check IDs:
    • clickbench_13543_1791293989
    • clickbench_13549_1791293988
    • clickbench_13555_1791293989
    • tpch_adapted_1_official_13567_1791293989
    • tpch_adapted_1_official_13578_1791293989
    • tpch_adapted_1_official_13613_1791293989

alexey-milovidov and others added 6 commits September 24, 2026 13:21
`UInt64 / inf` is `0` for every value, so reporting `is_strict = true` let
`optimizeReadInOrder` keep matching later `ORDER BY` terms from the key, e.g.
`ORDER BY x / inf, y` over a key `(x, y)` returned rows in `x` order instead
of `y` order. Mark `variable / ±inf` and `±inf / variable` as non-strict, and
add a two-key regression.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…tant only when the concrete range reaches it

`KeyCondition` passes the bounds of a range of marks to `getMonotonicityForRange`; a closed
range with finite endpoints holds no `±inf`, and one on either side of zero holds no zero, so
`x / inf` over a `Float64` range like `[1, 10]` keeps its monotonicity and its pruning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… a native numeric domain

The `NaN`-producing-constant check compared concrete range endpoints with a numeric `0`. For an `IPv4` key the endpoints are `IPv4` fields, and the comparison threw `Cannot compare long with DB::IPv4` (`BAD_TYPE_OF_FIELD`) during index analysis, failing `04651_intdiv_const_variable_monotonicity_ip` and `04652_intdiv_ip_key_monotonicity` in the Fast test. Use the endpoints only for a native integer or float domain; otherwise assume the range holds zero, which is conservative.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118720&sha=a4cc31ad74918c6831c8d164a57f2ae349e56a7f&name_0=PR&name_1=Fast%20test
#118720

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ecimal` key too

The endpoints of a `Decimal` key are `DecimalField`, which compare with an
integer `0`, so a range away from zero no longer declines the monotonicity of
`0. / x` and keeps pruning granules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Oct 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
Merged via the queue into master with commit ea4b37e Oct 9, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the read-in-order-transform-to-nan-118472 branch October 9, 2026 09:47
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
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