Repository navigation
Conversation
…fit the element type
On 26.8.10.6 and 26.3.33.24, `SELECT [toUInt8(44)] = '[300]'` returns 1 and
`SELECT * FROM values('x Array(UInt64)', '[18446744073709551616]')` materializes
`[0]`. The discriminator is quoting: the unquoted literal `[300]` is already
rejected today.
convertFieldToTypeImpl's Array/Tuple/Map branches gate on the source Field's own
type and recurse per element, so an out-of-range element of an unquoted composite
is already caught. A composite arriving as a String Field matches none of them and
falls through to "Conversion from string by parsing". That branch's only defence
against a wrapping parse is to parse into a promoted type (canBePromoted() /
promoteNumericType()) and let the recursive convertFieldToType range-check the
result, which is why the scalar narrow case is already correct. Composites inherit
canBePromoted() == false, so each element is read at its own width by
SerializationNumber<T>::deserializeText through readIntTextUnsafe, whose digit loop
was `res = res * 10 + digit` with no overflow handling of any kind. The magnitude
was destroyed before the range check could see it, so the check inspected an
in-range residue and accepted it.
readIntTextUnsafe now takes the overflow policy as a template parameter, defaulting
to today's behaviour. Under the checking policy the digit loop applies a per-digit
threshold test and reports a dedicated error. The bound is taken on the unsigned
accumulator the function already uses, which is max(T) normally and max(T) + 1 when
the value is negative and T is signed, because that is how the existing tail reaches
min(T). The front end (sign handling, the lone '+' token, the no-digit case) stays
shared, so the accepted-syntax surface cannot move. A per-digit threshold test is
used rather than common::mulOverflow because the latter is a no-op stub for the
big-int types, which is also why readIntTextInBaseImpl's own check is skipped there.
One internal FormatSettings field selects the policy, read only in
SerializationNumber and set only by the string branch, for composite targets. The
branch maps the dedicated error to Null, which is the contract its header already
documents and what the comparison fold needs in order to answer false rather than
throw. A dedicated error code is needed because the catch block must distinguish
leaf integer overflow from every other parse error, and ARGUMENT_OUT_OF_BOUND,
CANNOT_PARSE_NUMBER and INCORRECT_DATA are all already thrown while parsing other
leaf types during the same parse. The throw is out of line beside the two helpers
that already exist there, because an inline exception in this reader was measured to
grow the hot-path frame from 8 to 72 bytes.
tryDeserializeText honours the same field for the big-integer widths only. A Variant
element does not select its alternative through deserializeText; it tries each one
through the try-API, whose own overflow check is skipped for exactly those widths.
The narrow widths already reject and are deliberately untouched, so this makes the
wide case do what the narrow case already did.
Rejected alternatives. Widening the integer leaves of the parse type still wraps
above 2^256, so `[toUInt8(44)] = '[<2^256 + 44>]'` stayed 1. Widening and saturating
introduced new wrong answers: at a leaf that cannot be widened the saturated value
is accepted by the range check, `[toUInt256(<max>)] = '[<2^256>]'` would have flipped
from 0 to 1, an unwidened LowCardinality(UInt8) leaf clamped 300 to a valid 255, and
Array(Variant(UInt8, UInt16)) threw on duplicate transformed alternative names. Both
failed for the same reason: they tried to change a generic parser's behaviour by
substituting the parse type, and the substitution always reached further than
intended. Switching deserializeText to a checking reader unconditionally would change
every text input format on the declared bulk-ingestion hot path. Splitting the
composite text into element texts needs a new splitter that must agree byte for byte
with the Array, Tuple and Map deserializers.
Measurements. The default instantiation is unchanged and the field is false
everywhere else, so no text input format is affected: 63 syntax cells across
Array(UInt64), Array(Int8), Array(Variant(String, UInt128)) and
Array(Variant(String, Int256)) are identical before and after, the only two movers
being out-of-range magnitudes. The exact bounds of every width, the empty literal,
and the Bool, Enum8, Decimal32, Date, DateTime, Float64, String, UUID and IPv4 leaves
are all measured unchanged. Forcing the new field to false in one line and rebuilding
reverts every fixed case, including the wide Variant one.
Two user-visible deltas. The rejection is of the whole literal rather than the single
element, so `values('x Array(Nullable(UInt64))', '[2^64]')` now raises an error where
the unquoted literal yields `[NULL]`; it returns `[0]` today, so the quoted form is
never laxer than the unquoted one. Array(DateTime) and the other date and time leaves
read their own text and still saturate on an out-of-range integer, which is the same
class one type family over and is left out of scope.
Co-Authored-By: Claude Opus 5 <[email protected]>
…d cover Variant targets
Follow-up to the previous commit, which makes a string-to-Array/Tuple/Map
conversion return Null when an integer element does not fit.
FunctionComparison::executeWithConstString folds a Null constant to
IsOperation<Op>::not_equals for every operator. For an ordering operator that
answer is not complementary once the constant is a composite rejected as a
whole: `[toUInt8(43)] < '[300]'` became 0, and `x <= C` and `x > C` were both 0,
so a negated comparison rewritten into its complement (filter push-down, the
CNF pass) would select different rows than per-row evaluation. Which side of the
literal a value lies on is unknown, so `<`, `<=`, `>` and `>=` against an
Array/Tuple/Map constant that cannot be represented now throw
ARGUMENT_OUT_OF_BOUND. `=` and `!=` keep folding, since 0 and 1 are right there.
The Variant branch of convertFieldToTypeImpl does not return when no alternative
converts the source, so a String falls through to the string branch with the
Variant as the target. That parse did not set the overflow field, and the
try-API it uses skips the overflow check at the big-integer widths, so
`values('x Variant(Array(UInt128), UInt8)', '[2^128]')` returned [0]. The field
is now set for a Variant target too; the fall-through then fails with
INCORRECT_DATA, as it already did for a narrow alternative. A scalar big-integer
alternative is not reached this way: the strict loop converts to it through the
scalar path first, which wraps at 64 bits and wider on its own and is the scope
of ClickHouse#122245.
FormatSettings is now copied only when the field has to be set, instead of on
every string conversion including scalar targets.
The ReadHelpers.h comment that said readIntTextUnsafe cannot check for overflow
is reworded in place; it no longer holds.
The test gains the equality/ordering split, the top-level Variant composite
alternatives, and Array(LowCardinality(UInt8)) and
Array(LowCardinality(Nullable(UInt8))); it drops the obsolete
allow_experimental_variant_type setting.
Measured, base 5b0395f vs this build:
- before the change, on the previous build: `[toUInt8(43)] < '[300]'` 1 -> 0,
`<=`/`>` 1 0 -> 0 0, and both Variant forms unchanged ([0], 0);
- now every ordering operator, on either side, against Array, Tuple, Map,
Nullable(Tuple), a non-constant column and a MergeTree key raises
ARGUMENT_OUT_OF_BOUND, and in-range ordering is unchanged;
- 05257: 38 statements, 25 red on base, the whole file OK on this build and
50/50 with randomized settings;
- 1539 stateless tests matching tuple|array|map|variant|values|low_cardinality|
comparison, randomized and not: the same 64 fail on both builds, 0 differences.
The previous commit's message says 63 reader syntax cells; the measured total is
64, 62 identical and 2 intended movers.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous commit makes <, <=, > and >= against an Array, Tuple or Map constant that cannot be represented throw ARGUMENT_OUT_OF_BOUND. Each operator is its own FunctionComparison instantiation, and 05257 exercised <, >= and > but not <=, so dropping IsOperation<Op>::less_or_equals from the guard would have folded <= back to 0 with the test still green. The Map ordering line now uses <= instead of <, so each ordering operator appears exactly once. The comment above the Null fold in executeWithConstString still said every ordering comparison yields false; for an Array, Tuple or Map constant it now throws. The comment is reworded in place, same line count. Measured, base 5b0395f vs this build: - before editing: map(toUInt8(1), toUInt8(1)) <= '{300:1}' returns 1 on base and raises ARGUMENT_OUT_OF_BOUND on the previous build; - 05257: OK on this build, and the reference regenerated from it is byte-identical to the committed one; 38 statements, 25 red on base including the new <= line; 50/50 with randomized settings; - with less_or_equals removed from the guard, 05257 fails on exactly the <= line, while the previous version of the test passes; - the build is byte-identical to the previous one, since the only source change is a comment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mber the test to 05258 SerializationNumber<T>::tryDeserializeText declared `bool parsed;` and assigned it in both arms of the following if constexpr. The repository's .clang-tidy keeps cppcoreguidelines-init-variables enabled with WarningsAsErrors '*', and the check matches template patterns without flow analysis, so Build (arm_tidy) and Build (amd_tidy) would fail on this line. The variable is now initialized at its declaration, which is how master fixed the same shape before. The test prefix 05257 is now also used on master, by 05257_prewhere_after_final_float_sorting_key, so the test moves to the next free number, 05258. Both files are renamed only; their content is unchanged. Measured: - before editing, clang-tidy-22 -p build on SerializationNumber.cpp fails with exactly one error: SerializationNumber.cpp:162:10 variable 'parsed' is not initialized [cppcoreguidelines-init-variables]; - after the edit, clang-tidy-22 reports no diagnostic on SerializationNumber.cpp, ReadHelpers.cpp, convertFieldToType.cpp, less.cpp and ErrorCodes.cpp, both invoked as above and with the CI job's --extra-arg-before=--driver-mode=g++; - 05258: OK on this build, and the reference regenerated from it is byte-identical to the committed one; FAIL on base 5b0395f, with the same 38 statements and 25 of them red as before the rename; 50/50 with randomized settings; - style checks: 16 of 17 legs pass locally; the remaining one, settings_changes_history, needs the changed-files list only CI records. Co-Authored-By: Claude Opus 5.5 <[email protected]>
05258 rejected an unsigned value one past the maximum and a signed value one
past the minimum ('[-129]' for Int8), and accepted the exact signed bounds, but
it never had a signed value one past the maximum. The checked reader's bound is
max(T) + (is_signed_v<T> && negative ? 1 : 0). Dropping `&& negative` would make
the positive bound of Int8 128, so '[128]' would be accepted and stored as -128
while every line of the test stayed green. The new line
SELECT [toInt8(-128)] = '[128]' is the positive-side counterpart of the '-129'
line: 128 does not fit Int8, so the literal is rejected and the equality is 0.
Measured, base 5b0395f vs this build (unchanged, only the test changes):
- before editing: [toInt8(-128)] = '[128]' returns 1 on base (128 is read
modulo 256 as -128) and 0 on this build;
- 05258: OK on this build, and the reference regenerated from it adds exactly
one 0 line; FAIL on base, with 39 statements, 26 of them red including the
new line, and the other 38 answers unchanged; 50/50 with randomized
settings, with the same 14 ARGUMENT_OUT_OF_BOUND and 4 INCORRECT_DATA
errors in every run;
- style checks: 16 of 17 legs pass locally; the remaining one,
settings_changes_history, needs the changed-files list only CI records.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the ReadHelpers.h comment that restated the CHECK_OVERFLOW template argument and the note on the negative bound, and shorten the mulOverflow note in readIntTextUnsafe to one line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 9 findings over 5 rounds, the last delta recheck found none) plus my own cold review.
Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20260926-020400 |
Pre-PR validation gate (click to expand)
Regression: 1539 related stateless tests, randomized and not: the same 64 fail on both builds (cluster and user-files shapes a local server cannot serve), 0 differences. 50 randomized runs of the new test: 50 passed. Session id: cron:clickhouse-impl-self-slot-57:20260925-194300 |
|
Workflow [PR], commit [ab9dbc0] Summary: ✅
AI ReviewSummaryThis PR fixes the main overflow bug for quoted composite literals by rejecting out-of-range nested integers instead of wrapping them, and the new tests cover the core Findings
Final Verdict |
…ected tuple literal The previous commits make a quoted Tuple literal with an out-of-range integer element convert to Null, and executeWithConstString folds a Null conversion to a constant: = is false and != is true. The fold built that constant as UInt8, but a Tuple comparison declares Nullable(UInt8) when an element comparison is Nullable, for example (toUInt8(44), toNullable(toUInt8(1))) = '(300,1)'. The constant then did not match the declared type, so the analyzer's constant folding and ActionsDAG's partial-result evaluation raised the LOGICAL_ERROR "Unexpected return type from equals. Expected Nullable(UInt8). Got Const(UInt8)" that the AST fuzzer found (STID 3344-4ec5, both targeted jobs). Before these commits the fold was not reachable for a Tuple: the string was parsed at the element width and the integer wrapped instead. The fold now builds its constant with the function's result type. The value is unchanged, and every type that could reach the fold before declares UInt8, so nothing else changes. Array and Map comparisons with a string declare UInt8 and were not affected. Measured, the published head's build and this build, with base 5b0395f for the answers: - (toUInt8(44), toNullable(toUInt8(1))) = '(300,1)' and the fuzzer's own query abort with the LOGICAL_ERROR on the published head's build and return 0 on this build (1 on base, where 300 wraps to 44). The same holds for a non-constant tuple column, a nested Tuple with a Nullable element, a LowCardinality(Nullable) element, a Dynamic element and a MergeTree key. - 05258 gains one constant and one non-constant line for this. It is OK on this build, and the reference regenerated from it adds exactly those two answers. It is FAIL on base, with 41 statements, 28 of them red. 50/50 with randomized settings. - 144 comparison and tuple tests: the same single failure on base and on this build (00072, which needs the test.hits dataset). - clang-tidy-22 is clean on equals.cpp and notEquals.cpp. Style checks: 16 of 17 legs pass locally; the remaining one, settings_changes_history, needs the changed-files list only CI records. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| { | ||
| /// A composite constant is rejected as a whole, so the side of it every value lies on is unknown. | ||
| const WhichDataType which_to_compare(type_to_compare); | ||
| if (which_to_compare.isArray() || which_to_compare.isTuple() || which_to_compare.isMap()) |
There was a problem hiding this comment.
The new throw path only checks WhichDataType(type_to_compare) on the wrapped type. convertFieldToType unwraps Nullable(...) before parsing, so CAST((toUInt8(43), toUInt8(1)) AS Nullable(Tuple(UInt8, UInt8))) >= '(300,1)' still lands in converted.isNull() here, but which_to_compare.isTuple() is false and this returns 0 instead of raising ARGUMENT_OUT_OF_BOUND like the plain Tuple case.
Please strip Nullable / LowCardinality here (for example with removeLowCardinalityAndNullable) before the composite-type check, and add a Nullable(Tuple(...)) ordering case to 05258.
Fold the composite-literal fix (ClickHouse#122368, branch fix-out-of-range-integer-in-quoted-composite-literal at ab9dbc0) into this PR, as asked in review. The only conflict is the `converted.isNull()` block of `executeWithConstString`: keep the out-of-range direction for a scalar target, then the refusal for an Array, Tuple or Map target. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Folded into #122245 as asked in review there (#122245 (comment)). |
Related: #122245
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when a quoted composite literal such as
'[300]','(300,1)'or'{300:1}'holds an integer that does not fit its integer element type: the integer was read modulo the type, so a comparison against a value the column cannot hold returned true andvalues()materialized the wrapped value. Such a literal is now rejected, and an ordering comparison (<,<=,>,>=) against it raises an error.Description
On 26.8.10.6 and 26.3.33.24,
SELECT [toUInt8(44)] = '[300]'returns 1 andSELECT * FROM values('x Array(UInt64)', '[18446744073709551616]')materializes[0]. The unquoted literal[300]is already handled correctly.Root cause: the string branch of
convertFieldToTypeImplavoids a wrapping parse by parsing into a promoted type and range-checking the result. A composite cannot be promoted, so each element was read at its own width byreadIntTextUnsafe, which never checked overflow.Change: that reader gets an opt-in overflow check, selected by an internal
FormatSettingsfield that only this branch sets, and the branch maps the resulting error to Null. The field is false everywhere else, so text input formats keep their behavior and pay one test of it per integer. With the field set, the reader accepts the same syntax: of 64 syntax cells measured before and after, only the two out-of-range magnitudes move. The field also reaches the try path aVariantalternative is parsed through, whose own check skips the big-integer widths.=and!=against a rejected literal still answer;<,<=,>,>=raiseARGUMENT_OUT_OF_BOUND, because a literal rejected as a whole has no known side.Deltas: the whole literal is rejected, so
values('x Array(Nullable(UInt64))', '[2^64]')raises an error where the unquoted literal gives[NULL](master returns[0]).Array(DateTime)elements read their own text and still saturate; out of scope. #122245 fixes the scalar counterpart.Surface: what changes, what does not
Array/Tuple/Map/Nestedinteger element, any width and magnitude[44],[0],(0,1),{44:1},[[0]])Array(Int256)below its minimumArray(LowCardinality(UInt8)),Array(LowCardinality(Nullable(UInt8)))[44]Array(Nullable(UInt64))'[2^64]'[0]<,<=,>,>=against such a literalARGUMENT_OUT_OF_BOUNDArray(Variant(String, UInt128)),Variant(Array(UInt128), UInt8)with'[2^128]'[0]INCORRECT_DATA, as a narrow alternative already didUInt256max,Int256min,Int8[-128,127],UInt64maxBool,Enum8,Decimal32,Date,DateTime,Float64,String,UUID,IPv4elementsVariantalternativeCAST('[300]' AS Array(UInt8)),INSERT INTO t VALUES ('[300]')[44]INSERTwithinput_format_values_deduce_templates_of_expressions = 0[44]Array(DateTime)+ out-of-range integerSyntax cells measured identical:
+1,01, whitespace,1e3,0x10,1.0, lone+, empty, exact bounds.Workflow [PR]
Sync PR [sync-upstream/pr/122368]