Repository navigation
Fix comparisons, IN sets and partition ids built from an out-of-range integer string constant - #122245
Conversation
… integer string constant
On 26.8.10.6 and 25.3.14.14:
SELECT toInt32(0) < '2147483648'; -- 0, and 1 > '257' is 0 too
SELECT toUInt64(0) = '18446744073709551616'; -- 1
SELECT toUInt64(0) IN ('18446744073709551616'); -- 1
ALTER TABLE t DROP PARTITION '18446744073709551616'; -- dropped partition 0
Found by the nightly SQLancerPP (arm_release) NoREC oracle on true master, which
compares the rows of `WHERE p` against the per-row value of `p` and had been red
on 9 of the last 10 nightlies. Its own query reduced to
SELECT count() FROM t, v WHERE NOT (CAST(v.c0 AS Int32) <= '1908606676453317954')
returning no rows for a predicate that is true on every one of them.
Two causes compose here.
`convertFieldToTypeImpl`'s string branch parses through
SerializationNumber<T>::deserializeText, i.e. readIntTextUnsafe, which does not
check overflow. The promotion at the top of that branch covers the narrow
widths, but a literal past the promoted type's range comes back as a wrapped,
non-null value, in breach of the contract convertFieldToType.h already
documents ("If the value does not fall into the range - returns Null";
"Out-of-range values are always rejected"). The wrapped value then reaches every
caller of the shared conversion: equality, IN set construction, KeyCondition
bounds (measured: Granules 1/3, granules holding matching rows pruned on a
wrapped bound), ALTER ... PARTITION resolution and the values table function.
The literal is now range-checked, which restores that contract in one place.
Same fix class at the same layer as b50a2a4 and e3f838c; the
deserializer and readIntTextUnsafe are deliberately untouched, being the hot
path for bulk text ingestion.
Neither obvious checking primitive can be used at these widths, which is worth
recording: readIntText.h gates its overflow check on !is_big_int_v<T>, and
common::mulOverflow / addOverflow have big-integer specializations that compute
mulIgnoreOverflow and return false, under the comment "Overflow check is not
implemented for big integers". An implementation built on the latter classifies
10^256 as in range, because 10^256 mod 2^256 is 0.
FunctionComparison::executeWithConstString then folded the whole comparison to
IsOperation<Op>::not_equals whenever that conversion returned Null. That is
right for = (false) and != (true), since no value of the type can equal an
out-of-range constant, but wrong for two of the four ordering operators in each
direction, whose answer is fully determined by the direction of the overflow.
Answering false for both `x <= C` and `x > C` also destroys
NOT (x <= C) <=> (x > C), so filter push-down below a join, which reaches
KeyCondition's inverse_relations substitution, returned a different and empty
result from the same predicate evaluated per row. The fold now resolves the four
ordering operators by direction, mirrored when the constant is the left operand,
and leaves = and != on the answer that layer has made correct.
The classification is deliberately narrow: it applies only to a plain integer
target with no custom serialization, only to a well-formed decimal integer
literal, and never to a negative literal against an unsigned type, which
ClickHouse rejects today and must keep rejecting. LogicalExpressionOptimizerPass
and KeyCondition are left alone: both already decline to fold an unconvertible
string constant, and that decline becomes the correct outcome once this function
is right.
01311_comparison_with_constant_string has carried two `-- this is wrong for now`
markers on exactly the `1 < '257'` and `1 <= '257'` cells since 2020; they are
removed and those two reference values flipped.
Co-Authored-By: Claude Opus 5 <[email protected]>
… targets Two follow-ups on the previous commit, neither of which changes behaviour. The comment on the magnitude loop in `parseDecimalIntegerLiteral` claimed that neither `common::mulOverflow` nor `common::addOverflow` reports overflow at the widest integer widths. Only the first half is true. `base/base/arithmeticOverflow.h` gives `addOverflow` a real predicate in all four wide specialisations (`:59-87`), while `mulOverflow` is the no-op there (`:180-207`, under the in-tree comment "Overflow check is not implemented for big integers"). The comment is kept, because it records why the loop must not be rewritten onto `mulOverflow`: `10^256` is congruent to 0 modulo `2^256`, so a wrapped magnitude would classify as in range. It now names only `mulOverflow`. `classifyIntegerLiteralRange` parsed the literal before deciding whether the target could be an integer at all. The parse costs a `UInt256` subtract plus a `UInt256` division per digit, and the String branch of `convertFieldToTypeImpl` calls the classifier unconditionally, so every all-digit literal aimed at a `Decimal`, `DateTime`, `DateTime64`, `Date32`, `Time` or `Enum` ran the whole wide loop only to fall out of the switch's default arm as NotApplicable. That is per value rather than per query where a `Field` is materialised for each cell or set member, for instance in the PostgreSQL per-cell parser lambda and in set construction. Test the target type first. `WhichDataType::isInt()` and `isUInt()` cover exactly the 12 TypeIndex values the switch dispatches on, and `Date`, `DateTime`, `Enum8`, `Enum16`, `IPv4` and the `Decimal` types all carry their own TypeIndex, so the gate returns the same value the switch would have returned. Measured over 52 statements spanning every type family that reaches the String branch, all 12 integer widths at both sides of their boundary, the Nullable and LowCardinality wrappers and the malformed literals: identical results and identical error codes with and without the gate. The default arm is left in place for any TypeIndex added to the switch later. Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the comments that narrate the new code and its refuted alternatives; keep the ones stating a property of existing code (the unchecked integer reader, the widest-integer mulOverflow gap, the two's-complement minimum, custom text serializations) as standalone one-liners.
Internal second-model reviewAn independent model reviewed this diff cold, then adjudicated its findings against the recorded
On 1. This diff cannot reach it: on a composite target the new classifier returns On 2. For a non-nullable target an out-of-range constant is now rejected and the test pins it. For a Scope note. The range check sits in the shared conversion, so it reaches Two silent answers become errors, and in both cases the error is the one the header already documents: |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260925-105300 |
|
Workflow [PR], commit [c9457d7] Summary: ✅
AI ReviewSummaryFixes out-of-range integer string constants in scalar and quoted composite comparisons, Final VerdictStatus: ✅ Approve |
|
cc @Algunenano @nihalzp, could you review this? An ordering comparison against a string constant holding an out-of-range integer folded to false in both directions, so |
`Int16 a < '9999999999999999999999999'` is true on all 10000 rows: the constant is above `Int16`'s maximum. The reference recorded `0` because the pre-fix fold answered false for all four ordering operators whenever the constant could not be converted. Measured on a pre-fix build of this branch, `toInt16(-32768) < '9999999999999999999999999'` and `toInt16(32767) > '9999999999999999999999999'` were both `0`, so the recorded count came from that fold and not from a wrapped value. The test guards against the logical error of issue ClickHouse#67742, "Statistics 'tdigest' does not support estimating value of type String". That is untouched: the query still runs and the estimator declines instead of throwing. `allow_statistics_optimize = 0` yields the same count on both builds, so the estimator was never the source of the old value either. Fast test ran 12345 stateless tests on the previous head and this was the only failure.
The comment above `if (converted.isNull())` claimed that `=`, `<`, `>`, `<=` and `>=` all yield false, which the block below no longer does for an ordering operator against an out-of-range integer constant. It now states the three outcomes the block actually produces, and drops the per-operator enumeration that only restated the code under it. Comment-only: the comment-stripped form of the file is unchanged, and its comment line count stays at 217. `clang-tidy-22 -p build src/Functions/less.cpp` is rc=0 with no error.
The boundary row asserted the exact `UInt256` maximum only through `toUInt256(0) < '<max>'`. That cell cannot distinguish in-range from above-range: if the classifier treated the exact maximum as an overflow, the directional fold would answer `1` for `<` just the same. The other three extremes in the row are each asserted with `=`, which does distinguish them, because a constant classified out of range converts to `Null` and `=` then folds to false. Assert the maximum with `=` as well. The value is unchanged, so the reference is untouched, and the row keeps one `<` cell so an in-range constant is still covered by an ordering operator.
…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]>
`Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)` failed both `granules` lines of this test, 3 of 3 reruns: each printed `Granules: 5/5` (and `3/3`) behind the plan tree's vertical connector (U+2502) instead of the bare line the reference expects. That lane enables parallel replicas in the default profile. With the local plan on (the default), the local read step becomes the first child of a `Union` beside `ReadFromRemoteParallelReplicas`, so its lines carry a tree connector that `trimLeft` keeps. With `parallel_replicas_local_plan = 0` there is no local read step and no `Granules:` line at all, so stripping the prefix would not be enough. The granule count is a property of the key condition, which a single-node plan exercises the same way, so the two `EXPLAIN` queries now run with `enable_parallel_replicas = 0`, as in `04402_sparse_pk_index_analysis_truncated_isnull`. The value assertions beside them still run under parallel replicas. The reference is unchanged. Measured with the lane's two `enable_parallel_replicas.xml` overlays on a three-replica cluster: the previous test reproduces the CI diff exactly, and this one passes without randomization, with `parallel_replicas_local_plan = 0`, in 40 of 40 randomized runs under that profile and in 50 of 50 on the default configuration. A build without the fix still fails it, including `Granules: 1/3` for the `UInt64` key under the parallel replicas profile. 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]>
Build profile diff (arm_release)Commit See the job log for details. |
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]>
…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]>
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…ison-out-of-range-string-constant # Conflicts: # src/Interpreters/convertFieldToType.h
The row pinned `CAST('a', 'Enum8(\'a\' = 1)') < 'zz'` at 0 to show this
change leaves Enum targets alone. Since ClickHouse#122672 master rejects a
non-member literal in an ordering comparison with
UNKNOWN_ELEMENT_OF_ENUM before the conversion this change touches, so
the row can no longer reach that code and master's own
05243_enum_unknown_literal_key_condition covers the new behaviour.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 654de01Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261010-180005 |
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]>
One rule for a string constant compared with a column: an integer in it that does not fit the column type is compared by its value, as the same literal unquoted would be. It never wraps. A scalar target already answered by the side of the range the constant is on. A composite target (`Array`, `Tuple`, `Map`) refused ordering comparisons instead, since the literal was rejected as a whole and has no single side. Now the literal is re-read with its integer elements widened to 256 bits and compared with the generic comparison: `[toUInt8(43)] < '[300]'` is 1, like `[toUInt8(43)] < [300]`. Each element is widened to the 256-bit type of its own signedness, and if that does not hold the literal, all to `Int256`, then all to `UInt256`, so `[toUInt256(0)] > '[-1]'` and `[toUInt8(0)] < '[2^255]'` answer too. Integers that fit none of these are not equal to anything, and an ordering comparison against them raises `ARGUMENT_OUT_OF_BOUND`, also under a `Nullable` wrapper. No `Float64` fallback: it rounds one below the `Int256` minimum to the minimum. The checked read stops at the integer that does not fit, so the rest of the literal is validated by an unchecked read with `Int256` elements: `'[2^256x]'` is still a syntax error. A negative constant against an unsigned type was the other exception: it threw `TYPE_MISMATCH` for a scalar (`toUInt8(0) < '-1'`) and a parse error inside a composite. Both are now below the minimum like any other out-of-range value: the classifier returns `BelowMin` for a non-zero negative literal, and the checked integer reader reports a negative value for an unsigned type as an overflow, `-0` included. A scalar `-0` keeps its old behaviour. Conversions that store the value (`values`, `INSERT`) still reject an out-of-range integer, now also when it is negative. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…igned
When a quoted composite constant is re-read with 256-bit integer elements,
the resulting pair of types was passed to executeImpl without going through
getReturnTypeImpl. For `[(toUInt256(0), toNullable(toUInt8(1)))] < '[(-1,1)]'`
the signed retry gives `Array(Tuple(Int256, Nullable(Int256)))`, which has no
common type with the column, so the arrays were ordered lexicographically with
a Nullable element result and the ColumnUInt8 cast failed (a Bad cast logical
error in debug builds, an invalid static_cast in release). The unquoted
`[(-1,1)]` is rejected by getReturnTypeImpl for the same reason. Now the wider
pair must be accepted by getReturnTypeImpl with the same result type,
otherwise the constant is treated as not convertible: equality answers 0,
ordering raises ARGUMENT_OUT_OF_BOUND.
A Map is compared only through the common type of both maps, and the signed
retry turned every integer element into Int256, including a UInt256 one that
then had no common type with its original:
`map(toUInt8(0), toUInt256(0)) > '{-1:0}'` raised NO_COMMON_TYPE while the
unquoted `map(-1, 0)` gives 1. A new carrier, tried before the all-signed one,
widens to Int256 every element except UInt256, which keeps a common type with
every original element, so `Map(Int256, UInt256)` is used here.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Algunenano
left a comment
There was a problem hiding this comment.
I really like the direction of this PR, but I see that we've added a new ErrorCode (INTEGER_TEXT_OVERFLOW) and I don't see any test using it.
The code never reached a user: it was thrown only by the overflow-checked integer read that `convertFieldToType` enables for a quoted composite literal, and caught right there. Throw `VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE` instead. That code is also thrown for an out-of-range `Date` or `DateTime` element (with `date_time_overflow_behavior = 'throw'`), so the catch is keyed on the checked read only: such an error is swallowed there and thrown again by the unchecked validation read, as before. Catching it in the validation read too would turn the error into a comparison result of 0; the two new test rows fail that way. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. That code is also raised for an out-of-range |
Two master changes made comparisons that used to throw return a result, and the tests pinned the old exceptions: - ClickHouse#122245 compares a string constant with an integer outside the range of the column type in a wider integer type, so `UInt64 = '-42'` is `0` instead of `TYPE_MISMATCH`. `05101` now uses `'42.5'`, which integer runtime types still fail to parse, for the exception, and checks that `'-42'` matches nothing. - ClickHouse#124680 compares decimals of different scales exactly, so rescaling `Decimal(18, 2)` to the scale of `toDecimal64(1, 3)` no longer throws `DECIMAL_OVERFLOW`. `05103` now checks that the index keeps the matching row next to a value whose rescaling overflows. Both are intended behaviour. The index stays conservative for them: it keeps the granules where the conversion of the constant fails. Without the overflow check (`decimal_check_overflow = 0`) execution rescales with wraparound, which is why the index still keeps decimal types whose rescaling may overflow; the comment now says so. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113022&sha=c543bed2acf878e6046ff4920f52b901e3d77d7f&name_0=PR&name_1=Fast%20test PR: ClickHouse#113022 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
Related: #121719
Related: #120204
Related: #122368
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A string constant compared with a column now compares by value when an integer in it does not fit the column type, both for a scalar and inside a quoted
Array,TupleorMapliteral, like the same literal unquoted. Such an integer used to wrap around (toUInt64(0) = '18446744073709551616'and[toUInt8(44)] = '[300]'were1), ordering comparisons answered0in both directions (toInt32(0) < '2147483648'), a negative constant against an unsigned type threw, andALTER TABLE ... DROP PARTITION '18446744073709551616'dropped partition0.INsets, primary key ranges andvalues()no longer accept the wrapped value.Description
On 26.8.10.6 and 25.3.14.14,
SELECT toInt32(0) < '2147483648'returns0instead of1,SELECT toUInt64(0) = '18446744073709551616'returns1instead of0, andALTER TABLE t DROP PARTITION '18446744073709551616'drops partition0instead of being rejected.Found by the nightly
SQLancerPP (arm_release)NoRECoracle on true master, red on 9 of the last 10 nightlies: 2026-09-13 job.One rule: an integer in a string constant that does not fit the compared type is compared by its value and never wraps.
convertFieldToTypeparsed integer text without an overflow check. A scalar literal is now range-checked, and inside a quotedArray/Tuple/Mapthe element reader checks overflow (an opt-in mode ofreadIntTextUnsafe, folded from Reject an integer nested in a quoted composite literal that does not fit the element type #122368). The constant then becomesNull, which fixes=/!=,INsets, key ranges,ALTER ... PARTITIONandvalues()at once.executeWithConstStringfolded every ordering operator to false on a failed conversion. A scalar now answers by the side of the range the constant is on. A composite is re-read with 256-bit integer elements and compared generically, so[toUInt8(43)] < '[300]'is1like[toUInt8(43)] < [300]. Only integers that fit no 256-bit element, or element types the comparison also rejects for the unquoted literal, raiseARGUMENT_OUT_OF_BOUNDin an ordering comparison.TYPE_MISMATCH.01311_comparison_with_constant_stringand02864_statistics_bug_67742recorded the old answers and are updated.Workflow [PR]
Sync PR [sync-upstream/pr/122245]
Version info
26.11.1.437-master(included in26.11and later)