Repository navigation
Conversation
`ORDER BY <nullable column> NULLS FIRST WITH FILL` returned rows violating its own ORDER BY: generated rows landed in front of the NULLs, one of them was emitted twice with a NULL between the copies, the FILL FROM row was dropped, and with no FILL FROM nothing was generated at all. A DISTINCT-in-order consumer then read a range the plan had declared sorted, so a release build silently mis-deduplicated and a debug or sanitizer build raised `Logical error: 'Equal values are not contiguous within the range assumed to be sorted'`. `FillingRow` compares fill values as `Field`s, and `accurateLess` is false in both directions when either side is `Null`, so a NULL is unordered for every comparison the fill machinery makes even though `nulls_direction` gives it a definite position. Three consequences chained in `FillingTransform::transformRange`: `FillingRow::findBorder` returned the `fill_to` constraint for a NULL next value, reading it as "no upper border", so the range was generated ahead of a row that sorts before all of it and the suffix re-emitted the last generated row; the per-row `should_insert_first` compared against a NULL previous row and was therefore false, leaving the pending FILL FROM row unplaced; and the preamble anchored the range on the NULL, and an all-NULL `filling_row` makes `FillingRow::next` return false unconditionally. Under NULLS LAST all three are correct or unreachable. The fix adds `isNullPrefixSkippable` plus three guarded sites in `transformRange`, one per consequence: with a single fill key, `nulls_direction != direction` and no STALENESS, a range's NULL rows are a prefix that no generated row precedes, that does not anchor the range, and after which the pending FILL FROM row is placed. `FillingRow` and `generateSuffixIfNeeded` are untouched and no new insert site is added, so INTERPOLATE is inherited from the existing insert rather than duplicated. Shapes the predicate excludes are byte-identical to before, measured. Removes the `-- TODO: NULLS FIRST does not work correctly with FILL.` line added in 8c9be17 on 2023-02-09, which this resolves. Found by the AST fuzzer, STID 2508-4384: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117832&sha=8fdf5e908157268bcf5d47b49555f0c00c85a86f&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 ClickHouse#117832 Co-Authored-By: Claude Opus 5 <[email protected]>
Under NULLS FIRST the documented sort order is NULL, then NaN, then other
values (docs/reference/statements/select/order-by.mdx). Field comparison
disagrees: accurateLess hardcodes nan_direction_hint = 1 and never consults
nulls_direction, so a NaN compares above every ordinary value and
Field::isNaN is not Field::isNull. The previous commit's prefix test asked
only isNull, so for a Nullable(Float64) fill key holding {NULL, NaN, 5} with
FILL FROM 1 TO 3 the generated row 1 was inserted between the NULL and the
NaN, giving NULL, 1, NaN, 2, 5 instead of NULL, NaN, 1, 2, 5.
The prefix predicate now covers NULL or NaN at all four decision points, and
the insert site gets an explicit guard against placing a generated row before
a prefix row. That guard used to be supplied only as a side effect of
FillingRow::operator< returning false against a Null, which does not hold for
a NaN. Field::isNaN is type-guarded on Types::Float64, so for an integer,
Date, DateTime64 or Decimal fill key the predicate is exactly isNull and the
change is inert; a 27-shape matrix covering every fixed and every deliberately
excluded shape is byte-identical before and after, including the NULLS LAST
rows whose byte-identity is what proves this change cannot interact with the
NULLS LAST half.
The regression test's DISTINCT block now uses the shape the AST fuzzer
actually reported, a fill key that is NULL on every row, so the claim that a
generated row was emitted twice has an assertion behind it: before the fix
that query returns 2, NULL, NULL, 2 and after it NULL, NULL, 1, 2. This also
covers the row placer for that shape, which is a different code path from the
one the other blocks exercise.
…x rows
Adds the fourth guarded site, in generateSuffixIfNeeded. When every row of a
range is a NULL-or-NaN prefix row, the three in-range placers are all correctly
blocked, so nothing sets filling_row_inserted and the pending FILL FROM row
survives to the suffix. There should_insert_first tests only next_row.isNull(),
and a NaN is not a Null (Field::isNaN requires Types::Float64, isNull requires
Types::Null), while FillingRow::operator< gives nan < 1 == false. Both existing
disjuncts are therefore false and the generated row is dropped:
SELECT * FROM values('x Nullable(Float64)', (nan), (NULL))
ORDER BY x ASC NULLS FIRST WITH FILL FROM 1 TO 3
returned NULL, nan, 2 - losing the 1 - and now returns NULL, nan, 1, 2.
The && !filling_row_inserted conjunct is required, not symmetry with the
neighbouring disjunct. The range preamble inserts the FILL FROM row whenever
less(fill_from, current_value, direction) holds, and accurateLess(1.0, NaN) is
true, so a range whose FIRST row is a NaN reaches the suffix with the flag
already set by insertFromFillingRow. Measured without the conjunct, that shape
emits the generated row twice: values('x Nullable(Float64)', (nan)) with the
same clause gives 1, nan, 1, 2 instead of 1, nan, 2.
The suffix disjunct only widens should_insert_first, which is computed before
and consumed after the unchanged hasSomeConstraints/isConstraintsSatisfied
gate, so it cannot insert a row that violates a constraint; and it requires
!isNullPrefixRow(filling_row), so filling_row always holds an ordinary value
when it fires.
Also in the test: block 2 now uses the AST fuzzer's own two-group shape, which
keeps an all-NULL fill key (the reported CI signature) while still aborting a
debug build without the fix - the single-group all-NULL form does not abort, so
it would have traded the abort oracle away. Two statements pin the NaN
generalisation, one per placer path; before them, reverting the NaN half of the
prefix predicate left the test green.
isNullPrefixField's header said "False for every non-float type", which is
false for the whole function: isNull is type-agnostic, only the isNaN half is
type-scoped.
…mit guard
Two test statements. `src/` is unchanged by this commit.
The first pins the anchoring site. With no `FILL FROM` the range preamble stores
the first row's value in the filling row, so for a range whose prefix is a `NaN`
the filling row holds that `NaN` and `FillingRow::next` refuses to advance,
dropping every generated row in the range. The anchor re-seeds the filling row
from the first ordinary value, so `values('x Nullable(Float64)', (7), (3), (nan))`
`ORDER BY x ASC NULLS FIRST WITH FILL` goes from `nan 3 7` to `nan 3 4 5 6 7`.
Both pre-existing `NaN` statements carry `FILL FROM`, which leaves the filling
row holding the bound, so that site never fired with a `NaN` anywhere in the
file. An arm restricting it to `FillingRow::isNull` reddens the new statement
alone, and dropping `Field::isNaN` from the prefix predicate now reddens three
statements instead of two.
The second pins the `filling_row_inserted` guard on the suffix disjunct with a
row count rather than a full output. Its blocking branch is reachable only for
an all-`NaN` range with `FILL FROM`, and every such range also carries the
pre-existing misplacement of the `FILL FROM` row in front of a leading `NaN`, so
a full-output reference would record an ordering that is known to be wrong. The
count is three under that ordering and under any corrected one, and four without
the guard.
Internal second-model reviewTwo blockers fixed, both about A third round added missing coverage rather than code: with no
💡 Not pinned: a value below |
|
Workflow [PR], commit [21ce424] Summary: ❌
AI ReviewSummaryThis PR fixes the Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit 21ce424.
Changed lines: Changed C/C++ lines covered: 49/50 (98.00%) · Uncovered code |
|
cc @yakov-olkhovskiy @Michicosun, could you review this? |
| if (running_with_staleness) | ||
| return false; | ||
|
|
||
| return use_with_fill_by_sorting_prefix || sort_description.empty() |
There was a problem hiding this comment.
null_prefix_skippable is computed from the raw sort_description_, but the transform later drops leading sort keys that are not in the header. That still leaves the old wrong-result path reachable for supported shapes like ORDER BY 10 ASC, x ASC NULLS FIRST WITH FILL FROM 1 TO 3 SETTINGS enable_positional_arguments = 0, use_with_fill_by_sorting_prefix = 0: the literal 10 cannot affect ordering, yet it keeps this predicate false, so transformRange treats the leading NULL as unordered again and emits generated rows before it. This needs to key off the effective sort description (or otherwise ignore no-header constant keys) rather than the raw parser list.
There was a problem hiding this comment.
Ran it. The shape is real and pre-existing; the mechanism and the suggested fix are not.
It is unchanged by this PR: over (NULL), (2) that query prints 2 \N 2 on this head and byte-identically on its merge base, and it is the residual the description lists (use_with_fill_by_sorting_prefix = 0 with a key ahead of the fill key). At the default use_with_fill_by_sorting_prefix = 1 the same query is \N 1 2, so the boundary is that setting, not the constant.
Nothing drops the constant key. With WITH FILL present the planner materializes every ORDER BY column (PlannerExpressionAnalysis.cpp:539-542), so it arrives as an ordinary non-const column named 10_UInt8, and that name is in the transform's input header: EXPLAIN json=1 gives the step's sort description as 10_UInt8, __table1.x and EXPLAIN header=1 gives the same two names. deduplicateSortDescription only drops names absent from the header, so it keeps this one.
The suggested fix is therefore inert, measured rather than argued: I built the arm that decides from the effective description (isNullPrefixSkippable(sort_description, ...)) and its output is byte-identical to this head on the repro and on five controls, repro still 2 \N 2.
What does cover the shape is dropping the "fill key is the first sort key" condition, and that moves the violation instead of removing it. On that arm the repro becomes \N 1 2, but
SELECT p, x FROM values('p UInt8, x Nullable(Int64)', (1,NULL),(1,5),(2,NULL),(2,5))
ORDER BY p, x ASC NULLS FIRST WITH FILL FROM 1 TO 3 SETTINGS use_with_fill_by_sorting_prefix = 0becomes 1 \N / 0 1 / 0 2 / 1 5 / 2 \N / 2 5: with no sorting prefix the generated rows carry p's default and land mid-stream, so p runs 1,0,0,1,2,2 where master's runs 0,1,1,2,2. That is what the condition is guarding, so widening it is a scope decision for that residual, with its own tests and changelog, not a correction to this guard.
One point in your favour: the repro does not need enable_positional_arguments = 0. A constant spelled 'k' or 10+0 reaches it at default settings, so only use_with_fill_by_sorting_prefix = 0 is required.
Michicosun
left a comment
There was a problem hiding this comment.
NULLS FIRST WITH FILL looks like a non-combining feature; why do we need to support this case? Can we instead reject it at the parser level?
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, 15 s compile time in total, 8 of them have a recent master baseline. |
|
@Michicosun Two questions in one, so let me take them separately, with measurements. Is it non-combining? It is a documented surface that is already exercised. Can it be rejected at the parser level? Only by syntax, because the parser has no types: SELECT x FROM values('x Int64', (1), (5)) ORDER BY x ASC NULLS FIRST WITH FILL FROM 1 TO 4;
SELECT x FROM values('x Int64', (1), (5)) ORDER BY x ASC WITH FILL FROM 1 TO 4;It would also turn both tests above into syntax errors. Consistently with that, all 37 sites raising If you would rather reject than fix, the type-aware place is one of those stages: refuse |
CI finish ledger - 0934b44Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Not PR-caused, so nothing here is owed by this change. #117832's fix is measurably absent from this The two Session id: cron:our-pr-ci-monitor:20260904-200000 |
The `new_sorting_prefix` preamble in `transformRange` inserts the `FILL FROM`
row whenever `less(fill_from, current_value, direction)` holds. `Field`
comparison places a `NaN` above every value, while under `NULLS FIRST` a `NaN`
sorts below them, so the preamble emitted a generated row in front of a range
that starts with a `NaN`:
SELECT * FROM values('x Nullable(Float64)', (nan))
ORDER BY x ASC NULLS FIRST WITH FILL FROM 1 TO 3;
-- returns 1, nan, 2 expected nan, 1, 2
Guard that insertion with the prefix predicate the other sites already use.
Skipping the insertion leaves `filling_row_inserted` false, so the pending
`FILL FROM` row is still placed: by the guard in the row loop once the first
ordinary value arrives, or by `generateSuffixIfNeeded` when the range holds
prefix rows only.
`isNullPrefixSkippable` now also declines a bound that is not a finite number.
Such a bound reaches the filling row the way a prefix row does, so the range
re-anchored to its first ordinary value and then filled against a border the
bound never gives: `FILL FROM nan` over `{3, 7}` returned `3, 4, 5, 6, 7`
instead of `3, 7`, and `{nan, 3, 7}` under `FILL TO nan` or `FILL TO inf`, which
returned `nan, 3, 7`, generated rows until the memory limit. A non-finite bound
now keeps the whole path off, so those queries are left exactly as they were.
The last statement of `05060_with_fill_nulls_first` asserted `count()`, which
cannot see row order and stayed at 3 in both directions. It now asserts the full
output, plus a leading `NaN` followed by a value in a `Nullable` and in a plain
`Float64` column, two ranges opening with an ordinary value, and the four
non-finite bounds. Every guard fails on its own: reverting the preamble guard
moves the three `NaN` rows, dropping `filling_row_inserted` doubles a generated
row, and dropping either half of the bound check regenerates the `FROM nan`
rows, truncates `FROM inf`, or reaches the query memory limit under `TO nan` and
`TO inf`.
CI finish ledger - 21ce424Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Not PR-caused, re-measured on this head after the The two Session id: cron:our-pr-ci-monitor:20260908-143101 |
Related: #117832
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results for
ORDER BY ... NULLS FIRST WITH FILLover a column holdingNULLorNaNvalues. Generated rows were emitted before theNULLs or aNaNinstead of after them, one of them was emitted twice, theFILL FROMrow was dropped, and withoutFILL FROMno rows were generated at all.Description
ORDER BY <nullable column> NULLS FIRST WITH FILLviolates its ownORDER BY:NULLS FIRSTputs theNULLs at the head of the range, so no generated row precedes them. ADISTINCT-in-order consumer then reads a range the plan declared sorted, so a release build silentlymis-deduplicates and a debug build raises
Logical error: 'Equal values are not contiguous within the range assumed to be sorted'.Root cause.
FillingRowcompares fill values asFields andaccurateLessis false in bothdirections against
Null, so aNULLis unordered for the fill machinery even thoughnulls_directiongives it a definite position; five consequences chain in
FillingTransform.The change adds one predicate and guards the placement and anchoring decisions this makes wrong: with a single fill key,
NULLS FIRSTand noSTALENESS, a range's leadingNULLs are aprefix that generated rows follow and that does not anchor the range.
NULLS FIRSTsorts aNaNnext tothe
NULLs (order-by.mdx), so aNaNjoins that prefix, including when it opens the range, where theFILL FROMrow preceded it. Every repro in the test fails on master; five further statements pin theplan shape and the guards. It resolves the TODO in
8c9be17b915402f.Still unchanged: two or more fill keys;
use_with_fill_by_sorting_prefix = 0with a key ahead of the fillkey;
STALENESS; a non-finite bound, which keeps the path off (#118122); and an+/-infinityrow,where generation stops there in any null direction. Independent of #117832, whose sites are gated on
nulls_direction == directionand mine on the negation.Found by
AST fuzzer (amd_debug, targeted), STID2508-4384:https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117832&sha=8fdf5e908157268bcf5d47b49555f0c00c85a86f&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
Workflow [PR]
Sync PR [sync-upstream/pr/118096]