Repository navigation
Conversation
When a row has NULL in every WITH FILL key, FillingTransform cannot tell which side of that row the fill range belongs on. FillingRow compares with Field semantics, in which a NULL is unordered, while the ORDER BY gives it a definite position through nulls_direction. Three sites therefore get "unordered" as the answer, and the generated row is emitted after the NULL, emitted twice, or dropped, so the result violates its own ORDER BY. For a Nullable fill column with a sorting prefix the stray row lands in the same chunk as the rows around it, and DISTINCT in order above the fill then trips `Equal values are not contiguous within the range assumed to be sorted` in ColumnNullable::getEqualRangeEndAssumeSorted. In a release build the same stream is returned as wrong results: a duplicated row that survives SELECT DISTINCT, and the row promised by the FROM bound missing. The fix adds FillingRow::isNullsLast, a pure accessor over nulls_direction, and consults it at the three sites that have to place a pending generated row: the new-range preamble, the row loop, and generateSuffixIfNeeded. The one overloaded condition in generateSuffixIfNeeded is split into the three questions it was actually answering, so the empty-result-set case from ClickHouse#30888 is asked explicitly through a new parameter instead of through the next_row.isNull() proxy it had been borrowing. FillingRow.cpp is deliberately untouched. Making its comparison nulls_direction aware was tried and rejected: a NULL inside the filling row is ambiguous between "this key has no FROM" and "a copied real NULL value", and disambiguating it needs per-position set/unset state. Making FillingStep stop advertising preserves_sorting was also rejected, because it removes the assert but leaves the wrong output, which reproduces with no DISTINCT and no UNION at all. Found by Stress test (amd_debug) on ClickHouse#110321, STID 2508-4384: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110321&sha=42e6fb428c3380e4904795ba4e6136c94dc0a23c&name_0=PR&name_1=Stress%20test%20%28amd_debug%29 Related: ClickHouse#114352 Known gap, pending a design decision: with two or more fill keys, a row whose keys are all NULL can have partial-NULL rows sorting between it and where the pending row is placed, so the row loop change can move a pre-existing stray row from the end-of-stream chunk into a checked chunk. Measured in 2 of 192 two-key shapes; single-key and non-Nullable shapes are unaffected.
The previous commit applied the fix to any number of WITH FILL keys. Measured over 288 generated WITH FILL shapes on both a pristine and a fixed debug build, that scope repaired 20 mis-ordered outputs but turned 2 of the 24 two-key all-NULLS-LAST shapes from a silent mis-ordering into `Equal values are not contiguous within the range assumed to be sorted` in debug builds, which is the very exception this change exists to remove. The placement question is only decidable for one fill key. With one, a row's fill keys are either all real or all NULL, so the all-NULL rows form a single block at one end of the range and a generated row belongs immediately before it under NULLS LAST. With two or more there is a third class, rows holding a real value in some keys and NULL in others, which sorts strictly between the two, and no condition at these three sites can place a generated row relative to a class the comparison cannot order. The 2 regressions are exactly that: the row loop placed the pending row immediately before the all-NULL row, which is after a partial-NULL row that sorts earlier. So all three conditions are now gated on isSingleNullsLastFillKey, and FillingRow::isNullsLast is reverted: with a whole-row flag it has no caller, and FillingRow is untouched again. The gate is two-sided and exact. Where it is false each site is textually what it was before either commit, so those inputs are unchanged by construction; where it is true the three sites behave exactly as the previous commit made them. Measured on the same 288 shapes: 275 byte-identical to master, all 13 differences inside the single-key NULLS LAST slice, 10 mis-ordered outputs repaired, none newly mis-ordered and none newly raising the exception. The 24 in-scope shapes are byte-identical between the two scopes, so nothing the previous commit fixed for a single fill key is lost. The cost is the 10 two-key improvements the wider scope also bought. Gating only the row loop was rejected: it would keep some of them with no measured regression, but it needs two different scopes at three sites in one function and leaves the multi-key half safe only by measurement rather than inert by construction. Two or more fill keys, NULLS FIRST, and STALENESS are therefore unchanged from master, and are listed in the pull request description. Co-Authored-By: Claude Opus 5 <[email protected]>
`02562_with_fill_nullable` set `optimize_distinct_in_order = 1` and then asserted only the result rows. The setting requests the optimization, nothing asserted it was applied. `DistinctStep::transformPipeline` picks `DistinctSortedStreamTransform` only when the distinct sort description is non-empty, and otherwise falls back silently to the hash-based `DistinctTransform`, which deduplicates without looking at the stream. That stream check is what this file most needs to keep. A stream `(0,1) (0,2) (0,\N) (0,1) (1,1) (1,2) (1,\N)`, one row re-emitted and none dropped, reduces under `DistinctTransform` to exactly the six reference rows in the reference order, so the test would stay green while `DistinctSortedStreamTransform` raises the `Equal values are not contiguous` logical error on the non-contiguous `(0,1)`. Assert the transform with `EXPLAIN PIPELINE` wrapped in a subquery, so the assertion does not depend on the plan text layout. The comment above the query is also corrected: the order-sensitive reference does check that the generated rows are sorted, what needs both the subquery and the setting is the contiguity check on the underlying stream. The assertion is live rather than vacuous: it returns 1 with `optimize_distinct_in_order = 1` and 0 with `optimize_distinct_in_order = 0`, under both `enable_analyzer = 1` and `enable_analyzer = 0`.
…ey is defaulted
`isSingleNullsLastFillKey` decided the `NULLS LAST` placement from the fill
description alone, but `FillingTransform` only builds a sorting prefix when
`use_with_fill_by_sorting_prefix` is set. With the setting off, an `ORDER BY`
key that precedes the fill key is an ordinary column, so `insertFromFillingRow`
gives a generated row that key's default value instead of the original row's.
That key is the first sort key, so it decides the generated row's position
before the fill key is consulted, and relocating the row to a fill-key-correct
place can then violate the full `ORDER BY`.
Measured on
SELECT toInt32(number) - 2 AS p, number % 2 ? NULL : toNullable(toInt32(number)) AS x
FROM numbers(2) ORDER BY p ASC, x ASC NULLS LAST WITH FILL FROM 1 TO 2
SETTINGS use_with_fill_by_sorting_prefix = 0
master returns the sorted `(-2,0), (-1,NULL), (0,1)`, while the earlier commits
on this branch returned `(-2,0), (0,1), (-1,NULL)`, with `p` running -2, 0, -1.
`isSingleNullsLastFillKey` now also requires that no `ORDER BY` key precede the
fill key when the sorting prefix is not built, which makes every such site
textually equal to master again. Over the 24-cell
`use_with_fill_by_sorting_prefix = 0` sweep this trades 6 of the 12 `UNSORTED`
to `clean` repairs back for zero rightward transitions: the 6 that remain are
the ones with no preceding key, and all 12 cells that do have one become
byte-identical to master. Queries with the setting at its default are
unaffected, since the new condition is a disjunction on it.
Copying a preceding key's value into generated rows instead is precisely what
`use_with_fill_by_sorting_prefix = 0` opts out of, so that is deliberately not
done here.
…rder `DISTINCT` Two gaps in `02562_with_fill_nullable`, both of which let a real regression pass. `isNullPlacementDecidable` returns true when the sorting prefix is built, when `ORDER BY` is empty, or when the fill key is the first sort key. Only the first of those three was exercised: cases 1 to 3 run at the default `use_with_fill_by_sorting_prefix = 1`, where the first disjunct short-circuits, and case 4 pins the predicate being false by placing `p` ahead of the fill key. Deleting the third disjunct therefore left the whole file green while every query that has the setting off and the fill key first silently reverted to the old, wrongly ordered output. The new case is that query. It returns `0, 1, 2, NULL` here and `0, 2, NULL, 2` both on master and with the disjunct deleted, so it pins the repaired behaviour rather than the pre-existing one. The `EXPLAIN PIPELINE` assertion collapsed two `DistinctStep`s into `count() > 0` over rows matching `DistinctSortedStreamTransform`. That is satisfied by the upper stage alone, so if only the lower stage, the one sitting on `FillingTransform`, degraded to the hash `DistinctTransform`, the hash stage would drop the non-contiguous duplicate before the sorted stage could see it: no abort, the six result rows unchanged, and the assertion still green with the bug present. It now requires that no hash stage exist anywhere in the pipeline, which is equivalent to every stage being the in-order one because `DistinctStep::transformPipeline` emits `DistinctSortedStreamTransform` when `distinct_sort_desc` is non-empty and `DistinctTransform` otherwise, and this query builds no `IN` or `JOIN` set for `CreatingSetsStep` to add one. Asserting a stage count instead would pin an unrelated planner detail, and `EXPLAIN PIPELINE` may render repeated processors collapsed, so a row count is not a reliable proxy for one. Co-Authored-By: Claude Opus 5 <[email protected]>
The predicate no longer only asks whether there is a single `NULLS LAST` fill key: it also requires that the fill key is the key which decides a generated row's position, so that no preceding `ORDER BY` key the row would default can decide it first. The old name misread worst at the `current_value.isNull() ? ... : less(...)` site, where it said "if the value is `NULL`, insert if there is a single `NULLS LAST` fill key", which is not the condition being tested. The helper's own comment already says "decidable", so the names now follow it. Identifier text only. No condition, comment or signature changes. Co-Authored-By: Claude Opus 5 <[email protected]>
`WITH FILL` fills the half-open range `[FROM, TO)`, and equal bounds are legal:
`PlannerSorting` and `InterpreterSelectQuery` reject only a strictly inverted
range, so `FROM 1 TO 1` parses in both directions and under both analyzers and
must fill nothing.
Of the three sites this branch touches, the new-range preamble in
`FillingTransform::transformRange` is the only one that inserts without asking
whether the filling row still satisfies its constraints: the row loop conjoins
`FillingRow::isConstraintsSatisfied`, and `generateSuffixIfNeeded` returns early
on it. Master never reached the preamble's insert for a `NULL` first value,
because `less(fill_from, NULL, dir)` is always false there: `accurateLess` maps a
Null operand to `isPositiveInfinity` or `isNegativeInfinity`, and a plain SQL
`NULL` is neither. Replacing that arm with `null_placement_decidable` earlier on
this branch made the unguarded insert reachable for the first time, so
SELECT if(number < 100, NULL, toNullable(toInt32(number))) AS x
FROM numbers(2) ORDER BY x ASC WITH FILL FROM 1 TO 1
returned `1, NULL, NULL` here against `NULL, NULL` on master, with the `1`
outside the range the query declared. `ORDER BY x DESC` was the same defect,
since `DESC` defaults to `NULLS LAST`.
The `NULL` arm now conjoins `FillingRow::isConstraintsSatisfied`, which also
makes the three sites consistent. `null_placement_decidable` guarantees a single
fill key, and at size 1 that accessor reduces to true when `fill_to` is unset and
to `less(row[0], fill_to, dir)` otherwise, so `TO 1` no longer inserts while
`TO 3` and a missing `TO` are unchanged. Exactness is preserved: when
`null_placement_decidable` is false the arm is false, which is what master's
`less(fill_from, NULL, dir)` always returned.
The non-`NULL` arm's insert stays unguarded. It is pre-existing and behaves
identically on master, where `x = [5]` with `FROM 1 TO 1` also emits `1, 5`, so
guarding it would change output for existing queries and is left alone.
Co-Authored-By: Claude Opus 5 <[email protected]>
`02562_with_fill_nullable` had no case with an empty `[FROM, TO)` range, so neither of its oracles could see a row inserted outside the declared range. The order-sensitive reference cannot: under `NULLS LAST` a spurious `1` ahead of the trailing `NULL` rows is itself in order, so nothing about the row ordering is violated. The `EXPLAIN PIPELINE` assertion cannot either, since it pins only which `DISTINCT` transform runs. The two new queries use `FROM 1 TO 1`, one `ASC` and one `DESC`, over the file's existing all-`NULL` `Nullable(Int32)` idiom. Both return the two `NULL` rows and nothing else. Dropping `FillingRow::isConstraintsSatisfied` from the preamble's `NULL` arm makes both emit a leading `1` and reddens the file, while the five pre-existing cases stay green, because they use `TO 3` or `TO 2`, where that conjunct is true. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: one residual, already noted in the description
💡 Fixed before publishing: the fix was narrowed from any number of fill keys to one, because the |
|
Workflow [PR], commit [8fdf5e9] Summary: ❌
AI ReviewSummaryThis PR narrows the Missing context / blind spots
Final Verdict✅ No new inline review findings to post. The current head addresses the discussed upper-bound regression, and the remaining risk is limited to missing functional CI evidence rather than a code-level defect I can point to. LLVM Coverage ReportMeasured on commit 8fdf5e9.
Changed lines: Changed C/C++ lines covered: 45/45 (100.00%) · Uncovered code |
|
cc @yariks5s @davenger, could you review this? |
|
I traced both new insert sites end to end and the fix is sound for its claimed scope: the headline One behavior change looks undisclosed and worth a decision before merge. With Minor, no action needed: |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 14 s compile time in total, 8 of them have a recent master baseline. |
`FROM` without `TO` (and without `STALENESS`, which validation rejects together with `FROM`) leaves `FillingRow` with no constraint at all, so `isConstraintsSatisfied` is vacuously true and the two `NULL` arms added by this pull request emitted the bare `FROM` row in front of a trailing `NULL`: rows `[0, NULL]` with `ORDER BY x ASC WITH FILL FROM 1` returned `0, 1, \N` instead of `0, \N`, and `[NULL, NULL]` returned `1, \N, \N` instead of `\N, \N`. An omitted `TO` makes the sequence of filling use the maximum `expr` field value from `ORDER BY`, and a `NULL` is never that value, so the range is empty and no row belongs in it. The same input without the trailing `NULL` already emits no `FROM` row, so whether that row exists must not depend on a `NULL` being present. `hasSomeConstraints` is the existing test for a real upper bound, already paired with `isConstraintsSatisfied` in `generateSuffixIfNeeded`. Require it in the two `NULL` arms as well; the non-`NULL` arms keep their previous conditions exactly. Reported by zlareb1.
|
Reproduced both shapes on the head and against a master build: Your reading of the cause is right, and one more control makes it decisive: the same input without the trailing Agreed on the two minor points, and I left both as they are: the raw sort description can only deny decidability, and the interpolation source follows from where the insert happens. Verification: 24-test |
CI finish ledger - 8fdf5e9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
That red carries the assertion this PR exists to remove, so the attribution needs measurement rather than a The second line is the control: the null direction is the only difference between the two, and it is what SELECT if(number < 7, NULL, toInt32(number)) AS x FROM numbers(1)
ORDER BY x ASC NULLS FIRST WITH FILL FROM 1 TO 3;
-- both builds: 2, \N, 2 (1 dropped, 2 repeated around the NULL)
Session id: cron:clickhouse-maint-slot-14:20260903-200600 |
|
Fixing PR for the ledger row above: #118096 It covers the |
Related: #110321
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
ORDER BY ... WITH FILLover aNullablecolumn with a singleNULLS LASTfill key, where that key either comes first inORDER BYoruse_with_fill_by_sorting_prefixis enabled (the default): when a row heldNULLin that key, a generated row could be emitted after thatNULLinstead of before it, be emitted twice, or be dropped, which made the result violate its ownORDER BYand could raiseEqual values are not contiguous within the range assumed to be sortedinDISTINCT-in-order.Description
Found by
Stress test (amd_debug), STID2508-4384. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110321&sha=42e6fb428c3380e4904795ba4e6136c94dc0a23c&name_0=PR&name_1=Stress%20test%20%28amd_debug%29FillingRowcompares fill values asFields, where aNULLis unordered, while theORDER BYpositions it throughnulls_direction. All three sites inFillingTransformthat place a pending generated row therefore read "unordered", andgenerateSuffixIfNeeded'snext_row.isNull()disjunct, added for the empty-result-set case, covers for them: right underNULLS FIRST, wrong underNULLS LAST.Wrong results in a release build, with no
DISTINCTorUNION:I supply the missing direction at those three sites, scoped to a single
WITH FILLkey that no defaultedORDER BYkey precedes - the only decidable case: with two or more keys a partial-NULLrow sorts strictly between the all-real and all-NULLrows, so neither side of the latter is its place.Measured over 288 generated
WITH FILLshapes on pristine and fixed debug builds: 275 byte-identical, 10 mis-orderings repaired, none newly mis-ordered or aborting. The same rebuilds show both scope exclusions load-bearing - dropping the single-key conjunct re-aborts two two-key shapes - so the test pins only what this PR changes; say if you want the exclusions pinned too.Left unchanged from master, each still able to raise the same exception under
DISTINCT-in-order: two or more fill keys;NULLS FIRST, whereFillingRow::findBorderreads aNULLnext value as "no border" and fills past it; anduse_with_fill_by_sorting_prefix = 0with anORDER BYkey ahead of the fill key, whose default a generated row takes.STALENESSis only partly repaired:FillingRow::shiftis untouched, so its mis-ordering and the exception remain.How often this message is seen (CIDB)
The assertion text is a coarse bucket spanning about 15 distinct failure signatures, so the sub-family that actually carries a
WITH FILLquery is the useful count:Without the
WITH FILLpredicate the same 30 days give 208 rows / 175 PRs / 8 master rows, i.e. mostly unrelated mechanisms. The reported signature itself, STID2508-4384, has 2 rows in 90 days and none on master: PR 108129AST fuzzer (amd_debug, targeted, old_compatibility)on 2026-07-02 and this report on 2026-08-31.Workflow [PR]
Sync PR [sync-upstream/pr/117832]