Skip to content

Fix ORDER BY WITH FILL TO generating rows after a NaN or infinite value - #132176

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-with-fill-to-before-non-finite
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-with-fill-to-before-non-finite

Conversation

@groeneai

@groeneai groeneai commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118077

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 wrong results of ORDER BY ... WITH FILL with TO or STALENESS when the data contains an infinite value or, in ascending order, a NaN: generated rows were emitted on the wrong side of that value, so the result and an outer ORDER BY over it were not sorted, and with STALENESS they were dropped.

Description

On 26.10 (official 26.10.3.7), SELECT arrayJoin([0., inf]) AS x ORDER BY x WITH FILL TO 3 returns 0, inf, 1, 2 instead of 0, 1, 2, inf, and an outer ORDER BY x over it returns the same order, because the outer sort trusts the WITH FILL order. The same happens with NaN, with -inf under DESC, with FROM, in a later fill column and with INTERPOLATE; with STALENESS the rows are lost ([0, inf] ... TO 5 STALENESS 3 returns 0, inf).

Root cause. FillingRow::next stops at a NaN or infinite next original value (#90255, the fix of the #69261 hang) even when it steps towards a finite TO or staleness border before that value, so the rows up to the border come after the row, or are dropped with STALENESS. Its stops also returned before the later fill keys were filled.

Change. Stop only when no finite border comes before the non-finite value, and only after the later fill keys are filled. For NaN under DESC NULLS LAST (the DESC default) or ASC NULLS FIRST the old stop stays: the Field comparator orders NaN greatest, its sort position only for ASC NULLS LAST and DESC NULLS FIRST.

Tests. 14 queries appended to 03239_nan_with_fill (13 fail on master; one guards the NaN exception). In 04657_with_fill_bounds_out_of_column_type_range, [0, nan, 5] ... STALENESS 2 now also returns 6, inside the staleness window of 5.

Unchanged (separate defects): after a leading infinity without FROM no rows are generated ([-inf, 0, 3] stays -inf, 0, 3), and under DESC NULLS LAST or ASC NULLS FIRST generated rows are still misplaced around a NaN, because the comparator orders NaN greatest whatever the NULLS order (the NULLS FIRST part is #118096).

Found in review of #118077: #118077 (comment)

🤖 Generated with Claude Code


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

groeneai and others added 3 commits November 16, 2026 21:46
`FillingRow::next` returned early whenever the next original value was NaN
or infinite. ClickHouse#90255 added that to stop the ClickHouse#69261 hang, where the filling
steps forever towards a NaN target with no TO. But the filling steps towards
the border `findBorder` picks, the nearer of the TO/staleness constraint and
the next original value, and when that border is a finite constraint before
the non-finite value the stepping terminates on its own. The early return
generated nothing before such a row, so the rows up to TO were produced after
it (by the suffix, or by the next call in a later fill column), and with
STALENESS the window border was replaced after the row and the rows were lost:

    SELECT arrayJoin([0., inf]) AS x ORDER BY x WITH FILL TO 3
    -- 0, inf, 1, 2 instead of 0, 1, 2, inf

An outer ORDER BY over it returned the same unsorted rows, because it trusts
the order WITH FILL declares.

Keep the early return only when no finite border comes before the value. For
NaN with nulls_direction != 1 (DESC NULLS LAST, ASC NULLS FIRST) it stays as
well: `accurateLess` orders NaN greatest, which is its sort position only for
nulls_direction == 1, so the stepping and its callers misplace it there
(dropping that clause makes [0, nan] NULLS FIRST FROM -1 TO 3 emit 0 twice).

The 04657 case [0, nan, 5] STALENESS 2 now also returns 6, which is inside
the staleness window of 5.

Found in review of ClickHouse#118077.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Both non-finite stops in `FillingRow::next`, for a NaN or infinite cursor
and for a NaN or infinite next original value, returned before the loop that
fills the later fill keys towards their own constraints. That loop never
steps the key at `pos`, so it cannot run into the ClickHouse#69261 hang; returning
first only left the later keys of the current value unfilled, and they were
produced after the next original row instead:

    SELECT a, b FROM (SELECT arrayJoin([(0., 0), (inf, 0)]) AS t,
        t.1 AS a, t.2 AS b) ORDER BY a WITH FILL, b WITH FILL TO 3
    -- (0,0), (inf,0), (0,1), (0,2) instead of (0,0), (0,1), (0,2), (inf,0)

The same happened with a `-inf` cursor before a finite row. Move both stops
after the loop, so they guard only the step of `pos`. The NaN stop for
nulls_direction != 1 stays before the loop: under ASC NULLS FIRST a NaN
sorts first, but `less` does not place it before the cursor, so the loop
would emit the later keys of a FROM cursor before the NaN row.

Pin optimize_sorting_by_input_stream_properties = 1 on the outer ORDER BY
case of 03239: with the randomized value 0 the outer sort repairs the order
and the case no longer checks what a user sees by default.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the non-finite stop comment in FillingRow::next to one line; drop the sentence narrating its placement.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds): 1 blocker + 1 major fixed, 2 findings declined
Finding Verdict
❌ A non-finite value in an earlier fill key pushed the later key's generated rows after it ((0,0),(inf,0) ORDER BY a WITH FILL, b WITH FILL TO 3); same for a non-finite cursor AGREE, fixed: both non-finite stops now run after the later keys are filled; two multi-key cases added
⚠️ The outer-ORDER BY case is live only when the randomized optimize_sorting_by_input_stream_properties is 1 AGREE, pinned in the query SETTINGS
❌ The later key is not filled inside a group whose earlier key is non-finite ((0,0),(inf,0),(inf,3) ORDER BY a WITH FILL, b WITH FILL TO 4 has no (inf,1), (inf,2)) Not changed here: the cursor moves onto an original value only when a step lands on it, so a group off the step grid gets no later-key rows, finite or not (03266_with_fill_staleness_cases pins (30, 18) unfilled off the 25 STEP 3 grid). Master omits the same rows; this PR fixes their order
💡 NaN under DESC NULLS LAST still gets its rows after it ([0, nan] DESC TO -1 gives 0, nan, 0) Not changed here: the fill comparator orders NaN greatest whatever the NULLS order, a separate defect

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT arrayJoin([0., inf]) AS x ORDER BY x WITH FILL TO 3 returns 0, inf, 1, 2 on master and on the official 26.10.3.7 build, every run.
b Root cause explained? FillingRow::next returned early whenever the next original value was NaN or infinite (#90255), even when the border it fills towards is a finite TO or staleness bound before that value. Nothing was generated before the row, and the rows up to TO came after it from the suffix (or were dropped with STALENESS). Both non-finite stops (cursor and next value) also returned before the later fill keys were filled, so a non-finite value in an earlier key pushed their rows after it.
c Fix matches root cause? Yes. The early return now fires only when no finite border comes before the value (the #69261 hang shape), reusing the border findBorder already chose. Both non-finite stops now run after the later fill keys are filled; that loop never steps the non-finite key.
d Test intent preserved / new tests added? Yes. 14 queries appended to 03239_nan_with_fill, existing lines untouched. One expected line of 04657_with_fill_bounds_out_of_column_type_range gains the 6 that is inside the staleness window.
e Both directions demonstrated? Yes. 13 of the 14 new queries fail on master and pass with the fix; through the runner, master fails exactly 03239 and 04657 among the 95 fill tests, the fix passes all 95. Removing the NaN exception makes the remaining one fail.
f Fix is general across code paths? Yes. This is the only stop on the next original value; a later fill column reaches it on the next call, and an earlier key holding the non-finite value no longer skips the later keys (both tested), the staleness long jump has no such stop, and the suffix passes an all-NULL row.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. inf/-inf/NaN, ASC/DESC, NULLS FIRST/LAST, Float64/Float32/BFloat16/Nullable, FROM, fractional and huge STEP, STALENESS, INTERPOLATE, two fill columns, max_block_size = 1. LowCardinality(Float64) is rejected by WITH FILL before this code.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only the order of generated rows, and the STALENESS rows that were dropped.
i Invariants and contracts preserved? Yes. Generated rows sort between their neighbours again, the order FillingStep declares to the outer sort. The no-TO hang case and a NaN constraint still stop, and the new path is bounded by the existing TO, stagnation and overflow checks. 50/50 randomized runs of both tests pass.

Session id: cron:clickhouse-impl-self-slot-57:20261116-223800

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d56a164]

Summary: ✅


AI Review

Summary

The fix restores bounded WITH FILL generation before non-finite input and lets later fill keys finish before stopping. The regression test and changed staleness expectation pass on the PR-head CI binary. No new findings. The nullable suffix-ordering defect observed during focused validation also reproduces without non-finite input and is already tracked by PR #117832.

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 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d56a16417 with master 96db37980 (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

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

Job report

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