Repository navigation
Conversation
…aults a sort key `FillingStep::getTraits` declared `.preserves_sorting = true` unconditionally. That is false for part of the `WITH FILL` input space. `FillingTransform` classifies every header column that is not a fill column, not an `INTERPOLATE` result and not in the filling sorting prefix as an "other" column, and each generated row writes `insertDefault` into those. The sorting prefix is built only from `ORDER BY` entries ahead of the first fill key, and only while `use_with_fill_by_sorting_prefix` is on. So a non-fill `ORDER BY` key at or after the first fill key, and with that setting off every non-fill key, receives a default value interleaved among real ones while the stream is still advertised as ordered by it. `applyOrder` has no `FillingStep` branch, so it propagated the full `sort_description` above the step on the strength of that trait and installed it into `DistinctStep`. `DISTINCT` in order then ran `DistinctSortedStreamTransform` over a stream that is not sorted: `getEqualRangeEndAssumeSorted` binary-searches a range that is not monotonic, which trips `Equal values are not contiguous within the range assumed to be sorted` in debug and sanitizer builds, and in a release build silently resets the per-range hash table so a key that recurs non-contiguously is emitted twice. Compute the trait from the descriptions the step already owns instead of hardcoding it: sorting survives filling exactly when every `ORDER BY` entry outside the sorting prefix is itself filled. Both construction sites already pass `sort_description` and the setting, so no call site changes and both analyzers are covered by the one constructor. `DistinctStep`, `TotalsHavingStep` and `WindowStep` already take this shape of conditional `getTraits` in the same directory. Measured on `SELECT DISTINCT i, s` over `ORDER BY i ASC WITH FILL, s ASC, d ASC WITH FILL`: a debug build at the base commit aborts, the official 26.9.1.664 release build returns 3 rows where 2 are correct, and a debug build with this change returns the correct 2 rows. Shapes whose order does survive filling keep `DistinctSortedStreamTransform`, so the optimization is not withdrawn from `WITH FILL` generally; the new test asserts that in both directions. Co-Authored-By: Claude Opus 5 <[email protected]>
… key The previous commit's `sortingIsPreserved` required every `ORDER BY` entry from the end of the filling sorting prefix onward to be filled, and its message stated the rule as "sorting survives filling exactly when every `ORDER BY` entry outside the sorting prefix is itself filled". That rule is one clause too strict, and this commit corrects both it and that claim. A generated row's fill tuple is strictly between those of its two neighbours: `transformRange` inserts only while `FillingRow::next` keeps the row below the next real one, starting from the previous row's values. So any comparison that involves a generated row is already decided at a filled key and never reaches a key positioned after the last filled one. Two real rows whose filled values are equal get no generated row between them, so their trailing keys still order them. The order therefore breaks only for a non-filled key that some filled key follows, which is when the odometer can leave the earlier filled keys equal and the comparison walks into the defaulted key. `00995_order_by_with_fill.reference` records this: `ORDER BY date WITH FILL, val` stays ordered by `(date, val)` even though every generated row defaults `val`. Scan only up to the last filled entry. The stricter form withdrew `DISTINCT` in order from `ORDER BY <k> WITH FILL, <ordinary>`, where the trait is false, `applyOrder` propagates nothing and `DistinctStep` picks `DistinctTransform`. When every `DISTINCT` column is in the sort prefix, `DistinctSortedStreamTransform` builds no hash table at all, so `max_rows_in_distinct` and `max_bytes_in_distinct` are never charged, while the hash transform charges every row. A query with a bounded `max_bytes_in_distinct` that succeeds today would have started throwing `SET_SIZE_LIMIT_EXCEEDED`. The predicate values are unchanged for the two broken shapes and the three shapes that stay ordered; only the trailing-key shape moves, from false to true. Test block `E` pins it, and reverting just this narrowing flips that block while leaving the other five alone. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review❌ "the trait still says preserved for an all-filled
💡 The sensitivity controls are deliberate: the test also fails against a blanket Session id: cron:clickhouse-review-slot-10:20260904-111100 |
|
Workflow [PR], commit [8fdbe95] Summary: ✅
AI ReviewSummaryThe change limits the sorting information propagated across Findings❌ Previously reported correctness findings — deferred to separate fixes
Both threads are already resolved by a maintainer. Neither was reopened or replied to, and no new inline review was submitted. Missing context / blind spots
Final VerdictStatus: ✅ Approve No additional code changes requested for this PR. The remaining producer defects have explicit follow-up fixes; the full CI suite must still complete before merge. |
|
cc @antaljanosbenjamin @yariks5s, could you review this? |
Build profile diff (arm_release)Commit See the job log for details. |
…g the whole order `preserves_sorting` is a single `bool`, so returning `false` for a shape like `ORDER BY i WITH FILL, s, d WITH FILL` also discarded the order by `i`, which no generated row can default. `DistinctStep` narrows the propagated description to the `DISTINCT` columns, so `SELECT DISTINCT i` over that shape lost `DistinctSortedStreamTransform` and fell back to `DistinctTransform`. The hash transform charges `max_bytes_in_distinct` against its own hash table where the sorted transform hashes nothing, so a query that used to succeed started throwing `SET_SIZE_LIMIT_EXCEEDED`. `applyOrder` now truncates the propagated description to the keys ahead of the first defaulted one rather than discarding it. Measured on a 2000 row fixture with `max_bytes_in_distinct = 1024`: master and this build return 1999 rows, the previous commit throws with 32 KiB charged. The trait itself still reports `false`, so every other consumer keeps the conservative answer. Block `A` therefore keeps the sorted transform as well, over the prefix `i` alone; `A2` stays the oracle for `s` being left out of it. Block `F` covers the limits regression.
The previous commit filtered the preserved prefix through `getCollationAwareSortPrefixInColumns`. That helper deliberately stops at a collated column, which is right for a consumer that needs equal values to be adjacent, such as `DISTINCT` or `LIMIT BY`, and wrong for the general sorting property: filling copies the sorting prefix into generated rows unchanged, so a collated prefix key keeps its collated order and an outer sort over the same prefix is still avoidable. Those consumers apply the helper themselves, so propagating the collated key does not reach them unfiltered. The prefix is now taken positionally from the description the input actually advertises, truncated at the first key whose name does not match the filling description, so nothing is invented when the two descriptions disagree. Measured with `EXPLAIN PIPELINE` on `ORDER BY s COLLATE 'en', i WITH FILL, t, d WITH FILL` wrapped in an outer `ORDER BY` over the same keys, counting `MergeSortingTransform`: master 1, previous commit 2, this commit 1. With `optimize_sorting_by_input_stream_properties = 0` every build reports 2, which is why block `G` pins it: `clickhouse-test` randomizes that setting, and without the pin the block failed 20 of 50 randomized runs. It now passes 50 of 50. `getPreservedSortPrefixSize` replaces the `Names` accessor, and its comment no longer claims the keys it counts are never defaulted: for a trailing ordinary key they are, and the order survives because an earlier filled key decides the comparison first.
The collation control added in the previous commit builds a `Collator`, and Fast test configures with `-DENABLE_LIBRARIES=0` without re-enabling ICU, so the block would throw `SUPPORT_IS_DISABLED` there rather than exercise the optimizer. `04312_in_order_optimizations_with_collation.sql` carries the same tag for the same reason.
CI finish ledger - d0517a6Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
My merged #113941 is deliberately not linked as the owner here, because its fix is present in the Session id: cron:our-pr-ci-monitor:20260904-220000 |
|
cc @devcrafter @nihalzp, could you review this? |
…rt key The same false `preserves_sorting` trait of `FillingStep` that broke `DISTINCT` in order also turned the sort of a window, and of an outer `ORDER BY` on the same keys, into a merge-only `FinishSorting` over an unsorted stream. The window then found peer groups on unsorted input: debug and sanitizer builds abort in `assignPeerGroupIndexes` with `Equal values are not contiguous within the range assumed to be sorted` (STID 2508-31ed, Stress test (amd_msan), found on PR 111166), and the official 26.10.2.103 and 26.3.33.24 builds return wrong `rank()` values and rows out of order. The trait fix in this PR already restores both sorts; these cases pin them. Both cases pin `optimize_sorting_by_input_stream_properties = 1`, which the test runner randomizes; at 0 the sort is never converted and the cases cannot fail. Co-Authored-By: Claude Opus 5.5 <[email protected]>
master enables clang-tidy `modernize-use-nodiscard` with warnings as errors; every other const getter of `FillingStep` is marked. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the FillingStep prefix comment to two lines and the applyOrder FillingStep comment to one line; no code change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
DISTINCT results with WITH FILL when a generated row defaults a sort keyWITH FILL when a generated row defaults a sort key
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex) plus my own review, 2 rounds. Round 2 (head
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261116-142600 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20261116-122500 |
… key as sorted
`WITH FILL` computes generated values of a float key in `Float64` and only rounds
them when inserting into the column. For a `Float32` or `BFloat16` key a generated
value can therefore round onto an original value (e.g. `0.30000000000000004` becomes
the original `Float32` `0.3`), so the generated row no longer differs from its
neighbours on that key and its defaulted later keys break their order. Such a key now
ends the prefix `FillingStep` reports as sorted, so an outer `ORDER BY`, a window or
`DISTINCT` above it still sorts the later keys.
On 26.10.2.103, `SELECT x, s FROM (SELECT * FROM values('x Float32, s String', (0, 'a'),
(0.3, 'a')) ORDER BY x WITH FILL STEP 0.1, s DESC) ORDER BY x, s DESC` returns
`(0.3, '')` before `(0.3, 'a')`; `optimize_sorting_by_input_stream_properties = 0`
returns the correct order, as does this commit. Reported by the automated review.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
WITH FILL when a generated row defaults a sort keyWITH FILL when a generated row breaks the order of a later sort key
…ITH FILL precedes a fill key A generated row holds the default value in an ORDER BY key that is neither filled nor in the sorting prefix. Filling inside a group past `TO` therefore breaks the order when such a key precedes a fill key, e.g. `values (3,5,0),(3,5,3) ORDER BY i WITH FILL TO 1, g, k WITH FILL` returned (3,5,0),(3,0,1),(3,0,2),(3,5,3) and `SELECT DISTINCT i, g` over it returned a duplicate (a debug build aborts). Without `TO` the same rows are generated on master; that is the sort-order contract ClickHouse#118077 repairs. The decision whether `FillingRow::next` compares a key with the next row's value is now made once in the `FillingTransform` constructor, which knows the whole ORDER BY: no Nullable or floating-point fill column, no FROM, and no such key before the last fill key (the rule ClickHouse#118077 uses for the sort order FillingStep keeps). This replaces the per-call loop over the fill columns and the `FillColumnDescription::fill_column_nullable` field. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The fix looks right to me. The two open threads are real, but as you say, they are bugs in
After that the threads can be resolved, and the full CI can run. It has not run on Optional nits:
|
…test Review feedback on ClickHouse#118077: the comment above the `FillingStep` branch now states what is propagated and why collated keys stay in the prefix (`DISTINCT` and `LIMIT BY` take their prefix through `getCollationAwareSortPrefixInColumns`, which drops collated keys). Case G is the only part of 05076 that needs ICU, so it moves unchanged to 05076_with_fill_collated_sorting_prefix and the rest of 05076 loses its `no-fasttest` tag and runs in Fast test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The two open threads were opened by clickhouse-gh, and I leave those for the bot to resolve (it resolves its own once it accepts the reply, #130279), so they need the bot or you. Until then the review-threads gate keeps CI on the new head limited; resolving them re-runs it. Both nits are in 8fdbe95: the |
Related: #115611
Related: #117832
Related: #132176
Related: #132201
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results of
SELECT DISTINCT, window functions and an outerORDER BYover a subquery withORDER BY ... WITH FILLwhen generated rows break the order of a laterORDER BYkey: a non-filled key gets a default value (two or moreWITH FILLkeys separated by an ordinary key, oruse_with_fill_by_sorting_prefix = 0), or a generatedFloat32orBFloat16value rounds onto an existing one. Debug and sanitizer builds aborted withEqual values are not contiguous within the range assumed to be sorted.Description
FillingStep::getTraitsdeclared.preserves_sorting = trueunconditionally, butFillingTransformwrites a default into every
ORDER BYkey that is neither filled nor in the filling sorting prefix, sothe stream is not ordered by such a key when a filled key follows it.
applyOrdertrusted it, soDISTINCTin order emitted a recurring key twice, and the sort of a window orof an outer
ORDER BYon the same keys became aFinishSortingthat sorts nothing.The trait is now computed from the step's own descriptions and is false exactly for that shape, and
applyOrderpropagates only the keys ahead of the first defaulted one, which stay ordered. AFloat32orBFloat16fill key also ends that prefix: fill values are computed inFloat64, so a generated value canround onto an original one.
Not fixed here, as the inner query alone is already unsorted: the
FillingRowbugs of #132176 and #132201,and
NULLS FIRST(02562_with_fill_nullable.sql:4; #118096, #118109).On the official 26.10.2.103 and 26.3.33.24 builds,
SELECT DISTINCT i, soverORDER BY i ASC WITH FILL, s ASC, d ASC WITH FILLreturns 3 rows instead of 2, andrank()overORDER BY o, number WITH FILLwithuse_with_fill_by_sorting_prefix = 0ranks two equal rows 5 and 8.The base debug build aborts on both; this change returns the 2 rows and ranks both 5.
Found by CI, STID 2508-39b4 (
DISTINCT) and 2508-31ed (window):https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117158&sha=a4c12651618693c3d4a6dbc7e8981e99bbbdd2c7&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111166&sha=aff63ba936924eab2b71e8213f70c87fd5f481fc&name_0=PR&name_1=Stress%20test%20%28amd_msan%29
Workflow [PR]
Sync PR [sync-upstream/pr/118077]