Skip to content

Fix exceptions and wrong results of IN when the keys and the set have different types - #119183

Merged
nihalzp merged 73 commits into
ClickHouse:masterfrom
nihalzp:fix-nullable-tuple-set-semantics
Nov 17, 2026
Merged

nihalzp merged 73 commits into
ClickHouse:masterfrom
nihalzp:fix-nullable-tuple-set-semantics

Conversation

@nihalzp

@nihalzp nihalzp commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

Closes: #104942
Related: #119081
Related: #117606
Related: #117245
Related: #61982
Related: #67230

Fix conversion exceptions and incorrect IN / NOT IN results for tuple keys, including Nullable(Tuple). Skip outer NULL payloads, report failed tuple-field conversions consistently, and reject timestamp conversions that create false matches through truncation or range overflow.

Bug 1: Outer NULL keys raise conversion exceptions.

An outer NULL cannot match a non-nullable set key. Its hidden payload must not be converted before the row is excluded.

SET enable_nullable_tuple_type = 1;

SELECT (k, 1) IN (SELECT tuple(toUInt8(1)), 1)
FROM (SELECT materialize(CAST(NULL, 'Nullable(Tuple(UInt8))')) AS k)
SETTINGS transform_null_in = 0;
-- Expected: 0
-- Before PR: a `CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN` exception.

The same problem affects NULL tuples with a String field when transform_null_in = 1: parsing the hidden empty string raises an exception even though the row cannot match.

SELECT (k, 1) IN (SELECT tuple(toUInt8(1)), 1)
FROM (SELECT materialize(CAST(NULL, 'Nullable(Tuple(String))')) AS k)
SETTINGS transform_null_in = 1;
-- Expected: 0
-- Before PR: a `CANNOT_PARSE_TEXT` exception.

Bug 2: Failed tuple-field conversions throw instead of returning NULL or a non-match.

Tuple keys supported by accurateCastOrNull should treat failed conversions as non-matching rows, as scalar keys do.

SELECT (tuple(materialize('bad')), 1) IN (SELECT tuple(toUInt8(1)), 1)
SETTINGS transform_null_in = 0;
-- Expected: 0
-- Before PR: a `CANNOT_PARSE_TEXT` exception.

The underlying accurateCastOrNull call must return a NULL tuple when a field fails to convert. Numeric and enum parsers both need to honor this policy.

SELECT isNull(accurateCastOrNull(tuple(materialize('bad')), 'Tuple(UInt8)'));
-- Expected: 1
-- Before PR: a `CANNOT_PARSE_TEXT` exception.
SELECT isNull(accurateCastOrNull(tuple(materialize('bad')), 'Tuple(Enum8(\'a\' = 1))'));
-- Expected: 1
-- Before PR: an `UNKNOWN_ELEMENT_OF_ENUM` exception.

Bug 3: Reducing timestamp precision creates false matches.

Non-NULL Nullable(DateTime64) values used as scalar components of multi-column IN keys skipped the sub-second check. The half-second timestamp below must not match a whole-second DateTime key.

SELECT (ts, 1) IN (SELECT toDateTime('2026-01-01 00:00:00', 'UTC'), 1)
FROM (SELECT materialize(toNullable(toDateTime64('2026-01-01 00:00:00.500', 3, 'UTC'))) AS ts)
SETTINGS transform_null_in = 0;
-- Expected: 0
-- Before PR: 1

The check must also reach fields inside composite keys. Here, .123 and .12 differ; casting the left key to the set’s lower precision must not make them match.

SELECT (k, 1) IN (SELECT tuple(toDateTime64('2026-01-01 00:00:00.12', 2, 'UTC')), 1)
FROM (SELECT toNullable(tuple(toDateTime64('2026-01-01 00:00:00.123', 3, 'UTC'))) AS k)
SETTINGS transform_null_in = 0;
-- Expected: 0
-- Before PR: 1

Bug 4: Out-of-range timestamps match the destination boundary.

The input is one second beyond the largest DateTime value. A cast that clamps it to that boundary must not make it equal to the boundary key.

SELECT (k, 1) IN (SELECT tuple(toDateTime(4294967295, 'UTC')), 1)
FROM (SELECT toNullable(tuple(toDateTime64(4294967296, 0, 'UTC'))) AS k)
SETTINGS transform_null_in = 0;
-- Expected: 0
-- Before PR: 1

The following two fixes affect scalar conversions independently of Nullable(Tuple). They are included in the shared parsing and timestamp-conversion changes.

Bug 5: Decimal parsing rejects valid zero-padded FixedString values.

Trailing zero bytes are padding, so 1.25 remains valid decimal text.

SELECT toDecimal64OrNull(materialize(toFixedString('1.25', 8)), 2);
-- Expected: 1.25
-- Before PR: NULL

Bug 6: Fractional timestamps fail to match equivalent floating-point keys.

The value 0.5 is exactly representable as Float64. Precision-loss checks must allow this conversion to match.

WITH toDateTime64(0.5, 3, 'UTC') AS t
SELECT (t, 1) IN (SELECT toFloat64(0.5), 1)
SETTINGS transform_null_in = 0;
-- Expected: 1
-- Before PR: 0

Bug 7: Floating-point keys match every timestamp within their resolution.

A float holds a timestamp only to its own resolution, so the cast maps distinct DateTime64 values to one float: about 240 nanosecond ticks for Float64 in 2026, and 128 seconds for Float32. Only the timestamp that the float converts back to matches it.

SELECT (toDateTime64('2026-01-01 00:00:01', 3, 'UTC'), 1) IN (SELECT toFloat32(1767225600), 1);
-- Expected: 0
-- Before PR: 1

Bug 8: A NULL field inside a Nullable(Tuple) key never matched a constant set member.

A NULL field of a non-NULL tuple is part of the key value, as it already is when the set comes from a subquery. Constant sets skipped such members and the row-wise IN arr rewrite guarded against such keys with transform_null_in = 0. Only a plain tuple with several elements is a multi-column key, where a NULL element never matches.

SET enable_nullable_tuple_type = 1;

SELECT CAST(tuple(NULL), 'Nullable(Tuple(Nullable(UInt8)))') IN [tuple(NULL)]
SETTINGS transform_null_in = 0;
-- Expected: 1
-- Before PR: 0, although the same key matches through a subquery
SELECT tuple(NULL) IN arr FROM (SELECT [tuple(NULL)] AS arr)
SETTINGS transform_null_in = 0;
-- Expected: 1
-- Before PR: 0

JOIN keys with LowCardinality(Nullable) tuple elements take the common-subtype fallback like plain Nullable elements, since accurateCastOrNull reports their NULLs through the tuple's null map; JoinCommon::tryGetCommonSubtypeForJoinKeys no longer rejects them with NO_COMMON_TYPE.

The implementation shares null-map combination and tuple field mapping, including named fields, and keeps rejected timestamp conversions separate from genuine SQL NULLs. Ordinary CAST retains its existing truncation behavior.

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

IN and NOT IN no longer fail with an exception when a tuple left-hand column with NULL rows or NULL fields, such as a Nullable(Tuple) column, has to be converted to the set's key type, and no longer report false matches when a DateTime64 value loses sub-second precision or exceeds the DateTime range in that conversion; a fractional DateTime64 value now matches an equal Float64 value. accurateCastOrNull to a tuple type returns NULL instead of throwing when one of the fields cannot be converted, and toDecimal*OrNull and toDecimal*OrZero accept zero-padded FixedString input. A DateTime64 value matches a floating-point set key only when the key converts back to the same timestamp, and JOIN keys whose tuple elements are LowCardinality(Nullable) take the common-subtype fallback instead of failing with NO_COMMON_TYPE.


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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e8dfcea]

Summary: ✅


AI Review

Summary

The PR fixes tuple-key NULL handling and tuple-field conversion failures, rejects lossy timestamp membership conversions, and restricts rewrite_in_to_join to preserve set semantics. Reviewed head e8dfceae52e10eb08bba0f6afb410d5b1149a058, including the current diff, surrounding conversion and set code, all review threads and replies, and the top-level discussion. No new actionable findings remain.

Nullable-result consumers traced: createTupleWrapper collects field failures; prepareUnpackDictionaries expands dictionary results back to rows; createVariantToColumnWrapper and ConvertImplFromDynamicToColumn::execute unify converted alternatives' nullability; array and map wrappers retain strict text conversion; FunctionCastOrDefault selects defaults through outer null maps. The pre-existing numeric-container layout limitation is tracked in #132281.

The previous review's outstanding aggregate-state rewrite concern is now tracked in #132301, satisfying the requested follow-up option. Previously discussed numeric enum, timestamp range, boolean index, and composite boolean cases are tracked separately in #132250, #132251, #132252, and #132253. These accepted follow-ups do not require reopening the resolved threads.

Validation with the head's Fast test binary: all 12 targeted regression files matched their references, and all 13 separately executed expected-error cases produced the expected exception codes. The PR head remained unchanged throughout the review.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 10, 2026
Comment thread src/Interpreters/Set.cpp Resolved
@nihalzp
nihalzp requested a review from Avogar September 10, 2026 11:30
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e8dfceae5 with master 30c7f43ee (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

146 object files changed (-209.90 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion.cpp.o 25.35 MiB 24.96 MiB -397.56 KiB (-1.53%)
src/CMakeFiles/dbms.dir/Interpreters/getDateTime64CastLossMap.cpp.o new 71.74 KiB +71.74 KiB
src/CMakeFiles/dbms.dir/Functions/CastOverloadResolver.cpp.o 359.46 KiB 403.57 KiB +44.11 KiB (+12.27%)
src/CMakeFiles/dbms.dir/DataTypes/NullableUtils.cpp.o 60.65 KiB 79.01 KiB +18.36 KiB (+30.27%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

3010 translation units recompiled, 21643 s compile time in total, 3009 of them have a recent master baseline.

Job report

Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Interpreters/castColumn.cpp Resolved
Comment thread src/Interpreters/castColumn.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Interpreters/Set.cpp Resolved
Comment thread src/Interpreters/Set.cpp Resolved
Comment thread src/Interpreters/Set.cpp Resolved
…ull_in = 0`, as primary-key analysis keeps the bytes
@nihalzp

nihalzp commented Nov 17, 2026

Copy link
Copy Markdown
Member Author

@groeneai The review raised four bugs that are also on master, so they are out of scope for this PR. Open one issue for each, with its reproducer, and say in it that it reproduces on master. Then reply here with the links.

  1. accurateCastOrNull of a number that is not a value of the Enum throws UNKNOWN_ELEMENT_OF_ENUM instead of returning NULL, as a scalar and as a tuple field: Fix exceptions and wrong results of IN when the keys and the set have different types #119183 (comment)
  2. accurateCastOrNull of a DateTime64 that does not fit a narrow numeric type throws DECIMAL_OVERFLOW instead of returning NULL, and IN with a subquery set throws too: Fix exceptions and wrong results of IN when the keys and the set have different types #119183 (comment)
  3. Primary-key analysis disagrees with IN for a Bool set over an integer column: with x UInt8 = 2, x IN (SELECT true) returns the row without the index and drops it with the index, because KeyCondition::tryPrepareSetColumnsForIndex turns true into the point 1: Fix exceptions and wrong results of IN when the keys and the set have different types #119183 (comment)
  4. A Bool inside a tuple or array key of IN is compared by its raw byte unless another field forces a cast, because castColumn returns the column untouched when IDataType::equals holds: Fix exceptions and wrong results of IN when the keys and the set have different types #119183 (comment)

…of tuple elements, so that array and map elements convert to their declared types
@groeneai

Copy link
Copy Markdown
Collaborator
  1. accurateCastOrNull of a number that is not a value of the Enum throws UNKNOWN_ELEMENT_OF_ENUM instead of returning NULL #132250
  2. accurateCastOrNull of a DateTime64, Decimal or Time64 that does not fit a narrow numeric type throws DECIMAL_OVERFLOW instead of returning NULL, and IN with a subquery set throws too #132251
  3. Index analysis skips rows that IN matches for an integer key and a Bool subquery set: x IN (SELECT true) returns x = 2 only without the index #132252
  4. IN (subquery) compares a Bool inside a Tuple or Array key by its raw byte unless another element needs a conversion #132253

Each has its reproducer and says it reproduces on master (fdc4389b67de); 1, 2 and 4 also reproduce on 26.10.3.7. Two additions from the measurements: in 2, a Decimal or Time64 source throws the same way, and a DateTime source wraps instead (accurateCastOrNull(toDateTime(256, 'UTC'), 'UInt8') returns 0). In 3, the set(0) skip-index variant does reproduce for me on master: use_skip_indexes = 0 returns [2] and use_skip_indexes = 1 returns [] (queries in the issue).

@nihalzp

nihalzp commented Nov 17, 2026

Copy link
Copy Markdown
Member Author

@groeneai Open an issue for the remaining case of the AI review, and say in it that it reproduces on master: accurateCastOrNull to an explicitly nullable tuple fails with LOGICAL_ERROR when an element of an array or a map goes through a numeric conversion. Under CastType::accurateOrNull that conversion returns a ColumnNullable even when failures were not asked for, and the array or the map keeps it, so the column does not match the declared type:

SELECT accurateCastOrNull(tuple(materialize([toUInt16(1)])), 'Nullable(Tuple(Array(UInt8)))')
SETTINGS enable_nullable_tuple_type = 1;

The same holds for numeric map values, numeric tuples inside arrays and numeric Variant array elements. Then reply here with the link.

@groeneai

Copy link
Copy Markdown
Collaborator

#132281

It reproduces on master (fdc4389b67de) and on 26.10.3.7, also for a numeric map key, a Dynamic array element, a nested array and an integer-to-float element. With the same targets, accurateCastOrDefault does not throw on 26.10.3.7 and returns values that do not come from the input ([1, 2, 300] gives [144, 230, 155]), so the issue covers it too.

@nihalzp
nihalzp added this pull request to the merge queue Nov 17, 2026
@nihalzp nihalzp changed the title Fix exceptions and wrong results of IN with Nullable(Tuple) and DateTime64 keys Fix exceptions and wrong results of IN when the keys and the set have different types Nov 17, 2026
Merged via the queue into ClickHouse:master with commit 42a270d Nov 17, 2026
380 checks passed
@nihalzp
nihalzp deleted the fix-nullable-tuple-set-semantics branch November 17, 2026 13:29
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 17, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 21, 2026
…t-numbers-by-value

ClickHouse#119183 moved the conversion of `IN` keys into `Set::castToKeyType`, so the
exact-value conversion of a number for a `Bool` key moves there: such a probe
converts into `UInt8` instead of `Bool`, and the number alternatives of a
`Variant` probe are converted again after the cast of the whole column.

ClickHouse#129731 made `SimpleAggregateFunction(f, Bool)` keep `Bool` values, so a key
of that type gets the same exact-value conversion, and a probe of that type
keeps the `Bool` one.

Expectations that encoded the collapse of a number into `true` change:
05168 (`materialize(toUInt8(2)) IN (SELECT true)` with
`transform_null_in = 0` is now 0, as it already was with
`transform_null_in = 1`), 05556 `same as bool` (`[1]` for both sets) and the
`u` lines of 05406. 04871 keeps its expectations: its `Bool` byte 2 is now
a `Bool` from `reinterpret` instead of a `UInt8`, which the set compares by
value.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-bugfix Pull request with bugfix, not backported by default 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.

Nullable(DateTime64) precision check skipped due to getDataType() returning TypeIndex::Nullable

5 participants