Skip to content

Fix ORDER BY WITH FILL emitting a generated row before an original row that sorts earlier - #132201

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-with-fill-reset-keys-order
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-with-fill-reset-keys-order

Conversation

@groeneai

@groeneai groeneai commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118077 (comment)

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 into CHANGELOG.md):

Fixed ORDER BY ... WITH FILL with several fill keys emitting a generated row before an original row that sorts earlier, or emitting it twice, when a later fill key restarts from its FROM value. Such a row is now emitted after that original row or not at all.

Description

On 26.10.3.7 this query returns (1, 2, 1) before (1, 1, 2), violating its own ORDER BY:

SELECT * FROM values('i Int64, j Int64, k Int64', (0, 0, 1), (1, 1, 2))
ORDER BY i WITH FILL, j WITH FILL FROM 2, k WITH FILL FROM 1;

An outer ORDER BY i, j, k keeps that order: its sort is elided. With a third input row it is emitted twice.

When FillingRow::next (or FillingRow::shift for STALENESS) advances a key onto the next original row, it resets the later keys to FROM and inserts the row if ANY later key is less than the next row's. The row is now refused when it equals the next row up to the advanced key and the first later key that differs is not less.

The change only stops emitting rows: a refused row stays pending and is emitted after the original row, or dropped when nothing follows (as for a single key's FROM above the data), and a generated row identical to the next original row is no longer emitted. Every other row is decided as before, also when the deciding key is NULL or NaN. Unchanged: NULLS FIRST on a later fill key (#118096 fixes one key) and a non-fill key between fill keys (#118077).

Validation: the new test fails on master in the five bug cases and keeps master's output for an empty FROM = TO range, a NaN under DESC and an earlier key at its TO. The 115 existing WITH FILL tests pass. A randomized A/B sweep against master (4,431 multi-key shapes, TO on any key, empty FROM = TO ranges) and a NaN grid found no new ordering or duplicate violation and no row master does not emit.

🤖 Generated with Claude Code


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

groeneai and others added 5 commits November 16, 2026 22:13
…w that sorts earlier

When `FillingRow::next` advances a fill key onto the value of the next
original row, it resets the later keys to their `FROM` values (or to the
next row's values for keys without `FROM`) and decides whether to insert the
row. It accepted the row if ANY later key was less than the next row's, an
OR over the keys instead of a lexicographic comparison. For

    SELECT * FROM values('i Int64, j Int64, k Int64', (0, 0, 1), (1, 1, 2))
    ORDER BY i WITH FILL, j WITH FILL FROM 2, k WITH FILL FROM 1

the reset row (1, 2, 1) has j = 2 > 1 but k = 1 < 2, so it was emitted
before (1, 1, 2), and an outer ORDER BY over it returned the same rows
because the input is advertised as sorted. Inserted while still greater
than the previous original row, the same row was then inserted again by the
pending-row placement at the next original row (a duplicate).
`FillingRow::shift` (the STALENESS prefix path) has the identical block.

Both now call one helper, `resetKeysAfter`, which keeps the assignments and
the per-key test and lets the first key that differs from the next original
row decide; a row equal to it is not less. This only refuses rows: a refused
row is placed by the existing pending-row logic after the original row, or is
not emitted when nothing follows (like the `FROM` row of a single key above
the data). Also no longer emitted: a generated row identical to the next
original row (`Nullable` keys, NULL equals NULL), and one whose deciding key
equals its exclusive `TO` (`FROM 2 TO 2`).

Related: ClickHouse#118077 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… do not sort first

The previous commit replaced the OR over the reset keys by the decision of
the first differing key alone. That also refused rows that sort before the
next original row when the deciding key has an empty `FROM = TO` range
(the constraint conjunct), which master inserts in order and continues
from. The fill cursor then stayed at the refused row, and the next gap
added rows master never emits, e.g. (1, 2, 2) after (1, 3, 2) for

    SELECT * FROM values('i Int64, j Int64, k Int64', (0, 0, 1), (1, 3, 2), (1, 3, 5))
    ORDER BY i WITH FILL, j WITH FILL FROM 2 TO 2, k WITH FILL FROM 1

Now the original OR decides as before and the row is additionally refused
when it does not sort before the next original row (first differing later
key decides), so every accepted row is one master accepts too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ecides the order

The previous commit refused a reset row whenever its first differing later key
was not less than the next original row's. `less` orders NaN by direction only,
while the sort places it by `NULLS FIRST/LAST` (last by default, for both
directions), so a row that sorts first was dropped, e.g. (1, 0, 1) for

    SELECT * FROM values('i Int64, j Float64, k Int64', (0, 0, 0), (1, nan, 2))
    ORDER BY i WITH FILL, j DESC WITH FILL FROM 0, k WITH FILL FROM 1

It also ignored the keys before the advanced one, which can already make the row
sort first (a key at its `TO`, or a NULL marker).

Now the row is refused only when it equals the next original row up to the
advanced key and the first differing later key is a non-NULL, non-NaN value that
is not less; every other row is decided as before. The test gains two blocks
pinned to the existing output: an empty `FROM = TO` range and a NaN under `DESC`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test gains a block where a key before the advanced one sits at its `TO`, so the row sorts first by that key and
master's decision is kept. The declaration comment of `resetKeysAfter` states the NULL/NaN exception.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the resetKeysAfter header comment to two lines (now also states the all-equal refusal) and drop the duplicated contract from the .cpp comment, keeping only the NULL/NaN ordering invariant.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 8 findings over four rounds) plus my own cold review.

# Sev Finding Verdict Evidence / action
1 ❌ A reset row refused because its deciding key has an empty range (FROM 2 TO 2) stays the fill cursor, behind the original row just emitted AGREE, fixed @ 3ea7be9 Such a row sorts first, so the old decision is kept for it. (0,0,1),(1,3,2),(1,3,5) returns exactly what 26.10.3.7 returns; the test pins (0,0,1),(1,3,2)
2 ⚠️ NaN on a later DESC key: less puts NaN first under DESC, the sort puts it last, so a row sorting first was refused AGREE, fixed @ 5cf78d0 A NULL or NaN deciding key keeps the old decision; (0,0,0),(1,nan,2) with j DESC WITH FILL FROM 0 returns what 26.10.3.7 returns (test block). The 3-row variant the model gave already misorders on 26.10.3.7
3 ⚠️ The test did not cover the kept old decision AGREE, fixed @ 5cf78d0 Two blocks added (empty range, NaN under DESC), each fails on the design it guards
4 ❌ NULLS FIRST on a later fill key: a reset row is still placed before a NULL DISAGREE Identical on 26.10.3.7. Needs the pending-row comparator too (FillingRow::operator< skips NULL keys): the multi-key part of the class #118096 leaves unchanged; stated in the description
5 ❌ A non-fill sort key between fill keys (ORDER BY i WITH FILL, s DESC, j WITH FILL FROM 1) DISAGREE Generated rows carry defaults for non-fill columns; 26.10.3.7 misorders the same way with no FROM and no reset. Consumer side: #118077
6 💡 A key before the advanced one differs from the next row (at its TO): a row sorting first by that key could be dropped AGREE, fixed @ 5cf78d0 Such a row keeps the old decision
7 ⚠️ The test did not cover a key before the advanced one deciding the order AGREE, fixed @ 4da5901 Test block added: (1,0,5,5),(5,1,0,1) with i WITH FILL TO 1 returns what 26.10.3.7 returns; it fails on the earlier variant that decided by the later keys only
8 💡 The declaration comment omitted the NULL/NaN exception AGREE, fixed @ 4da5901 Comment states it
9 💡 The declaration comment does not mention that a row equal to the next row in every key is refused AGREE, fixed @ d426cb4 Comment states it

Also noticed, not in this PR (separate code, unchanged): a fill key sitting at its TO is treated as finished even when the next original row is past TO, so later keys are filled behind a row already emitted (values (0,2,0),(0,3,5),(0,3,8) ORDER BY i WITH FILL, j WITH FILL TO 2, k WITH FILL on 26.10.3.7).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The five queries of the new test fail on every master run (no randomness), e.g. ORDER BY i WITH FILL, j WITH FILL FROM 2, k WITH FILL FROM 1 over (0,0,1),(1,1,2) returns (1,2,1) before (1,1,2); same on official 26.10.3.7.
b Root cause explained? FillingRow::next / shift reset the keys after the advanced one to their FROM values and accept the row if ANY of them is less than the next original row's (an OR, not a lexicographic comparison). The row is then inserted before a smaller original row and, still pending, inserted again at the next one.
c Fix matches root cause? Yes. Master's decision is kept; it is overridden only when the row equals the next original row up to the advanced key and its first differing later key (non-NULL, non-NaN) is not less, so a reset row is no longer inserted before an original row it does not sort before. No guard, no setting.
d Test intent preserved / new tests added? New stateless test, eight blocks: five bug shapes (ASC, STALENESS, DESC, Nullable, duplicate) that fail on master, and three that pin master's output for the guarded classes (an empty FROM = TO range, a NaN under DESC, an earlier key at its TO). The 115 existing WITH FILL tests pass unchanged.
e Both directions demonstrated? Yes. Same queries on the master binary (wrong order / duplicates) and the fix binary (sorted, no duplicates); 50/50 randomized runs of the new test pass.
f Fix is general across code paths? Both copies (next, shift) use one helper. The other insertion paths decide at a key that is already strictly less. A different pre-existing defect (a preamble row with an unset key placed by FillingRow::operator<, different trigger, in FillingTransform.cpp) is not changed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? Randomized A/B sweep of 4,431 shapes (2-5 keys, ASC/DESC, STEP 1/2, FROM/TO/STALENESS, TO on any key, empty FROM = TO ranges, Nullable keys with NULLs): no new ordering or duplicate violation, no lost input row, no row master does not emit. A 96-query NaN grid (ASC/DESC x default/NULLS FIRST/NULLS LAST): 90 identical to master, the other 6 only drop the reset row master emits out of order. max_block_size = 1 gives identical output.
h Backward compatible? (maintainer-approved exception only) The change only stops emitting rows (fix output is a sub-multiset of master's on every sweep shape): only a reset row that equals the next original row up to the advanced key and whose first differing later key is not less is refused; every other row is decided as on master. No setting or format change.
i Invariants and contracts preserved? Return contract of next / shift unchanged (false with value_changed = true already happens for a reset row equal to the next row); the same keys get the same assignments; per-key NULL and constraint tests unchanged.

Session id: cron:clickhouse-impl-self-slot-57:20261117-021403

@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d426cb4]

Summary: ✅


AI Review

Summary

PR #132201 fixes out-of-order and duplicate generated rows when later WITH FILL keys reset, sharing the comparison logic between FillingRow::next and FillingRow::shift. Reviewed head d426cb45717ad4492be7804559df78138029e843, its callers, regression coverage, and prior discussion; no actionable findings. Independently ran the eight-block regression against the PR-head fast-test binary: output matches the reference exactly. All 16 additional variants passed ordering, input-row preservation, and duplicate checks across ascending/descending order, STALENESS, suffix bounds, and max_block_size = 1.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d426cb457 with master 81c9f0701 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

9 translation units recompiled, 25 s compile time in total, 9 of them have a recent master baseline.

Job report

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 17, 2026
With FROM on a fill column the change of the first commit made results
unsorted where master returns them sorted. It lets the later columns be
filled inside a group whose earlier key is past its TO, and there the reset
of the following columns to their FROM can put the filling row behind an
original row (the defect fixed separately in ClickHouse#132201):
- over (3,0,0,1),(3,1,1,2),(3,1,2,3) `ORDER BY i WITH FILL TO 1, j WITH FILL,
  k WITH FILL FROM 2, l WITH FILL FROM 1` it returned (3,1,2,1) before
  (3,1,1,2), and `SELECT DISTINCT i, j, k` over it aborted a debug build;
- over (0,0,0,1),(2,-3,2,0),(2,1,0,3) `ORDER BY a WITH FILL TO 0 STEP 2
  STALENESS 3, b WITH FILL STEP 4, c WITH FILL FROM 0 TO 0, d WITH FILL TO 2`
  the STALENESS reset left c at its FROM 0 and it returned (2,-3,0,1) after
  (2,-3,2,0).
Both were found by the AI review on the PR. A fill column with FROM now keeps
the previous comparison like a Nullable or floating-point one.

Also measured a narrower alternative that changes only a key exactly at its
TO and keeps the early return for a key past it: it returns 25 of 18000
random cases unsorted that master returns sorted (the walk of the later
columns then starts from a filling row left behind by that early return), so
it was not used.

Measured over random 2-4 key cases (Int64, random ASC/DESC, TO, FROM, STEP,
STALENESS, a sorting prefix; Nullable(Int64) with NULLs; Float64 with
inf/-inf/nan), output sorted under the ORDER BY and every input row present,
30000 cases: none is unsorted where master is sorted; every case with a FROM,
a Nullable or a floating-point column (13063) is identical to master; the
unsorted master results without them (plain 173/3000, STEP 109, STEP with
STALENESS 64, sorting prefix 37) are all sorted now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Manerone Manerone self-assigned this Nov 24, 2026

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants