Skip to content

Fix comparisons, IN sets and partition ids built from an out-of-range integer string constant - #122245

Merged
Algunenano merged 21 commits into
ClickHouse:masterfrom
groeneai:fix-ordering-comparison-out-of-range-string-constant
Oct 21, 2026
Merged

Algunenano merged 21 commits into
ClickHouse:masterfrom
groeneai:fix-ordering-comparison-out-of-range-string-constant

Conversation

@groeneai

@groeneai groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121719
Related: #120204
Related: #122368

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):

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, Tuple or Map literal, like the same literal unquoted. Such an integer used to wrap around (toUInt64(0) = '18446744073709551616' and [toUInt8(44)] = '[300]' were 1), ordering comparisons answered 0 in both directions (toInt32(0) < '2147483648'), a negative constant against an unsigned type threw, and ALTER TABLE ... DROP PARTITION '18446744073709551616' dropped partition 0. IN sets, primary key ranges and values() no longer accept the wrapped value.

Description

On 26.8.10.6 and 25.3.14.14, SELECT toInt32(0) < '2147483648' returns 0 instead of 1, SELECT toUInt64(0) = '18446744073709551616' returns 1 instead of 0, and ALTER TABLE t DROP PARTITION '18446744073709551616' drops partition 0 instead of being rejected.

Found by the nightly SQLancerPP (arm_release) NoREC oracle 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.

  • convertFieldToType parsed integer text without an overflow check. A scalar literal is now range-checked, and inside a quoted Array/Tuple/Map the element reader checks overflow (an opt-in mode of readIntTextUnsafe, folded from Reject an integer nested in a quoted composite literal that does not fit the element type #122368). The constant then becomes Null, which fixes =/!=, IN sets, key ranges, ALTER ... PARTITION and values() at once.
  • executeWithConstString folded 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]' is 1 like [toUInt8(43)] < [300]. Only integers that fit no 256-bit element, or element types the comparison also rejects for the unquoted literal, raise ARGUMENT_OUT_OF_BOUND in an ordering comparison.
  • A negative constant against an unsigned type is below the minimum like any other out-of-range value instead of throwing TYPE_MISMATCH.

01311_comparison_with_constant_string and 02864_statistics_bug_67742 recorded the old answers and are updated.


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

Version info

  • Merged into: 26.11.1.437-master (included in 26.11 and later)

groeneai and others added 3 commits September 25, 2026 12:04
… 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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 25, 2026
@groeneai

groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed this diff cold, then adjudicated its findings against the recorded
evidence. Verdicts below.

# Finding Verdict
❌ 1 An out-of-range integer nested in a quoted composite literal ('[18446744073709551616]') still wraps, so Array/Tuple/Map equality against it answers true and values() materialises [0]. Not blocking here. Real, and raised separately. See below.
❌ 2 The conversion reports "not representable" by returning a Null Field, which is indistinguishable from SQL NULL. So for a Nullable target the out-of-range constant becomes NULL instead of an error, and a composite with a nullable element keeps it as a NULL member. Not blocking here. Pre-existing design, documented in tree, and not widened by this diff. See below.
⚠️ 3 The comment on the magnitude loop claimed that neither common::mulOverflow nor common::addOverflow reports overflow at the widest widths. Agreed, corrected. Only mulOverflow is a no-op there (arithmeticOverflow.h:177-208); addOverflow does check (:63-88). The comment now names only mulOverflow.
⚠️ 4 classifyIntegerLiteralRange parsed the literal before testing whether the target could be an integer at all, so an all-digit literal bound for a Decimal/DateTime/Enum target paid a UInt256 division per digit and then returned NotApplicable. Agreed, fixed. The type test now precedes the parse. Pure reorder: WhichDataType::isInt()/isUInt() cover exactly the 12 TypeIndex values the switch dispatches on, so the value returned is unchanged for every input.
💡 5 Ordering comparisons against a non-member enum literal are still non-complementary (e < 'zz' and e >= 'zz' are both 0). Not this fix. It is decided above this branch, is gated by validate_enum_literals_in_operators, and is the subject of #118398. Since #122672 master rejects such a literal, so the test row that pinned the old 0 was dropped after the master merge.

On 1. This diff cannot reach it: on a composite target the new classifier returns NotApplicable, and
the second layer is guarded by a failed conversion, which the wrapped parse does not produce, so the
composite path is byte-for-byte what it was before this diff in both layers. The unquoted form
arr = [18446744073709551616] is already correct through the per-element recursion, so quoting is the
discriminator and the remedy lives in a different layer: either moving SerializationNumber::deserializeText
off readIntTextUnsafe, or teaching the classifier to parse composite text. Either is its own PR, and I
have filed it with the mechanism, the reachable queries and the probe numbers. The same fix class was landed
twice in this same function this month, one branch per PR (b50a2a408e13d, e3f838ce656ad).

On 2. For a non-nullable target an out-of-range constant is now rejected and the test pins it. For a
nullable target it becomes NULL, because the conversion reports "not representable" by returning a Null
Field and its consumers deliberately treat that like a source NULL when the type can hold one. That
predates this change and is stated in tree (convertFieldToType.cpp:853-869, and the header already
documents convertFieldToType(Field(1e300), Float32, .., false, true) -> Null). What this PR does change is
that a nullable column used to store the wrapped value: '18446744073709551616' into Nullable(UInt64)
stored 0, and now stores NULL. In an IN set the scalar path already keeps the two outcomes apart on
purpose (convertColumnToType.cpp:186-199, SetUtils.cpp:406-409); only a composite with a nullable element
absorbs it, which is finding 1's neighbourhood. Distinguishing them everywhere means a tri-state return
across about twenty call sites, against the in-tree comment's explicit choice. Glad to do that if you want
the boundary moved, but not inside this PR.

Scope note. The range check sits in the shared conversion, so it reaches =/!=, IN sets,
KeyCondition bounds, ALTER ... PARTITION and values(), not only the comparison the oracle found. That
breadth is deliberate, because fixing the comparison alone would leave IN admitting the wrapped value.
Every other consumer of a failed conversion already declines rather than guessing, which I verified site by
site. Happy to split the conversion layer into its own PR and land the comparison fix first if the breadth is
unwelcome.

Two silent answers become errors, and in both cases the error is the one the header already documents:
ALTER TABLE ... DROP PARTITION '<out of range>' and values('x UInt8', '<out of range>') now raise
ARGUMENT_OUT_OF_BOUND instead of using a wrapped value. Everything that raised before still raises with the
same code.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no table: SELECT toInt32(0) < '2147483648' returns 0 (must be 1) and SELECT toUInt64(0) = '18446744073709551616' returns 1 (must be 0), on official 26.8.10.6 and 25.3.14.14 and on master. Plus the oracle's own recovered script.
b Root cause explained? Two composing causes. convertFieldToType's string branch parses integers with an unchecked reader, so a literal too large comes back wrapped instead of Null, breaking the range contract its header documents; on top of that, executeWithConstString folds all four ordering operators to false whenever that conversion fails, which is right for =/!= but wrong for two operators in each direction and destroys NOT (x <= C) <=> (x > C).
c Fix matches root cause? Yes. The range check goes where the contract is broken (constant conversion only, never the bulk-ingestion reader), and the comparison answers from the direction the conversion already knew. No widened bound, no new setting, no guard at the symptom site. LogicalExpressionOptimizerPass and KeyCondition stay untouched: both already bail safely, and that bail becomes the correct outcome (measured: Condition: true, Granules: 3/3, nothing pruned).
d Test intent preserved / new tests added? New stateless test with 40 assertion rows over every carrier; 01311_comparison_with_constant_string, which already recorded two of these cells as -- this is wrong for now, has exactly those two markers removed and those two reference values flipped. The flip is load-bearing in both directions: 01311 fails on the fixed build if left unflipped, and fails on the unpatched build once flipped.
e Both directions demonstrated? Yes, on two builds of this tree: 24 of the new test's 40 rows differ between the unpatched and the fixed binary (the other 16 are must-not-regress controls), and both tests FAIL on the unpatched one. The unpatched run's first failure is ALTER TABLE ... DROP PARTITION '18446744073709551616' succeeding where the test expects a rejection.
f Fix is general across code paths? Censused, not assumed: the comparison function is the only site in src/ that folds a comparison's result on a failed constant conversion. Every other consumer of a Null conversion declines an optimization, raises, or materializes a value, and for those the range check turns a silently wrapped value into a rejection (measured: values('x Int32', '<100 digits>') returned 0, now raises ARGUMENT_OUT_OF_BOUND).
g Fix generalizes across inputs (params/datatypes/wrappers)? All 12 integer widths at max+1 and, for signed, min-1, each in the < and the > form (only > separates a rejected constant from a wrapped one); both directions; both operand orders; all four operators; Nullable, LowCardinality, LowCardinality(Nullable), materialize, FixedString; the in-range extremes as controls; magnitudes past UInt256 in both signs, swept from 20 to 400 digits; + sign, leading zeros, a NULL constant; Float32/Date/Decimal/Enum/Bool/UUID/IPv4/DateTime/BFloat16 targets byte-identical.
h Backward compatible? (maintainer-approved exception only) No setting, so no SettingsChangesHistory.cpp entry; no serialization, format, on-disk or wire surface; deterministic and per-node. Results change only where they were wrong. Two silent answers become errors, both being the contract the header already documents: ALTER ... DROP PARTITION with an out-of-range id now raises instead of dropping the partition the value wrapped onto, and values() raises instead of inserting a wrapped value. Everything that raised before still raises with the same code: 7 cases measured (TYPE_MISMATCH x3, DECIMAL_OVERFLOW, CANNOT_PARSE_BOOL x2).
i Invariants and contracts preserved? One is restored: out-of-range values are now rejected for a string source, as convertFieldToType.h already promised, and IN membership stays consistent with =. The classifier is total and side-effect-free, returning "not applicable" for a non-integer target, a custom serialization, a non-integer literal and a negative literal against an unsigned type, so no previously-correct or previously-throwing path is re-answered. The new constant return matches the two already in the function, and the nullable wrapper reassembles the null map (measured). No lock, allocation or durability surface.

Session id: cron:clickhouse-impl-slot-4:20260925-105300

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c9457d7]

Summary: ✅


AI Review

Summary

Fixes out-of-range integer string constants in scalar and quoted composite comparisons, IN sets, and partition/value conversion. The previous inline findings are addressed, and no new actionable issues were found. Against PR head c9457d7391f4, focused comparison probes and all 60 statements of the new composite regression test passed, including expected exceptions and exact reference output.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 x <= C and NOT (x <= C) matched the same rows and filter push-down below a join then dropped every row; the constant is now range-checked in convertFieldToType, and the fold answers by the direction of the overflow. It touches the same function as #121719, which instead rejects such a comparison at analysis time.

@Algunenano Algunenano self-assigned this Sep 25, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 25, 2026
`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.
groeneai and others added 6 commits September 25, 2026 16:09
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]>
Comment thread src/Interpreters/convertFieldToType.cpp Resolved
groeneai and others added 2 commits September 26, 2026 00:22
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit c9457d7391f4ec049eaa48e4a9278c226f1598ab was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 35 queries analysed

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
  • StressHouse run: 82c04495-589e-44a8-ae74-91226a85277d
  • MIRAI run: 53e1352e-4525-4356-9d29-121cba68f354
  • PR check IDs:
    • clickbench_2670444_1790833925
    • clickbench_2670450_1790833926
    • clickbench_2670460_1790833925
    • tpch_adapted_1_official_2670486_1790833926
    • tpch_adapted_1_official_2670500_1790833926
    • tpch_adapted_1_official_2670514_1790833926

groeneai and others added 3 commits October 10, 2026 12:02
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 654de01

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore flaky, not from this PR: UNKNOWN_TABLE (code 60) for the initiator-local _materialized_cte_c_* table when a reused MATERIALIZED CTE is read through parallel replicas with a local plan; 128 of 128 reruns pass. More than 70 PRs and 5 master runs show it since 2026-10-08 #123121 (mine, open)
Mergeable Check, PR praktika rollups of the row above #123121 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261010-180005

groeneai and others added 2 commits October 13, 2026 18:33
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]>
Comment thread src/Functions/FunctionsComparison.h Resolved
Comment thread src/Interpreters/convertFieldToType.cpp Resolved
…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 Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks. INTEGER_TEXT_OVERFLOW never reached a user: only the overflow-checked integer read that convertFieldToType enables for a quoted Array/Tuple/Map literal threw it, and the same function caught it (its only trace was the system.errors counter), so no test could produce it. I removed it in c9457d7: the checked read now throws the existing VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE.

That code is also raised for an out-of-range DateTime element under date_time_overflow_behavior = 'throw', so only the checked read swallows it and the unchecked validation read rethrows it as before. The two new rows in 05258 pin that: catching it in both reads turned [toDateTime(...)] = '[''2200-01-01 00:00:00'']' into 0 instead of the error.

@Algunenano
Algunenano added this pull request to the merge queue Oct 21, 2026
Merged via the queue into ClickHouse:master with commit 2d9380b Oct 21, 2026
178 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 21, 2026
rorylshanks added a commit to rorylshanks/ClickHouse that referenced this pull request Nov 4, 2026
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
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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants