Repository navigation
Validate IN tuple/subquery column count mismatch in analyzer - #97540
Conversation
When a tuple on the left side of `IN` has a different number of elements than the number of columns in the subquery on the right side, the query is semantically invalid. Previously, constant folding could optimize away the `IN` expression before this mismatch was detected, silently hiding the error. For example, `(1, 1) IN (SELECT 1)` wrapped in a subquery with a constant-false outer WHERE would succeed without error. This adds validation during analysis in `resolveFunction` to check the column count before any constant folding can mask the issue. Closes #74442 Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Workflow [PR], commit [beccda2] Summary: ✅
AI ReviewSummaryThis PR adds analysis-time validation for Findings
Final Verdict
LLVM Coverage ReportMeasured on commit beccda2.
Changed lines: Changed C/C++ lines covered: 88/98 (89.80%) · Uncovered code |
…ry-column-count-mismatch
…ry-column-count-mismatch
The IN column count validation was too strict: it rejected cases where the right-side subquery returns a single Tuple column (e.g., `(a, b) IN (SELECT tuple(a, b))`). In `FunctionIn`, when the right side is a single column, the entire left-side value is compared against it as one value, so this is valid. Fix: when the right side returns exactly one column of Tuple type, skip the column count mismatch check. Update tests that had genuinely invalid column count mismatches (scalar `IN` multi-column subquery) to expect `NUMBER_OF_COLUMNS_DOESNT_MATCH`. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ry-column-count-mismatch
The complex query with `WHERE NULL` causes the subquery to be constant-folded before the IN column count validation runs, so the validation does not catch this case. Remove the incorrect `serverError` annotation and update the reference to match actual output. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ry-column-count-mismatch
…notation The inner `1024 IN (SELECT [NULL, ...], number FROM numbers(7, 100))` has 1 column on the left and 2 on the right. The analyzer resolves this inner IN before any constant folding of the outer `WHERE NULL`, so the `NUMBER_OF_COLUMNS_DOESNT_MATCH` exception is correctly thrown. Restore the `serverError` annotation and correct the reference file. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ry-column-count-mismatch
The IN column count validation does not fire for subqueries with `WHERE NULL` due to early optimization, so the `serverError` annotation was incorrect. Restore the original test behavior.
…ation The inner `1024 IN (SELECT [NULL, ...], number FROM numbers(7, 100))` has 1 column on the left and 2 on the right. The analyzer resolves this before any constant folding of the outer `WHERE NULL`, so `NUMBER_OF_COLUMNS_DOESNT_MATCH` is correctly thrown. Add `serverError` annotation and update the reference file. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Strip both `LowCardinality` and `Nullable` wrappers when checking whether the right side of IN is a single Tuple column. Previously only `Nullable` was stripped, causing a false `NUMBER_OF_COLUMNS_DOESNT_MATCH` for `LowCardinality(Tuple(...))`. Add test cases for `LowCardinality`, `Nullable`, and plain `Tuple`. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ry-column-count-mismatch # Conflicts: # contrib/rust_vendor
…tion, remove invalid test case - Use `removeLowCardinalityAndNullable` for the left argument of IN (was only `removeNullable`), making it symmetric with the right side. - Remove the `LowCardinality(Tuple(UInt8, UInt8))` test case because `LowCardinality` does not support `Tuple` as an inner type in ClickHouse. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ry-column-count-mismatch
…ble(Tuple(...))`
The Fast test was failing on
SELECT (1, 2) IN (SELECT CAST((1, 2), 'Nullable(Tuple(UInt8, UInt8))'));
because creating a `Nullable(Tuple(...))` column requires the experimental
setting `allow_experimental_nullable_tuple_type = 1`. Enable it before the
query to keep coverage for the `Nullable`-wrapped single-tuple column path
in the `IN` column count validation.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97540&sha=4cd10acca051f6c09476f7f406a64cf4bf0e7362&name_0=PR&name_1=Fast%20test
PR: #97540
…ry-column-count-mismatch
`37e0e41393c9` made `validateInColumnsCountMatch` skip left-hand types with a dynamic structure, so a `Variant` left side is no longer rejected by the analyzer-time one-key cast check: `IN` itself refuses to cast `Variant(Tuple(UInt16, UInt64), UInt8)` to `Tuple(Int8, UInt64)` and throws `TYPE_MISMATCH` instead of `CANNOT_CONVERT_TYPE`. Verified locally that the error is identical with `rewrite_in_to_join` 0 and 1, which is what the test asserts.
|
🕵 Fixed the |
…Tuple` right column The scalar-versus-tuple guard in `validateInColumnsCountMatch` rejected every left type that is not a raw top-level `DataTypeTuple` as soon as the single right column was a `Tuple`. That is too broad in two ways: * A `Nullable(Tuple(...))` (or `LowCardinality(...)`) left side is a tuple key, not a scalar: `FunctionIn` keeps it as one key and `Set` strips those wrappers, so comparing it against a single right `Tuple` column is a perfectly valid one-key comparison. Rejecting it broke the master test `03714_tuple_inside_nullable_for_in_function_non_literal`, which failed in six stateless jobs with `Cannot cast Nullable(Tuple(Int32, Int32)) to Tuple(Int32, Int32) in IN`. * Even a non-tuple left type is not necessarily a mismatch: `Set::execute` casts the whole left value to the single right key type, and `String` is parsed into the tuple by `FunctionCast::createTupleWrapper`, so `SELECT '(1,2)' IN (SELECT CAST((1, 2), 'Tuple(UInt8, UInt8)'))` must stay valid (review finding by `clickhouse-gh`). Compare the set key types instead (`Nullable` / `LowCardinality` stripped, as `Set::getElementTypes` does) and, for a non-tuple left key, reuse the existing type-level castability probe: throw only when no cast path to the right tuple exists, which is exactly the genuine `1 IN (SELECT tuple(1))` shape. `04871_in_tuple_single_key_rewrite_in_to_join` is restored to the errors the runtime actually produces for a `Nullable(Tuple(...))` left side (`CANNOT_CONVERT_TYPE` for the overflowing one-key cast, identical under `rewrite_in_to_join` 0 and 1) and asserts that the valid wrapped one-key comparison returns rows again; `03380_in_tuple_subquery_column_count` gains the accepted `String`, `LowCardinality(String)` and `Nullable(Tuple(...))` shapes.
…ry-column-count-mismatch Criss-cross merge: `git merge-base --all` returns two bases (`74477eec80bb` from 2026-08-21 and `3087a9264673` from 2026-05-29), so the `ort` virtual base produced 302 conflicts although this branch touches only 18 files. Resolved mechanically: every conflicted file outside the branch's own file set was taken from `master` verbatim, and the three overlapping test files were re-merged against the real (newest) base with `git merge-file`, which merged cleanly. Verified that `git diff --cached origin/master --numstat` is byte-identical to the pre-merge `git diff 74477ee..HEAD --numstat` (18 files, +569/-19), i.e. the result is exactly master plus this branch's change, with no submodule gitlink drift.
|
🕵 Status update on What cleared: the 6 stateless reds from the previous head are gone, and Remaining reds on
Neither has a fix on @groeneai, could you investigate failure 1 ( About the Verified locally on a |
|
Covered by #115868 (mine, open and green since 2026-08-21). It came out of the same request on #109377, which is why it is not in the list above. Measured rather than read off titles, both arms built from the same commit (master
Control on the same two binaries: #115868's own reproducer goes 134 -> 0, so the arms discriminate. Your reading holds: no set is ever built for one copy of the subquery body, and it is not related to this PR (clean master reproduces it). One caveat on the artifacts. SET allow_experimental_correlated_subqueries = 1, correlated_subqueries_default_join_kind = 'left';
SELECT n FROM (SELECT number AS n FROM numbers(2) WHERE n IN (SELECT 1)) AS t WHERE 1 = (SELECT t.n);Mechanism: Why none of the five covers it: #113963 needs a MergeTree read and this query reads no table; #112968 is scoped to object storage, file and url |
…rrelated setting on the actual rewrite Two findings from the AI review on `f42b8f28c1c8`. 1. `FunctionIn::getReturnTypeImpl` rejects every left operand whose type has a dynamic structure with `ILLEGAL_TYPE_OF_ARGUMENT` before it looks at the set arity, including carriers whose dynamic structure comes from a nested member such as `Tuple(Dynamic, UInt8)`. `validateInColumnsCountMatch` exempted that family only in the scalar-left special case, so a nested carrier reached the arity branch and reported `NUMBER_OF_COLUMNS_DOESNT_MATCH` instead. Return early from the helper for any `hasDynamicStructure` left type - that error is raised during analysis as well, so constant folding cannot hide it. 2. The `allow_experimental_correlated_subqueries` check ran as soon as the right side of `IN` was a subquery, i.e. before `left_value_compared_as_single_key` decided that the shape stays on the regular `IN` path. Enabling `rewrite_in_to_join` alone therefore rejected such queries with `SUPPORT_IS_DISABLED` even though no correlated rewrite happens. Move the check into the branch that actually performs the rewrite. Regressions added to `03380_in_tuple_subquery_column_count` (nested dynamic carriers) and `04871_in_tuple_single_key_rewrite_in_to_join` (`rewrite_in_to_join = 1` with `allow_experimental_correlated_subqueries = 0`).
|
🕵 Status update on
Both requested regressions were added: Verified locally on a |
| || !left_result_type->equals(*rhs_query_node->getProjectionColumns().front().type)); | ||
| } | ||
|
|
||
| if (in_second_argument->as<QueryNode>() && !left_value_compared_as_single_key) |
There was a problem hiding this comment.
This rewrite guard is still broader than plain IN: it only skips the one-column RHS case, so it still reaches left-hand shapes that regular IN rejects before set construction.
Two concrete traces:
FunctionIn::getReturnTypeImplrejects any left type whosehasDynamicStructure()is true (src/Functions/in.cpp:67), but forCAST((number, 1), 'Tuple(Dynamic, UInt8)') IN (SELECT number, 1 FROM numbers(1))the RHS has two projection columns, soleft_value_compared_as_single_keystays false and this branch rewrites toEXISTS. That bypassesFunctionInentirely even though tuple/dynamic comparison is supported byequals, so the observable behavior now depends onrewrite_in_to_join.- The new
03380_in_tuple_subquery_column_counttest already documents that(x -> x) IN (SELECT 1)should stayILLEGAL_TYPE_OF_ARGUMENT, but hereleft_key_typeis null, so withrewrite_in_to_join = 1andallow_experimental_correlated_subqueries = 0we hit theSUPPORT_IS_DISABLEDbranch below instead of the regularINvalidation.
Please skip the rewrite whenever the resolved left side is not a valid plain-IN value shape (at least !left_result_type, left_result_type->hasDynamicStructure(), and bare LambdaNode), and add focused rewrite_in_to_join = 1 regressions for both cases.
|
Verified the fix on the head build — all mismatch shapes I tried (direct/folded, One residual of the same #74442 mechanism survives, and it is asymmetric with a shape this PR does catch: a one-element tuple on the left against a scalar column passes the count check (1 == 1), so constant folding can still hide the runtime error, while the mirror shape is caught at analysis: -- still silently returns an empty result at pure defaults (head build):
SELECT 1 FROM (SELECT 2 AS c1 WHERE tuple(1) IN (SELECT 1)) t0 WHERE t0.c1 = 1;
-- the direct spelling throws ILLEGAL_TYPE_OF_ARGUMENT (Code 43) at runtime:
SELECT tuple(1) IN (SELECT 1);
-- whereas the mirror is now rejected during analysis:
SELECT 1 IN (SELECT tuple(1)); -- TYPE_MISMATCH at analysisRoot cause: |
|
@alexey-milovidov @qoega — this PR looks backward incompatible but is categorized as Why: The throw at resolveFunction.cpp:1053-1056 rejects query shapes that returned a value in every released version and under both planners: on the 26.8.1 binary Suggested category: |
|
@alexey-milovidov @qoega — title/description suggestions: Description (currently
Ignore if intentional. |
…ble(Tuple(...))`
The Fast test was failing on
SELECT (1, 2) IN (SELECT CAST((1, 2), 'Nullable(Tuple(UInt8, UInt8))'));
because creating a `Nullable(Tuple(...))` column requires the experimental
setting `allow_experimental_nullable_tuple_type = 1`. Enable it before the
query to keep coverage for the `Nullable`-wrapped single-tuple column path
in the `IN` column count validation.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97540&sha=4cd10acca051f6c09476f7f406a64cf4bf0e7362&name_0=PR&name_1=Fast%20test
PR: ClickHouse#97540
The new validation in `resolveFunction` only runs in the new analyzer. On the "old analyzer" CI variant the affected queries either succeed silently (when the IN expression is constant-folded) or throw `ILLEGAL_TYPE_OF_ARGUMENT` instead of `NUMBER_OF_COLUMNS_DOESNT_MATCH`, so the `serverError` annotations added by this PR fail. Force `enable_analyzer = 1` for the queries that depend on the new behavior, leaving the surrounding tests untouched. CI report: ClickHouse#97540
Closes: #74442
The analyzer (
resolveFunction) now validates that the number of elements on the left side ofINmatches the number of columns in the right-side subquery. Previously, constant folding could optimize away theINexpression and silently hide the mismatch: for example,(1, 1) IN (SELECT 1)wrapped in a subquery with a constant-false outerWHEREsucceeded silently. Now it correctly throwsNUMBER_OF_COLUMNS_DOESNT_MATCHduring analysis. A singleTuplecolumn on the right side is still accepted, sinceFunctionIncompares the whole left-side value against it;LowCardinalityandNullablewrappers are unwrapped before the check. Covered by the new test03380_in_tuple_subquery_column_count, including the original reproducer from the issue.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Detect column count mismatch between a tuple and a subquery in the
INclause during analysis, preventing constant folding from silently hiding the error.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/97540]
Version info
26.9.1.459(included in26.9and later)