Skip to content

Decide read-in-order NaN placement from the direction the key is read in - #118469

Merged
alexey-milovidov merged 16 commits into
masterfrom
read-in-order-nan-direction-117980
Oct 14, 2026
Merged

alexey-milovidov merged 16 commits into
masterfrom
read-in-order-nan-direction-117980

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

optimize_read_in_order (on by default) returned rows in the wrong order - and wrong rows under LIMIT -
when the ORDER BY expression was a monotonically decreasing function of a Float sorting key that holds
NaN:

CREATE TABLE t (x Float64) ENGINE = MergeTree ORDER BY x;
INSERT INTO t VALUES (1), (2), (nan), (3);

SELECT negate(x) AS n FROM t ORDER BY n;          -- nan,-3,-2,-1   (wrong)
SELECT negate(x) AS n FROM t ORDER BY n LIMIT 2;  -- nan,-3         (wrong rows)
SELECT negate(x) AS n FROM t ORDER BY n SETTINGS optimize_read_in_order = 0;  -- -3,-2,-1,nan

A part stores such a key with its NULLs and NaNs at one physical end, and reading the part cannot move them,
so whether the requested order is satisfiable depends on the direction the key is read in. The guard tested
nulls_direction before that direction was known, which is only correct for a monotonically increasing
match: ORDER BY negate(x) is served by a backward read, which surfaces the NaNs first while ASC NULLS LAST wants them last, and the elided sort never repairs the placement.

The check moves to the end of the iteration, where the monotonicity of the match has been applied, and
compares the position the read produces with the one the query asks for. That also lifts the restriction in
the other direction, for the order a backward read does satisfy exactly: ORDER BY negate(x) ASC NULLS FIRST
(values ascending, NaNs first) is now read in order instead of sorted. (The issue names DESC NULLS FIRST
here, but that one asks for descending values with the NaNs first, which neither read direction produces, so
it stays sorted.)

The same placement rule is missing from the legacy ReadInOrderOptimizer, so it gets the same
direction-aware check; that path never had even the original nulls_direction guard, so it was wrong for a
plain ORDER BY x ASC NULLS FIRST on a Float key too. It also does not fold sorting_key_reverse_flags
into the direction it matches with at all - matchSortDescriptionAndKey compares against the key as if every
column ascended, and ReadFromMergeTree applies the flag once more when it builds the sort description of
the stream it advertises - so a key column declared DESC is rejected there outright, for every key type,
until that optimizer can model the flags.

This optimizer is no longer reachable from SQL: master refuses enable_analyzer = 0 with
SETTING_CONSTRAINT_VIOLATION (the analyzer is mandatory since v26.9), so the fix cannot be covered by a
functional test and the test's legacy section was removed rather than left asserting that error. What remains
are the internal users of the old interpreter (MutationsInterpreter, ProjectionsDescription), where a
rejection is the conservative outcome: no read-in-order or aggregation-in-order, instead of a wrong order.

The guard looks through LowCardinality: a LowCardinality(Float64) key (allowed with
allow_suspicious_low_cardinality_types) holds its NaNs at a physical end just like a plain one.

Because the check now runs after the iteration consumed the key, a rejection gives the key back, so a
rejected key does not widen used_prefix_of_sorting_key_size - the width the storage reads with and applies
a hard LIMIT to - past the advertised prefix. This rollback is defensive bookkeeping: a control binary with
only those three restores removed answers identically, because order_key_prefix_descr is pushed after the
placement check (so the advertised prefix never contained the rejected key) and
used_prefix_of_sorting_key_size is not printed by EXPLAIN in either the text or the JSON form. The test
does pin the advertised prefix for that shape (Prefix sort description: a ASC).

00940_order_by_read_in_order_query_plan and its analyzer twin
02911_analyzer_order_by_read_in_order_query_plan pinned one of the wrong matches - a read-in-order prefix
for ORDER BY (a + b) * c DESC, intDiv(sin(a / b), -2) over the key ((a + b) * c, sin(a / b)), whose
second column holds a NaN for the test's own data (sin(0 / 0)) - so their references are updated to the
prefix that stops before it.

Closes: #117980
Related: #101838

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 wrong result order (and wrong rows under LIMIT) from the read-in-order optimization when ORDER BY
is a monotonically decreasing function of a Float sorting key containing NaN, e.g. ORDER BY negate(x).
The opposite request for the same shape, ORDER BY negate(x) ASC NULLS FIRST, is now read in order instead
of being sorted.


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

Version info

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

`optimize_read_in_order` returned rows in the wrong order - and wrong rows under `LIMIT` - when the
`ORDER BY` expression was a monotonically decreasing function of a `Float` sorting key that holds `NaN`:

    CREATE TABLE t (x Float64) ENGINE = MergeTree ORDER BY x;
    INSERT INTO t VALUES (1), (2), (nan), (3);

    SELECT negate(x) AS n FROM t ORDER BY n;          -- nan,-3,-2,-1
    SELECT negate(x) AS n FROM t ORDER BY n LIMIT 2;  -- nan,-3

A part stores such a key with its NULLs and NaNs at one physical end, and reading the part cannot move
them, so whether the requested order is satisfiable depends on the direction the key is read in. The
guard tested `nulls_direction` before that direction was known, which is only correct for a
monotonically increasing match: `ORDER BY negate(x)` is served by a backward read, which surfaces the
NaNs first while `ASC NULLS LAST` wants them last, and the elided sort never repairs the placement.

The check moves to the end of the iteration, where the monotonicity of the match has been applied, and
compares the position the read produces with the one the query asks for. That also lifts the mirror
restriction: `ORDER BY negate(x) DESC NULLS FIRST`, which a backward read satisfies exactly, is no
longer rejected.

`00940_order_by_read_in_order_query_plan` and its analyzer twin
`02911_analyzer_order_by_read_in_order_query_plan` pinned one of the wrong matches - a read-in-order
prefix for `ORDER BY (a + b) * c DESC, intDiv(sin(a / b), -2)` over the key `((a + b) * c, sin(a / b))`,
whose second column holds a `NaN` for the test's own data (`sin(0 / 0)`) - so their references are
updated to the prefix that stops before it.

Closes: #117980

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 [1e2620c]

Summary: ✅


AI Review

Summary

This PR moves the NULL/NaN read-in-order eligibility check to the point where the optimizer already knows the physical read direction, rolls back consumed key state when that check rejects a later key, and extends the guard through LowCardinality. I re-checked the current diff against the resolved discussion threads and do not see any remaining contract violations or missing bug-fix evidence in the current code.

Final Verdict
  • Status: ✅ Approve

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

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 1e2620c67090b2a00592798d22d09eac19d18dd2 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

The order the lifted restriction makes readable in order is `ASC NULLS FIRST`, not `DESC NULLS FIRST`:
for a decreasing function of the key, a backward read yields the values ascending with the NaNs first.
`DESC NULLS FIRST` asks for descending values with the NaNs first, which neither read direction gives,
and the test now says so and keeps asserting the sorted answer for it. The new case also pins that the
readable one is in fact read in order.

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

Copy link
Copy Markdown
Member Author

The AST fuzzer failure on this PR (Logical error: 'Equal values are not contiguous within the range assumed to be sorted' for the mutated query SELECT DISTINCT negate(x) AS n FROM remote('127.0.0.{4..6}:9000', currentDatabase(), 't_read_in_order_nan__fuzz_2') ORDER BY n DESC NULLS FIRST) is a pre-existing bug that the new test table exposed to the fuzzer, not something this change introduces. It is in optimize_distinct_in_order, and it is independent of read-in-order:

CREATE TABLE t (x Float64) ENGINE = MergeTree ORDER BY x;
INSERT INTO t VALUES (1), (2), (nan), (3);

SELECT DISTINCT negate(x) AS n FROM t ORDER BY n DESC NULLS FIRST;
-- -1 -2 -3 nan   (wrong: NULLS FIRST asks for the nan first)

SELECT DISTINCT negate(x) AS n FROM t ORDER BY n DESC NULLS FIRST SETTINGS optimize_read_in_order = 0;
-- -1 -2 -3 nan   (same, so read-in-order is not the cause)

SELECT DISTINCT negate(x) AS n FROM t ORDER BY n DESC NULLS FIRST SETTINGS optimize_distinct_in_order = 0;
-- nan -1 -2 -3   (correct)

Without DISTINCT the same query answers nan -1 -2 -3 on this branch (the test pins it), and a plain SELECT DISTINCT x FROM t ORDER BY x DESC NULLS FIRST is correct too, so the defect needs a monotonic function of the key plus DISTINCT in order. Over remote() the same shape additionally returns duplicates on both settings of optimize_read_in_order, which is what the debug build turns into the logical error above.

Happy to fix that separately if you want it in this PR.

alexey-milovidov and others added 2 commits September 11, 2026 13:48
…s it

The check runs after the iteration consumed the key, so a rejected key still
widened `next_sort_key`, which becomes
`InputOrderInfo::used_prefix_of_sorting_key_size` - the width the storage reads
with and applies a hard `LIMIT` to - while the advertised prefix stopped at the
previous key. Undo the consumption before breaking.

Also see through `LowCardinality` when deciding whether the guard applies: a
`LowCardinality(Float64)` sorting key (allowed with
`allow_suspicious_low_cardinality_types`) holds its `NaN`s at a physical end
just like a plain `Float64` one, and `isFloat` of the outer type said no, so
`ORDER BY negate(x)` over such a key kept the original wrong order.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Storages/ReadInOrderOptimizer.cpp Resolved
alexey-milovidov and others added 2 commits September 18, 2026 22:25
…mizer

`ReadInOrderOptimizer` never folds `sorting_key_reverse_flags` into the direction it
matches with: `matchSortDescriptionAndKey` compares the request against the key as if
every column ascended, and `ReadFromMergeTree` applies the reverse flag once more when it
builds the sort description of the stream it advertises. The order it advertises then
disagrees with the order the merge upstream assumes - for every type of key, not only for
the `NULL`/`NaN` cases the previous commit guarded. Reject a reverse key column outright
until this optimizer can model the flags.

The test drops its legacy-optimizer section: `enable_analyzer = 0` is now refused with
`SETTING_CONSTRAINT_VIOLATION` ("the analyzer is mandatory since v26.9"), so that path is
no longer reachable from SQL and the queries only pinned the error message. The
`EXPLAIN` assertion asked for on the two-key shape is added instead: the advertised
`Prefix sort description` stops at `a`, the key before the one the placement check
rejects.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Storages/ReadInOrderOptimizer.cpp Resolved
alexey-milovidov and others added 2 commits September 25, 2026 01:11
…irection-117980

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp
…column

The reverse-flag rejection in `ReadInOrderOptimizer::getInputOrderImpl` ran
before the skip of key columns that are constant after filtering, so a key like
`(tenant DESC, event_time)` with `WHERE tenant = '42' ORDER BY event_time` lost
read-in-order. A constant key column does not affect the order, so let the
fixed-column skip handle it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@jh0x

jh0x commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

There's a slightly related PR - #106588

alexey-milovidov and others added 2 commits October 3, 2026 18:27
…irection-117980

Master removed the legacy `ReadInOrderOptimizer` (the setting `query_plan_read_in_order` became obsolete), so the conflicting change to `src/Storages/ReadInOrderOptimizer.cpp` is dropped together with the file.
…decreasing_function_nan`

`clickhouse-test` randomizes `optimize_read_in_order`; with it off the optimized arms compared control with control and the `EXPLAIN` check for `Prefix sort description` failed in every stateless job.
`query_plan_read_in_order` is obsolete on master now, so only `optimize_read_in_order` needs pinning.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118469&sha=latest&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
#118469

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

Copy link
Copy Markdown
Member Author

🕵 Thanks @jh0x. #106588 overlaps here: both change the NaN/NULL placement guard in optimizeReadInOrder.cpp, and this PR also looks through LowCardinality (the LowCardinality(Float64) case is covered by 05114_read_in_order_decreasing_function_nan). Beyond that, this PR decides placement from the direction the key is actually read in, after monotonicity is applied, so it also covers ORDER BY negate(x) over a float key. Whichever of the two is merged first, the other should be rebased onto it. Also, master has since removed the legacy ReadInOrderOptimizer, so the reverse-key issue described in #106588 is gone along with that code path; this branch now merges master and drops its change to that file.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118469&sha=ef55c5e044bada9a471a3d94f9cc2e8c0abf6fa0&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%201%2F2%29 (05237_with_expression_alias_scope_descendant: view 10 / stored alias is bare 0 instead of 100 / 1, under DatabaseReplicated; it failed in about 200 PRs on 2026-10-03 to 2026-10-05) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The other red job, Build (amd_fuzzers) (R_X86_64_PC32 out of range while linking clickhouse_fuzzer), is fixed on master by 8ef38ed, which I merged into this branch.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

The fix is in progress: #123790 (it includes the change from my #123774, closed in its favor). It is not flaky: under a Replicated database the view is re-interpreted from the DDL log and stores nested as <db>.nested, which gives view 10 and stored alias is bare 0. In the run of #123790 on 2a290a03b667, 05237 passes in the arm_binary DBReplicated job.

The current head db9aee40d929 includes the revert #123789, so this arm_binary DBReplicated job does not run on it.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. Confirmed: the current head db9aee40d929 includes the revert #123789, and every CI job on it is green, so 05237_with_expression_alias_scope_descendant no longer affects this PR. The real fix is tracked in #123790.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failures (unrelated to this PR, which only changes the read-in-order NaN placement check): 05210_lightweight_update_materialized_cte_in_ignore (UNKNOWN_TABLE while executing Remote under parallel replicas) https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118469&sha=f00b6209fdd919b1e58f20e3a12fb0b9e6decf83&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29 and test_storage_iceberg_concurrent/test_concurrent_reads.py::test_concurrent_reads (FILE_DOESNT_EXIST for the metadata file on CREATE TABLE) https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118469&sha=f00b6209fdd919b1e58f20e3a12fb0b9e6decf83&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%201%2F4%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. I merged the latest master into this branch in the meantime.

@groeneai

Copy link
Copy Markdown
Collaborator

Both already have fixes.

05210_lightweight_update_materialized_cte_in_ignore: this is the UNKNOWN_TABLE race from #112642 (Unknown table expression identifier '_materialized_cte_c_...'). The fix is #123121 (mine, open). Master still hits it without the fix: 4 failures since 06:45 UTC today, all with the same error.

test_storage_iceberg_concurrent/test_concurrent_reads.py::test_concurrent_reads: fixed by #125448 (mine), merged 2026-10-13 01:47 UTC. This run tested f00b620 merged into master fa58f0f (2026-10-12 23:44 UTC), which does not contain the fix. The signature matches: test_storage_delta/test_writes_interop.py ran earlier on the same xdist worker gw1, and the retry in a fresh pytest session passed. Since the merge, master has 112 passing runs and 1 failure, on 3ab409c, which predates the fix. The current head 1e2620c6709 includes #125448.

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Oct 14, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 14, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Read in order will be inhibited in some cases of queries from a table with a Float primary key. But a workaround is possible - just specify NULLS FIRST or NULLS LAST.

@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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.

Read-in-order optimization returns wrong order (wrong rows under LIMIT) for a monotonically decreasing function of a Float sorting key containing nan

5 participants