Repository navigation
Decide read-in-order NaN placement from the direction the key is read in - #118469
Conversation
`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]>
|
Workflow [PR], commit [1e2620c] Summary: ✅
AI ReviewSummaryThis PR moves the Final Verdict
|
Build profile diff (arm_release)Commit 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]>
|
The AST fuzzer failure on this PR ( 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 Happy to fix that separately if you want it in this PR. |
…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]>
…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]>
…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]>
|
There's a slightly related PR - #106588 |
…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]>
|
🕵 Thanks @jh0x. #106588 overlaps here: both change the |
|
🕵 @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 ( The other red job, |
|
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 The current head |
…adInOrder.cpp` The merge with master left the header included twice, which fails `clang-tidy` with `readability-duplicate-include`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118469&sha=fd162deb9a0439f68599c6f20080ec93d425922e&name_0=PR&name_1=Build%20%28arm_tidy%2C%204%2F4%29 #118469 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Both already have fixes.
|
|
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. |
|
@alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
optimize_read_in_order(on by default) returned rows in the wrong order - and wrong rows underLIMIT-when the
ORDER BYexpression was a monotonically decreasing function of aFloatsorting key that holdsNaN: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_directionbefore that direction was known, which is only correct for a monotonically increasingmatch:
ORDER BY negate(x)is served by a backward read, which surfaces the NaNs first whileASC NULLS LASTwants 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 FIRSThere, 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 samedirection-aware check; that path never had even the original
nulls_directionguard, so it was wrong for aplain
ORDER BY x ASC NULLS FIRSTon aFloatkey too. It also does not foldsorting_key_reverse_flagsinto the direction it matches with at all -
matchSortDescriptionAndKeycompares against the key as if everycolumn ascended, and
ReadFromMergeTreeapplies the flag once more when it builds the sort description ofthe stream it advertises - so a key column declared
DESCis 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 = 0withSETTING_CONSTRAINT_VIOLATION(the analyzer is mandatory since v26.9), so the fix cannot be covered by afunctional 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 arejection is the conservative outcome: no read-in-order or aggregation-in-order, instead of a wrong order.
The guard looks through
LowCardinality: aLowCardinality(Float64)key (allowed withallow_suspicious_low_cardinality_types) holds itsNaNs 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 appliesa hard
LIMITto - past the advertised prefix. This rollback is defensive bookkeeping: a control binary withonly those three restores removed answers identically, because
order_key_prefix_descris pushed after theplacement check (so the advertised prefix never contained the rejected key) and
used_prefix_of_sorting_key_sizeis not printed byEXPLAINin either the text or the JSON form. The testdoes pin the advertised prefix for that shape (
Prefix sort description: a ASC).00940_order_by_read_in_order_query_planand its analyzer twin02911_analyzer_order_by_read_in_order_query_planpinned one of the wrong matches - a read-in-order prefixfor
ORDER BY (a + b) * c DESC, intDiv(sin(a / b), -2)over the key((a + b) * c, sin(a / b)), whosesecond column holds a
NaNfor the test's own data (sin(0 / 0)) - so their references are updated to theprefix that stops before it.
Closes: #117980
Related: #101838
Changelog category (leave one):
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 whenORDER BYis a monotonically decreasing function of a
Floatsorting key containingNaN, 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 insteadof being sorted.
Workflow [PR]
Sync PR [sync-upstream/pr/118469]
Version info
26.10.1.2352-master(included in26.10and later)