Repository navigation
Reject WITH FILL bounds that do not fit the ORDER BY column type - #112650
Conversation
`WITH FILL FROM`/`TO` values are converted to a type wide enough for the
arithmetic - `Int64` for every integer column type - while the generated values
are written into a column of the column's own type, which truncates whatever
does not fit its range. A truncated value wraps around, so the filled stream
stops being monotonic while the query plan keeps claiming that it is still
sorted by the fill columns.
`DISTINCT` in order relies on that claim and reads the stream as a sequence of
sorted runs, so it deduplicates within wrong ranges:
SELECT count() FROM (SELECT DISTINCT x, s FROM
(SELECT toUInt8(5) AS x, 'Hello' AS s ORDER BY x ASC WITH FILL FROM 1 TO 1025))
returns 1024 instead of 257 in a release build, and in a debug or sanitizer
build it aborts with `Equal values are not contiguous within the range assumed
to be sorted` in `DistinctSortedStreamTransform`.
Reject such bounds with `INVALID_WITH_FILL_EXPRESSION`, next to the existing
check that rejects negative bounds for an unsigned column type. `TO` is an
exclusive bound, so it may still be one step outside of the range:
`WITH FILL FROM 0 TO 256` over a `UInt8` column keeps generating 0..255.
Found by the AST fuzzer:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=b0030d87c1f4e4b31d2766c17286e42492a2da94&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29
#109454
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [563fbf4] Summary: ✅
AI ReviewSummaryThe PR prevents Consumers of the newly widened arithmetic fields were traced:
The PR-head Fast test passed both Final Verdict✅ Approve |
The `TO` bound check assumed a unit step and accepted only `TO - direction` as the last value that filling can produce, so it rejected queries where a larger `STEP` stops well before the bound: `WITH FILL FROM 0 TO 257 STEP 3` over a `UInt8` column generates `0, 3, ..., 255`, all of which fit, but the check threw because neither `257` nor `256` is representable. Compute the last value that filling actually generates when it is known up front - with `FROM` and a plain numeric step the sequence is `FROM + k * STEP` while it stays strictly before `TO`. Without `FROM` the sequence is anchored at a data value, and an `INTERVAL` step is not a constant number of the column type units, so in those cases the previous conservative bound is kept.
`convertFieldToType` returns Null for a value out of range of the target type, which is exactly the check that was written by hand as an insert into a temporary column followed by a comparison.
…s-out-of-column-type-range
The switch to `convertFieldToType` in the `WITH FILL` bounds check broke fills over `DateTime` and silently disabled the check for `Date32`: the fill bounds are normalized to `Int64` fields, and `convertFieldToType` had no `Int64` -> `DateTime` path (it threw `TYPE_MISMATCH`, failing tests like `01145_with_fill_const`), while the `Int64` -> `Date32` path returned the value without a range check. Convert both through the underlying integer type (`UInt32` for `DateTime`, `Int32` for `Date32`), which range-checks the value and returns Null when it does not fit - the contract the bounds check relies on. Add `DateTime` and `Date32` cases to the test. Failed tests: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112650&sha=85e1516b761b26936639e392e86662f89054f43e&name_0=PR&name_1=Fast%20test #112650 Co-Authored-By: Claude Fable 5 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 45/48 (93.75%) · Uncovered code |
…s-out-of-column-type-range
Address review: the previous commit only range-checked the `Int64` carrier for `Date32`, while the separate `UInt64` branch below still went through `convertNumericType<Int64>`. Positive literals and `VALUES` inputs reach the helper as `UInt64`, so a day number like `3000000000` was accepted and then silently truncated when materialized into a `Date32` column (`Int32` under the hood). Both integer carriers now share the `convertNumericType<Int32>` path, and `gtest_convertFieldToType` covers the out-of-range `Date`, `Date32` and `DateTime` integers in both carriers.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes153 object files changed (+124.38 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units862 translation units recompiled, 6847 s compile time in total, 862 of them have a recent master baseline. |
…s-out-of-column-type-range
|
🕵 The |
Without FROM the fill sequence is anchored at a data value, so which values are generated is known only at execution time: WITH FILL TO 257 STEP 3 over a UInt8 column stops at 254 when the data ends at 11 but reaches 256 when it ends at 13. The check used to assume the value right before TO in that case, turning previously correct queries into INVALID_WITH_FILL_EXPRESSION. Whenever filling generates anything at all, its last value lands within one step before TO, so reject the bound only when even the value one whole step away from TO (clamped towards zero, so that anchors close enough to TO to generate nothing keep being accepted) does not fit the column type - that is, only when filling provably wraps for every possible anchor. With an INTERVAL step and no FROM nothing can be proven up front, so such bounds are now accepted as well. #112650 Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 The only red on fdb7a13, |
…ALENESS` is present `STALENESS` can only be used without `FROM`, and it replaces `TO` as the effective upper bound whenever it comes first: `FillingRow::updateConstraintsWithStalenessRow` sets the constraint to `min(fill_to, base_row + staleness)`. The sequence therefore stops at the last data value plus the staleness, which can be arbitrarily far below `TO`, so nothing about `TO` can be proven up front and `SELECT toUInt8(5) AS x ORDER BY x ASC WITH FILL TO 1025 STALENESS 20` - which stops at `24` - must not be rejected. `fillValueRequiredToFitColumnType` now returns `nullopt` (accept) whenever `fill_staleness` is set.
…s-out-of-column-type-range
|
🕵 Addressed the AI Review Major about On the reds of
|
… `INT64_MAX` `FROM` and `TO` of a `UInt64` column are converted to the `Int64` carrier, so the step past `INT64_MAX` wrapped around and was taken for an overflow, which stopped the filling and silently omitted valid `UInt64` values, while the same sequence anchored at a data value was filled completely. A step from an `Int64` cursor to a value the column can hold past `INT64_MAX` now continues as a `UInt64`; any other step wraps around as before. Also fix the clang-tidy `performance-no-automatic-move` error in `FillingTransform.cpp`: https://s3.amazonaws.com/clickhouse-test-reports/PRs/112650/68ea10984c380f7d5567c307fb02841d07be88be/pr/build_arm_tidy_4_4/build_clickhouse/build_clickhouse.log Co-Authored-By: Claude Opus 5.5 <[email protected]>
…DateTime64` `tryConvertFields` builds `staleness_step_func` with the same helper as `step_func`, so the whole-tick requirement for a fixed-length step finer than the scale of a `DateTime64` column rejected `STALENESS` steps too, e.g. `STALENESS INTERVAL 1 MILLISECOND` over `DateTime64(0)`, which works on master. A `STALENESS` step is never materialized: it is an exclusive bound after a data value, so round it away from zero to whole ticks instead, which keeps exactly the same values before the bound. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged The only red on 89ada51 was @Ergus, both of your threads from 2026-10-22 are addressed in 68ea109, with details in the thread replies. An |
|
🕵 Merged None of the red checks on e1173f5 are related to
@groeneai, investigate the failures: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112650&sha=e1173f5e4aeed1ad24c07718a15e6fcf97560ecd&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29 and https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112650&sha=e1173f5e4aeed1ad24c07718a15e6fcf97560ecd&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29, and provide fixes in separate PRs. If the fixes are already in progress (the PRs linked above), link them here. @Ergus, both open threads from 2026-10-22 were addressed in 68ea109; the details are in the thread replies. Could you resolve them if you agree? |
|
Both fixes are in progress in my open PRs:
|
|
🕵 Merged The only red check on 96b2cd7 was Thanks @groeneai for confirming that the other failures are tracked in #125026 and #128052. @Ergus, both of your open threads from 2026-10-22 are addressed in 68ea109 (details in the thread replies). Could you take another look and resolve them if you agree? |
|
🕵 Merged |
…alue Co-Authored-By: Claude Opus 5.5 <[email protected]>
…o fix-with-fill-bounds-out-of-column-type-range
…ections Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov
left a comment
There was a problem hiding this comment.
It might look bulky, but I didn't find any issues with this logic. We just painstackingly check the bounds.
|
@alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
WITH FILL FROM/TOvalues are converted to a type wide enough for the arithmetic -Int64for every integer column type - while the generated values are written into a column of the column's own type, which truncates whatever does not fit its range. A truncated value wraps around, so the filled stream stops being monotonic while the query plan keeps claiming that it is still sorted by the fill columns.DISTINCTin order relies on that claim and reads the stream as a sequence of sorted runs, so it deduplicates within wrong ranges:returns
1024instead of257in a release build, becauseWITH FILL FROM 1 TO 1025over aUInt8column generates1..255, 0, 1..255, 0, .... In a debug or sanitizer build the same query aborts inDistinctSortedStreamTransformwithEqual values are not contiguous within the range assumed to be sorted, which is what the AST fuzzer hit:https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109454&sha=b0030d87c1f4e4b31d2766c17286e42492a2da94&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29
#109454
The fuzzer query is unrelated to that pull request; the abort reproduces on
master:Fix
Reject
FROM/TOvalues that cannot be represented in the type of theORDER BYcolumn withINVALID_WITH_FILL_EXPRESSION, next to the existing check that rejects negative bounds for an unsigned column type. This matches how the equivalentDate/DateTimebound mismatch is already rejected (#30421).TOis an exclusive bound, so it may still be outside of the range as long as the values that filling actually generates fit:WITH FILL FROM 0 TO 256over aUInt8column keeps generating0..255, and so doesWITH FILL FROM 0 TO 257 STEP 3, which stops at255. The last generated value is known up front only whenFROMand a plain numericSTEPare given. WithoutFROMthe sequence is anchored at a data value, so which values are generated is known only at execution time:WITH FILL TO 257 STEP 3over aUInt8column stops at254when the data ends at11but reaches256when it ends at13. An empty input generates nothing at all. So withoutFROMthe bound is not checked up front; such a fill is checked value by value as it is generated, see below, and is rejected exactly when it would produce a value the column cannot hold. WithFROMthe sequence is the same for any data, so the up-front check is exact and fails fast: the per-value check alone would rejectWITH FILL FROM 0 TO 4294967297over aDateTimecolumn only after generating 2^32 rows. AnINTERVALstep overDateandDateTimecannot stop short of the boundary of the type (see below), so it always passes that boundary before it could reach aTOoutside of it (on current master it wrapped around and never terminated, e.g.SELECT toDate(0) AS d ORDER BY d ASC WITH FILL FROM toDate(0) TO 70000 STEP INTERVAL 100 YEAR). WithFROM, such aTO(out of range in the fill direction) is therefore rejected up front.STALENESS, which is allowed only withoutFROM, replacesTOas the effective bound whenever it comes first, so the sequence can stop arbitrarily far belowTOand such aTOis not checked either. Float and Decimal bounds are not checked: they saturate instead of wrapping, and aFloat64bound is generally inexact in aFloat32column, so requiring exact representability there would reject ordinary queries.For
Date32andDateTime64the calendar arithmetic of anINTERVALstep clamps at the boundaries of the representable calendar instead of wrapping - the[0000-01-01, 9999-12-31]window ofDateLUTImpl, taken in the local civil calendar of the column's time zone, which is strictly narrower than their storage type. A step that would leave the calendar returns its input unchanged, and since bc901b2 (Stop WITH FILL when the step can no longer advance the cursor)FillingRow::nextends the fill on such a step, so aTObeyond the calendar boundary just lets the fill run up to the last value it can reach (e.g.SELECT toDate32('9999-12-31') AS d ORDER BY d ASC WITH FILL TO 3000000 STEP INTERVAL 1 YEARreturns 1 row). Such aTOis therefore accepted for anINTERVALstep over these two types; onlyDateandDateTime, which really wrap around their storage type, keep theINTERVAL-stepTOcheck above.Beyond reachability, for
Date32andDateTime64the values between the calendar boundary and the boundary of the storage type are invalid in themselves: no conversion produces them (they all clamp at the calendar boundary), yet aFROMbound in that gap is materialized into the column as is and serialized as the clamped boundary date - a spurious duplicate of the genuine boundary value next to it (e.g.SELECT d FROM (SELECT toDate32('2000-01-01') AS d ORDER BY d ASC WITH FILL FROM -719529 TO -719528 STEP INTERVAL 1 YEAR)on current master returns a0000-01-01row holding the day number-719529, which is not0000-01-01). The representability check therefore tests bounds of these two types against the calendar window (in the local civil calendar of the column's time zone forDateTime64), not just the storage range: an out-of-calendarFROMis rejected for any kind of step - like aFROMout of the storage range already is - and a numeric-stepTOis rejected when the last value generated under it provably lands in the gap, under the same rules as the storage range. The last-generated-value computation covers theDecimal64-carriedDateTime64bounds as well as theInt64-carried types: a numeric step overDateTime64advances raw ticks of the column's scale, and ticks beyond the calendar do not wrap but are equally invalid (they all serialize as the clamped boundary date).Finally, the calendar arithmetic of an
INTERVALstep overDateandDateTimereturns the storage type of the column, so a step whose result would leave that type wrapped around, even below a perfectly representableTO: on current masterWITH FILL FROM toDateTime('2106-01-01 00:00:00', 'UTC') TO 4294967295 STEP INTERVAL 100 YEARjumps from 2106 back to 2069 and keeps cycling belowTOforever, and a step longer than the span of the type (INTERVAL 150 YEARoverDateTime) even wraps forward. Such a step is now redone in the wider calendar ofDate32(day numbers) orDateTime64(0)(seconds), which agrees with the narrow one wherever the result fits, and the result is returned as is when it does not fit the storage type (calendarStepOutOfStorageType). The sequence therefore stays monotonic: aTOwithin the range stops the fill at the step that passes it (the query above returns just2106-01-01), and a value the column cannot hold is rejected by the per-value check below.The bounds known when the transform is constructed are only half of the picture: a fill without
FROMis anchored at a data value, andSTALENESSplaces its bound at a fixed distance past the last data row, so what such a fill actually generates depends on the data.FillingRowtherefore checks the runtime side as well, with the same notion of representability - the storage range plus, forDate32andDateTime64, the calendar window. The inclusive[min, max]range of the column type is computed byfillRepresentableRangeOfColumnTypeand checked with two accurateFieldcomparisons everywhere:fillValueFitsColumnTypewraps it for the construction-time checks, and on the per-generated-value path the range is precomputed once per fill column.FillingRow::nextchecks every value it is about to generate and throwsINVALID_WITH_FILL_EXPRESSIONwhen the value does not fit the type of the fill column. A step that turns back - an overflow of theInt64carrier of the integer types or of theDecimal64ticks ofDateTime64- ends the fill like any other overshoot, because the value it overflowed from is past any border:WITH FILL FROM INT64_MAX - 1 TO INT64_MAX STEP 2returns[INT64_MAX - 1]. A step that fails to advance (NaN, infinity, a float step below the precision at the current magnitude, or the calendar clamp ofDate32/DateTime64) keeps stopping the filling, as it always did. Before the suffix is generated, when the anchor is known, a fill towards a constraint past the range of the type is also checked once withdoLongJump, soWITH FILL TO 4294967297 STEP INTERVAL 1 SECONDoverDateTimefails at once instead of after generating 2^32 rows. A NaN border generates nothing: the accurateFieldcomparison orders NaN greatest, so on current master a fill towards a NaNfill_toor aSTALENESSborder derived from a NaN row runs until the float step stagnates. This is the only check for fills withoutFROM:WITH FILL TO 257 STEP 3over aUInt8column stops at254when the data ends at11- a perfectly ordinary fill - but reaches256, which the column stores as0, when it ends at13, and an empty input filledTO 1025generates nothing. Rejecting the bound up front would reject the ordinary queries along with the wrapping one, so only the wrapping one is rejected, when it actually generates the value.The
STALENESSborder itself is not validated - it may not even be the active bound (findBordermay discard it for a closerTO, and a border that does not advance the anchor simply generates nothing through the ordinary border cut-off), so a border past the range of the column type is fine as long as the fill never reaches a value the column cannot hold. When it does, the same per-generated-value check rejects it, including the calendar window:SELECT toDateTime64('9999-12-31 23:59:58', 0, 'UTC') AS t ORDER BY t ASC WITH FILL STALENESS 10puts the border at the raw tick253402300808, which fits theDecimal64carrier but is past the last representable time point, and on current master the query returns9999-12-31 23:59:59nine times in a row - the out-of-calendar ticks253402300800..807all serialized as the clamped boundary date; with this change it throws when the fill reaches the first out-of-calendar tick.(The
DateTime64/Time64integer-carrier hardening ofconvertFieldToTypethis PR originally carried landed on master independently, asconvertWholeSecondsToDateTimeTypein #118656; the tests here keep covering it.)Changelog category
Bug Fix (user-visible misbehavior in an official stable release)
Changelog entry
Reject
WITH FILLbounds and generated values that do not fit the type of theORDER BYcolumn, and stopWITH FILLat a step that overflows instead of generating wrapped-around, non-monotonic, or non-terminating output.Documentation entry
Workflow [PR]
Sync PR [sync-upstream/pr/112650]
Version info
26.11.1.1695-master(included in26.11and later)