Skip to content

Validate IN tuple/subquery column count mismatch in analyzer - #97540

Merged
qoega merged 125 commits into
masterfrom
fix-in-tuple-subquery-column-count-mismatch
Aug 31, 2026
Merged

qoega merged 125 commits into
masterfrom
fix-in-tuple-subquery-column-count-mismatch

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Feb 21, 2026 •

Copy link
Copy Markdown
Member

Closes: #74442

The analyzer (resolveFunction) now validates that the number of elements on the left side of IN matches the number of columns in the right-side subquery. Previously, constant folding could optimize away the IN expression and silently hide the mismatch: for example, (1, 1) IN (SELECT 1) wrapped in a subquery with a constant-false outer WHERE succeeded silently. Now it correctly throws NUMBER_OF_COLUMNS_DOESNT_MATCH during analysis. A single Tuple column on the right side is still accepted, since FunctionIn compares the whole left-side value against it; LowCardinality and Nullable wrappers are unwrapped before the check. Covered by the new test 03380_in_tuple_subquery_column_count, including the original reproducer from the issue.

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

Detect column count mismatch between a tuple and a subquery in the IN clause during analysis, preventing constant folding from silently hiding the error.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.9.1.459 (included in 26.9 and later)

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

clickhouse-gh Bot commented Feb 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [beccda2]

Summary: ✅


AI Review

Summary

This PR adds analysis-time validation for IN tuple/subquery arity mismatches and extends that logic across the rewrite_in_to_join path. The remaining gap is that the rewrite still reaches some left-hand shapes that plain IN rejects before set construction, so query behavior can still depend on rewrite_in_to_join.

Findings

⚠️ Majors

  • [src/Analyzer/Resolve/resolveFunction.cpp:1838] The rewrite_in_to_join skip logic is still keyed only to the one-column RHS case, so it misses left operands that regular IN rejects before set construction. A multi-column RHS with hasDynamicStructure() on the left (for example Tuple(Dynamic, UInt8) IN (SELECT number, 1 FROM numbers(1))) now bypasses FunctionIn::getReturnTypeImpl entirely even though plain IN throws ILLEGAL_TYPE_OF_ARGUMENT, because validateInColumnsCountMatch returns early and this branch still rewrites to EXISTS. The same branch also rewrites unresolved lambda LHS values, so with rewrite_in_to_join = 1 but allow_experimental_correlated_subqueries = 0, (x -> x) IN (SELECT 1) now hits SUPPORT_IS_DISABLED instead of the regular ILLEGAL_TYPE_OF_ARGUMENT already covered by 03380_in_tuple_subquery_column_count. 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 stateless regressions for both cases.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Prevent the rewrite_in_to_join path from rewriting left operands that plain IN would reject before set construction.
    • Add focused stateless regressions for the multi-column dynamic-structure case and the lambda-left case under rewrite_in_to_join.

LLVM Coverage Report

Measured on commit beccda2.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 92.00% 92.10% +0.10%
Branches 80.70% 80.80% +0.10%

Changed lines: Changed C/C++ lines covered: 88/98 (89.80%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Feb 21, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as draft February 21, 2026 04:26
alexey-milovidov and others added 13 commits February 21, 2026 13:21
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]>
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]>
…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]>
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.
alexey-milovidov and others added 2 commits March 30, 2026 11:36
…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]>
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Mar 30, 2026
alexey-milovidov and others added 2 commits March 31, 2026 10:20
…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]>
Comment thread contrib/aws Resolved
…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
`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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed the Fast test failure on 37e0e41393c9: that commit made validateInColumnsCountMatch skip left-hand types with a dynamic structure, so the Variant case in 04871_in_tuple_single_key_rewrite_in_to_join 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. Updated the expectation (and its comment) accordingly in 0d8626d64d5e, and verified locally with a RelWithDebInfo build that the error is identical under rewrite_in_to_join 0 and 1, which is exactly what the test asserts. Also merged master (the branch was red and behind). The Finish Workflow / new_tests_check.py failure was a consequence — the per-arch Bugfix validation jobs were dropped after Fast test failed — and should clear on the new run.

…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update on b82816b98bf9 → merged master and pushed f42b8f28c1c8.

What cleared: the 6 stateless reds from the previous head are gone, and CH Inc sync is now pass (7 known failure(s) ignored). AI Review on b82816b98bf9 is ✅ Approve, 0 unresolved review threads, cloud perf verdict no_change.

Remaining reds on b82816b98bf9, both unrelated AST-fuzzer finds:

  1. AST fuzzer (amd_debug, targeted, old_compatibility) — Logical error: 'Not-ready Set is passed as the second argument for function 'in'' (STID 0250-58e8), thrown from src/Functions/in.cpp:128 for

    SELECT DISTINCT NULL FROM (SELECT toLowCardinality(1), -2147483648 AS c1 WHERE CAST((1023, 256), 'Nullable(Tuple(UInt8, UInt8))') IN (SELECT 65535 WINDOW w_fuzz_4247 AS ()) INTERSECT SELECT toLowCardinality(1), toInt128(-2147483648) WHERE CAST((1023, 256), 'Nullable(Tuple(UInt8, UInt8))') GLOBAL NOT IN (SELECT 65535)) AS t WHERE 1048575 = (SELECT t.c1)

    This is a set-preparation failure (the FutureSet is never built for the INTERSECT branch), not an arity/type question, so it is orthogonal to this PR's analyzer validation. The same stack signature has been hit on unrelated pull requests (Perf(Column): Coalesce contiguous runs in ColumnFixedString filtering #115051 on 2026-08-18, Add ARM SVE infrastructure and SVE-optimized paths for unary arithmetic and findExtreme #97473 on 2026-08-17, Fix LOGICAL_ERROR on runtime filter lookup before build finished #107108 on 2026-08-12). Known family: Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) #107619, Not-ready Set for globalIn on the correlated-subquery-to-join rewrite path (correlated_subqueries_use_in_memory_buffer = false) #116343, Using external data inside additional_table_filters fails with "Not-ready Set is passed as the second argument for function 'in' ..." #72739.

  2. AST fuzzer (amd_debug) — Logical error: 'Can't determine table for parallel replicas' (STID 3634-3276) for a RIGHT JOIN whose right side is a clusterAllReplicas(...) view. Tracked by Logical error 'Can't determine table for parallel replicas' for RIGHT JOIN whose right side has no eligible table #113292 (comp-parallel-replicas, culprit-pr-not-found). Also seen on unrelated pull requests (Remove the sharded aggregator in favor of the adaptive aggregator #116532 today, Fix logical error for RIGHT JOIN with parallel replicas #113515 on 2026-08-18, Add clickhouse-proxy application mode #110105 on 2026-08-16). No IN/set code involved.

Neither has a fix on master yet, so the master merge will not clear them deterministically — but both are random-query fuzzer finds, so the fresh run on f42b8f28c1c8 is unlikely to reproduce the same queries.

@groeneai, could you investigate failure 1 (Not-ready Set, STID 0250-58e8, https://github.com/ClickHouse/ClickHouse/actions/runs/32684832888/job/97312960390) and provide a fix in a separate pull request? If it is already covered by one of the open Not-ready Set fixes (#102192, #112968, #113963, #115083, #110463), please link it here.

About the master merge: git merge-base --all origin/master HEAD returned two bases (74477eec80bb from 2026-08-21 and 3087a9264673 from 2026-05-29), so the ort virtual base produced 302 conflicts even though this branch touches 18 files. Resolution was purely mechanical: every conflicted file outside this branch's file set was taken from master verbatim, and the three overlapping test files (03393_non_constant_second_argument_for_in.{sql,reference}, 04635_in_tuple_subquery_rewrite_in_to_join.reference) were re-merged against the real newest base with git merge-file, which merged cleanly. Verified invariant: git diff --cached origin/master --numstat is byte-identical to the pre-merge git diff 74477eec80bb..HEAD --numstat (18 files, +569/-19), and no submodule gitlinks moved.

Verified locally on a RelWithDebInfo build of the merged tree (master added ~625 lines to src/Analyzer/Resolve/resolveFunction.cpp since the merge base, so this was not skippable): build exit 0, and 03380_in_tuple_subquery_column_count, 04871_in_tuple_single_key_rewrite_in_to_join, 04635_in_tuple_subquery_rewrite_in_to_join, 03393_non_constant_second_argument_for_in, 02386_analyzer_in_function_nested_subqueries, 02431_single_value_or_null_empty, 01650_expressions_merge_bug, 01681_bloom_filter_nullable_column, 02513_analyzer_duplicate_alias_crash_fix, 04545_correlated_subquery_in_set_speculative_build, 03714_tuple_inside_nullable_for_in_function_non_literal and 03989_set_low_cardinality_in_tuple all match their references.

@groeneai

Copy link
Copy Markdown
Collaborator

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

arm build id the fuzzed query
master ecc1b570c4216bf5 abort, Not-ready Set ... for function 'in', src/Functions/in.cpp:128
master + #115868 source diff 4006b757d2da8f79 no abort, ends in the query's own Code: 43 Illegal type Tuple(UInt8, UInt8) of argument of function toUInt16

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. fuzzer.log carries two Changed settings: dumps and they disagree: the server BaseDaemon one, which is the aborting query's own context, has allow_experimental_correlated_subqueries = true, while the client one printed after Lost connection to the server has it at 0. The trigger is allow_experimental_correlated_subqueries = 1 plus either correlated_subqueries_default_join_kind = 'left' or correlated_subqueries_use_in_memory_buffer = 0. INTERSECT, the WINDOW clause, the Nullable(Tuple(...)) cast, GLOBAL and DISTINCT are all decoration:

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: materializeQueryPlanReferences clones a subplan holding a DelayedCreatingSetsStep, the step clone is shallow, so both copies share the one-shot FutureSetFromSubquery::source and the copy in() reads stays unbuilt. Join kind left reaches this with the buffer setting on as well, because the buffer is only taken for RIGHT (QueryPlanOptimizationSettings.cpp:255-257).

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 _path / _file; #110463 needs a Distributed table plus the sharding key IN rewrite; #115083 only throws when its new observed_cancel is set and there is no cancellation in this job (0 hits in fatal.log and fuzzer.log); #102192 is titled "Not a fix". #115868 also fixes the reproducer in #116343.

@alexey-milovidov alexey-milovidov removed the submodule changed At least one submodule changed in this PR. label Aug 29, 2026
…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`).
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update on f42b8f28c1c8 → pushed beccda27e48f, addressing both Majors of the ⚠️ Request changes AI review verdict. CI on the previous head was fully green (160 pass / 19 skipping, CH Inc sync pass), so the only outstanding work was the review itself.

  1. hasDynamicStructure precedence (resolveFunction.cpp:962) — validateInColumnsCountMatch now returns early for every left type with a dynamic structure, before any arity logic, so FunctionIn::getReturnTypeImpl's ILLEGAL_TYPE_OF_ARGUMENT keeps its precedence for nested carriers such as Tuple(Dynamic, UInt8). That error is raised at analysis time too, so constant folding cannot hide it, which is why an early return is safe here. The scalar-left special case lost its now-redundant hasDynamicStructure() exemption.

  2. Correlated-subquery gate (resolveFunction.cpp:1829) — the allow_experimental_correlated_subqueries check moved into the branch that actually performs the rewrite, i.e. after left_value_compared_as_single_key is computed. Enabling rewrite_in_to_join alone no longer changes query acceptance for shapes that intentionally stay on the regular one-key IN path. An arity mismatch under rewrite_in_to_join = 1 with the correlated setting disabled now reports NUMBER_OF_COLUMNS_DOESNT_MATCH, the same error as with rewrite_in_to_join = 0, instead of SUPPORT_IS_DISABLED — which is exactly the setting-independence this pull request is about. No test relied on the old precedence.

Both requested regressions were added: 03380_in_tuple_subquery_column_count covers Tuple(Dynamic, UInt8) against a one-column and a two-column right side plus Array(Dynamic), and 04871_in_tuple_single_key_rewrite_in_to_join covers concat('0', toString(number + 1)) IN (SELECT toUInt8(1)) and a wrapped-tuple one-key case under rewrite_in_to_join = 1, allow_experimental_correlated_subqueries = 0, and asserts that a genuinely rewritten shape still requires the setting.

Verified locally on a RelWithDebInfo build of this head (build exit 0, 0 errors): both AI reproducers behave as required, and 03380, 04871, 04635, 03393, 03583, 03713, 04202, 04335, 04512, 04652, 04820, 02386, 02431, 02513, 03714 (rendered from its .j2), 03989 and 04545 all match their references. No master merge this run: the branch is 4 days behind, green and MERGEABLE, so none of the merge triggers fire.

|| !left_result_type->equals(*rhs_query_node->getProjectionColumns().front().type));
}

if (in_second_argument->as<QueryNode>() && !left_value_compared_as_single_key)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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::getReturnTypeImpl rejects any left type whose hasDynamicStructure() is true (src/Functions/in.cpp:67), but for CAST((number, 1), 'Tuple(Dynamic, UInt8)') IN (SELECT number, 1 FROM numbers(1)) the RHS has two projection columns, so left_value_compared_as_single_key stays false and this branch rewrites to EXISTS. That bypasses FunctionIn entirely even though tuple/dynamic comparison is supported by equals, so the observable behavior now depends on rewrite_in_to_join.
  • The new 03380_in_tuple_subquery_column_count test already documents that (x -> x) IN (SELECT 1) should stay ILLEGAL_TYPE_OF_ARGUMENT, but here left_key_type is null, so with rewrite_in_to_join = 1 and allow_experimental_correlated_subqueries = 0 we hit the SUPPORT_IS_DISABLED branch below instead of the regular IN validation.

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.

@qoega qoega self-assigned this Aug 31, 2026
@qoega
qoega added this pull request to the merge queue Aug 31, 2026
Merged via the queue into master with commit 25dfbdb Aug 31, 2026
174 checks passed
@qoega
qoega deleted the fix-in-tuple-subquery-column-count-mismatch branch August 31, 2026 19:22
@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

Verified the fix on the head build — all mismatch shapes I tried (direct/folded, WHERE/HAVING/PREWHERE, NOT IN, GLOBAL IN, CTE/view/Merge-engine/table right sides, nested tuples, single-Tuple-column arity mismatch) now throw NUMBER_OF_COLUMNS_DOESNT_MATCH at analysis, and no valid single-key carve-out regressed.

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 analysis

Root cause: validateInColumnsCountMatch only runs the castability probe when the counts mismatch or when the right key is a Tuple column / the left side is a scalar; with left_columns_count == right_columns_count == 1 and a non-Tuple right key, a Tuple left value is never checked. The same-count element-type shapes ([1,1] IN (SELECT 1), (1,1) IN (SELECT (1,2),(3,4))) also remain foldable-silent, though I understand element-type compatibility is deliberately left as a runtime question.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 31, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov @qoega — this PR looks backward incompatible but is categorized as Bug Fix (user-visible misbehavior in an official stable release).

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 SELECT NULL IN (SELECT 1, 2) returns \N with enable_analyzer=0 and =1, and SELECT (1,2) IN (SELECT NULL) returns 0 in both; both now throw. The PR itself deletes result lines from three existing .reference files (02386, 02431, 01650) and rewrites the expectations of five more tests, which is the signature of a semantics change rather than a contained fix. The changelog entry field also contains a Claude Code attribution line instead of an entry.

Suggested category: Backward Incompatible Change. Ignore if the change is intentionally non-breaking.

@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov @qoega — title/description suggestions:

Description (currently incomplete):

  • Why: The body describes only the arity check. It omits three other behavior changes in the same diff: the new analysis-time TYPE_MISMATCH for a scalar left operand against a single Tuple right column (resolveFunction.cpp:962-967), the rewrite_in_to_join restructuring that moves the allow_experimental_correlated_subqueries gate and skips the rewrite for single-key shapes (:1826-1849, with new tests 04635 and 04871), and the constant-1 column injected for zero-ordinary-column table functions (:2421-2426). It also does not state that previously-accepted queries now fail — three existing .reference files lose result lines. The changelog entry field holds a tool attribution line, not an entry.

  • Suggested addition:

    Behavior change: queries whose IN arity never matched but which previously returned 0/NULL — because constant folding, the empty-set fast path, or an all-NULL left operand removed the comparison — now throw. Verified on 26.8.1: SELECT NULL IN (SELECT 1, 2) returned \N under both enable_analyzer=0 and =1, SELECT (1,2) IN (SELECT NULL) returned 0, and SELECT 1 IN j for a two-column Join-engine table returned 0. Stored views containing such an IN will start failing on read after upgrade. Also worth spelling out in the body: the new TYPE_MISMATCH path for a scalar left operand versus a single Tuple right column, and the rewrite_in_to_join changes covered by 04635/04871.

Ignore if intentional.

@egor-click egor-click added the pr-backward-incompatible Pull request with backwards incompatible changes label Sep 7, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backward-incompatible Pull request with backwards incompatible changes 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.

Analyzer regression on query validation

8 participants