Skip to content

Interpret an array subquery on the right of IN as a set of its elements - #110169

Merged
alexey-milovidov merged 9 commits into
masterfrom
in-subquery-array-as-set
Jul 15, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
in-subquery-array-as-set

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

The right side of IN treats an array as the set of its elements, so x IN [1, 2, 3], x IN array_returning_function() and a bare array column x IN arr are all handled that way. A subquery returning an array, however, was not: x IN (SELECT groupArray(x) ...) treated the whole array as a single opaque set value, coercing the left argument into the array type and producing a confusing error instead of a result:

SELECT count() FROM numbers(10) WHERE number IN (SELECT groupArray(number) FROM numbers(10));
-- Code: 53. TYPE_MISMATCH: CAST AS Array can only be performed between same-dimensional ...

SELECT count() FROM numbers(10) WHERE toString(number) IN (SELECT groupArray(toString(number)) FROM numbers(10));
-- Code: 130. CANNOT_READ_ARRAY_FROM_TEXT: Array does not start with '[' character

This extends the same dimension-based rule that was recently added for a bare array column (#109416) to a subquery: when the subquery's single result column is an Array exactly one dimension deeper than the left argument, the subquery is wrapped as SELECT arrayJoin(<column>) FROM (<subquery>) so the array elements become the set elements. Both queries above now return 10. Equal-depth arrays (e.g. Array(T) on both sides) stay a one-element set, i.e. equality, matching the bare-column behaviour.

Closes: #37066
Related: #109416

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A subquery on the right side of IN whose single column is an array one dimension deeper than the left argument is now interpreted as the set of the array's elements (like an array literal or an array-returning function), instead of failing with a confusing type-mismatch error. For example, x IN (SELECT groupArray(x) FROM ...) now works.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.972 (included in 26.7 and later)

`x IN (SELECT groupArray(x) ...)` previously treated the whole array
returned by the subquery as a single opaque set value: the left argument
was coerced into the array type, producing a confusing
`CANNOT_READ_ARRAY_FROM_TEXT` ("Array does not start with '[' character")
or `TYPE_MISMATCH` error.

The right side of `IN` treats an array as the set of its elements, so
`x IN [1, 2, 3]`, `x IN array_returning_function()` and a bare array
column `x IN arr` are already handled this way. Extend the same
dimension-based rule to a subquery: when the subquery's single result
column is an `Array` exactly one dimension deeper than the left argument,
wrap it in `SELECT arrayJoin(<column>) FROM (<subquery>)` so the array
elements become the set elements. Equal-depth arrays stay a one-element
set (equality), matching the bare-column behaviour.

Closes: #37066

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cc0d703]

Summary: ✅


AI Review

Summary

This PR extends analyzer-side IN handling so a right-hand subquery, direct table, or table function returning an Array one dimension deeper than the left operand is flattened with arrayJoin, making it behave like other array-backed IN forms instead of coercing the left side to an Array and throwing confusing exceptions. I traced the modified resolveFunction.cpp paths, re-checked the prior review threads against the current head, and the current implementation plus targeted stateless regressions are consistent with the stated contract.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 12, 2026
alexey-milovidov and others added 2 commits July 12, 2026 18:41
`NameAndTypePair` takes its arguments by const reference, so `std::move`
of `element_name` and `element_type` did not move anything and failed the
`arm_tidy` build:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110169&sha=2a1abc2e8d60090dd27f8ed7a9cca15853e034c9&name_0=PR&name_1=Build%20(arm_tidy)

Co-Authored-By: Claude Fable 5 <[email protected]>
An array subquery on the right of `IN` is now the set of its elements, so
`(1, 2) IN (SELECT [0, 0] UNION ALL SELECT [1, 1])` tests the tuple against
a set of `UInt8` elements and fails with `ILLEGAL_TYPE_OF_ARGUMENT` - the
same exception as the pre-existing `(1, 2) IN (SELECT 0 UNION ALL SELECT 1)` -
instead of `TYPE_MISMATCH` from coercing the tuple into the array type.
Failed in Fast test:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110169&sha=2a1abc2e8d60090dd27f8ed7a9cca15853e034c9&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Fable 5 <[email protected]>
… path

An array subquery on the right of `IN` is the set of its elements, flattened
with `arrayJoin`. So far this was only applied in the regular `IN` handling.
When `rewrite_in_to_join = 1` (which requires
`allow_experimental_correlated_subqueries = 1`), the earlier branch rewrites a
non-constant `x IN (subquery)` into a correlated `EXISTS` before the regular
`IN` handling runs, so the right side was still compared as `x = <array>`
instead of being flattened into set elements, keeping the reported bug alive
and making the new behavior depend on an unrelated setting.

Factor the flattening into a shared helper `flattenArraySubqueryOnRightOfIn`
and call it in both the regular `IN` path and before building the `EXISTS`
rewrite. Add regression queries under `rewrite_in_to_join = 1` to
`04512_in_function_array_subquery_right_argument`.

Addresses the AI review finding on
#110169
Addresses the review on `resolveFunction.cpp:784`: verify how an array
subquery on the right of `IN` with `Nullable` elements interacts with
`transform_null_in` and `rewrite_in_to_join`.

On the regular `IN` path the flattened array subquery honors
`transform_null_in`: with `transform_null_in = 1` a `NULL` element is a
set member (a `NULL` left argument matches), and with the default
`transform_null_in = 0` a comparison against `NULL` is unknown (`NULL`).

Under `rewrite_in_to_join` the non-constant `x IN (subquery)` is lowered
to a correlated `EXISTS` that compares with `equals`, which does not honor
`transform_null_in` for a `NULL` set element. This is a pre-existing
property of the rewrite that applies to a scalar `QueryNode` subquery too,
so the flattened array subquery behaves exactly like the equivalent
`SELECT arrayJoin(...)` scalar subquery and adds no new inconsistency: the
test asserts the array-subquery and the `arrayJoin`-subquery forms produce
the identical result under the rewrite.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits July 13, 2026 06:49
… of IN

Addresses the review finding that the array-as-set flattening only ran on
the subquery path, so a direct table reference on the right of `IN` whose
single column is an `Array` kept the old opaque-array behavior:
`2 IN some_array_table` failed with a type mismatch while the equivalent
`2 IN (SELECT arr FROM some_array_table)` now works.

The `TableNode` branch of the `IN` handling in `QueryAnalyzer::resolveFunction`
now calls a new helper `flattenArrayTableExpressionOnRightOfIn`, which, when
the table has a single `Array` column exactly one dimension deeper than the
left argument, wraps it as a `SELECT column FROM table` subquery and reuses
`flattenArraySubqueryOnRightOfIn` (so the elements become the set elements).
Tables with a non-`Array` column, a wrong depth, or more than one column are
left untouched, so the ordinary `x IN table` path and any `StorageSet` fast
path are unchanged.

The `TableFunctionNode` branch, which already wraps the table function into a
one-column subquery, now runs the same flattening on the wrapped subquery for
consistency.

Added regressions to `04512_in_function_array_subquery_right_argument` for the
direct-table spelling: element membership, `NOT IN`, multiple rows, `Array`
left argument with an `Array(Array(...))` column, equal-depth equality, nullable
elements with `transform_null_in`, a non-`Array` table regression guard, and the
`rewrite_in_to_join` path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110169&sha=383b1435878feb788eea2d4e49dd3e32c86b8c7e&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is an UndefinedBehaviorSanitizer report (signed overflow in std::chrono::duration_cast, __chrono/duration.h:93) inside condition_variable::wait_for called from ConcurrentBoundedQueue::popImpl via LazyOutputFormat::getChunk and PullingAsyncPipelineExecutor::pull in TCPHandler::processOrdinaryQuery — most likely a huge randomized timeout in milliseconds overflowing when converted to nanoseconds. Unrelated to this PR (analyzer-only change); I found no existing issue tracking it.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix is already in progress: #106961 "Fix signed integer overflow in condition_variable::wait_for with huge timeouts".

The report here (STID 2881-3dbd, __chrono/duration.h:93 signed overflow 18446744073709551 * 1000000) is the exact call site #106961 already clamps: ConcurrentBoundedQueue::popImpl reached via the lazy output format. libc++ evaluates wait_for(ms) as now() + ms in nanoseconds, so a huge randomized ms timeout (e.g. interactive_delay) overflows Int64 on the ms->ns multiply. #106961 wraps every user-controlled ms timeout with a shared saturatedMilliseconds() clamp ([0, one year]) before it reaches the chrono deadline, including this popImpl site. Confirmed unrelated to this PR.

Deterministic repro on master:
clickhouse-local --query "SELECT 1 SETTINGS interactive_delay = 100000000000000000"

#106961 is under review.

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 61/65 (93.85%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 15, 2026
@alexey-milovidov
alexey-milovidov merged commit a3a6d9c into master Jul 15, 2026
176 of 177 checks passed
@alexey-milovidov
alexey-milovidov deleted the in-subquery-array-as-set branch July 15, 2026 01:21
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 15, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @alexey-milovidov — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… path

An array subquery on the right of `IN` is the set of its elements, flattened
with `arrayJoin`. So far this was only applied in the regular `IN` handling.
When `rewrite_in_to_join = 1` (which requires
`allow_experimental_correlated_subqueries = 1`), the earlier branch rewrites a
non-constant `x IN (subquery)` into a correlated `EXISTS` before the regular
`IN` handling runs, so the right side was still compared as `x = <array>`
instead of being flattened into set elements, keeping the reported bug alive
and making the new behavior depend on an unrelated setting.

Factor the flattening into a shared helper `flattenArraySubqueryOnRightOfIn`
and call it in both the regular `IN` path and before building the `EXISTS`
rewrite. Add regression queries under `rewrite_in_to_join = 1` to
`04512_in_function_array_subquery_right_argument`.

Addresses the AI review finding on
ClickHouse#110169
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…y-as-set

Interpret an array subquery on the right of IN as a set of its elements
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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.

odd excpetion messages when scalar in (select [array])

4 participants