Skip to content

Reject a Distributed sharding key with IN over a subquery or a non-Set table - #124646

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-sharding-key-in-subquery-set
Oct 10, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-sharding-key-in-subquery-set

Conversation

@groeneai

@groeneai groeneai commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117004
Related: #121639
Related: #110463

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 sharding key of a Distributed table, a Remote table or the remote/cluster table functions that contains IN with a subquery or with a non-Set table is now rejected when the table is defined. The set of such an IN was never built, so every INSERT failed with a Not-ready Set logical error and optimize_skip_unused_shards could prune to the wrong shard and return wrong results. A table defined earlier with such a key still loads, but an INSERT that needs the key fails with BAD_ARGUMENTS and shard pruning does not use it. Pruning by a key with IN over a Set table, which can change after rows are placed, now needs allow_nondeterministic_optimize_skip_unused_shards, as for joinGet.

Description

CI: BuzzHouse (amd_tsan) on #117004, INSERT INTO FUNCTION remote(..., c0 GLOBAL NOT IN <Alias of a Remote table>). Its segfault is fixed by #121639; with it, the statement fails with Not-ready Set (LOGICAL_ERROR, DistributedSink::createSelector).

On 26.8.2.7 (also 26.3.42.3), with sharding key c0 IN vip (vip a MergeTree table holding 1) and the rows placed by that key, SELECT count() FROM d WHERE c0 = 1 SETTINGS optimize_skip_unused_shards = 1 returns 0 instead of 1, and INSERT INTO d fails with the same logical error.

Root cause: the key is compiled once in the StorageDistributed constructor, where such an IN registers a FutureSetFromSubquery that nothing builds.

The constructor now rejects such a key with BAD_ARGUMENTS. As in #117791 (arrayJoin), only a definition stated now is checked (is_fresh_definition), so stored tables still load. For them the INSERT selector throws the same error before executing the key, shard pruning skips it (force_optimize_skip_unused_shards throws), and a stored AS remote(...) table throws on first access.

IN (1, 2) and IN <Set table> are ready sets and still work, but a Set table can change after rows are placed, so such a key is now non-deterministic for shard pruning, like joinGet (on master, adding a value to the set made the query above return 0 instead of 1).

Alternative: a syntactic checkExpressionDoesntContainSubqueries (as for MergeTree keys) would also reject the IN <Set table> key.

Tests: 05339 and 05340, both fail on master.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1990-master (included in 26.10 and later)

groeneai and others added 2 commits October 8, 2026 13:38
…t table

The sharding key is compiled once in the StorageDistributed constructor.
An IN over a subquery or over a non-Set table registers a
FutureSetFromSubquery there, and nothing ever builds it for table
metadata, so every consumer of the key sees an unready set: an INSERT
fails in DistributedSink::createSelector with "Not-ready Set is passed as
the second argument for function 'in'" (LOGICAL_ERROR), and the
optimize_skip_unused_shards path folds the key to a wrong constant and
prunes to the wrong shard (26.8 and 26.3 return 0 instead of 1 for a
point query on such a table).

Reject such a key with BAD_ARGUMENTS right after it is built. A tuple or
Set-table IN is a ready set and keeps working. As for arrayJoin
(be38893), only a definition stated now is checked
(is_fresh_definition): stored tables still load and ALTER does not
revalidate. The check runs after the build so a missing table in the key
still reports UNKNOWN_TABLE (02111_global_context_temporary_tables).

Found by BuzzHouse (amd_tsan) on ClickHouse#117004, where the INSERT into remote()
with c0 GLOBAL NOT IN <Alias of a Remote table> segfaulted before ClickHouse#121639
and fails with this LOGICAL_ERROR after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove the comment above the sharding key subquery-set check; the exception message states the same thing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 8, 2026
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Head 8f1de62a6b57. Own cold review plus the Gate B second-model review: 0 blockers, 0 majors.

Finding Verdict
💡 Error code: the arrayJoin check in the same constructor uses ILLEGAL_COLUMN Kept BAD_ARGUMENTS, the code checkExpressionDoesntContainSubqueries uses for MergeTree keys, skip indexes, TTL and PARTITION BY
💡 Two test files Same pair as #117791. 05340 is the only test that fails when the is_fresh_definition gate is dropped

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local -n --queries-file repro.sql with INSERT INTO FUNCTION remote('127.0.0.1,localhost', currentDatabase(), dst, c0 IN (SELECT c0 FROM src)) SELECT number % 2 FROM numbers(4): official master build with #121639 gives Code: 49 Not-ready Set every run; a debug build aborts with DistributedSink::createSelector in the stack.
b Root cause explained? The sharding key is compiled once in the StorageDistributed constructor. ActionsMatcher::makeSet registers an IN over a subquery or a non-Set table as a FutureSetFromSubquery, and no query pipeline ever builds it for table metadata, so FunctionIn sees an unready set whenever the key is executed (insert selector) or folded (shard pruning).
c Fix matches root cause? Yes. The key is rejected where it is defined, right after it is built, so the unready state can no longer be created by a user statement. Only the set kind that is never built is rejected; tuple and Set-table sets keep working.
d Test intent preserved / new tests added? Two new tests: 05339 (rejection matrix incl. the CI shape GLOBAL NOT IN over an Alias of a Remote table, a lambda, remote() INSERT and SELECT, plus tuple / Set controls) and 05340 (stored definition loads, short ATTACH, unrelated ALTER, restating it is rejected).
e Both directions demonstrated? Yes. Both tests FAIL on the base build (the server aborts on the 05339 INSERT row) and PASS with the fix; 50/50 randomized runs of each pass. Mutation arms: widening the check to any set reddens 05339; dropping the is_fresh_definition gate reddens 05340.
f Fix is general across code paths? Yes. Every StorageDistributed with a sharding key goes through this constructor: the Distributed, Remote and RemoteSecure engines and the remote/cluster table functions. The insert selector and both shard-pruning paths read the same expression, so all of them are covered at the source.
g Fix generalizes across inputs (params/datatypes/wrappers)? The check reads the set column node, not the function name. Measured on the fixed build: IN, NOT IN, GLOBAL IN, GLOBAL NOT IN, nullIn, notNullIn over a subquery or a MergeTree table, and an IN inside a lambda, are rejected; IN [1, 2], IN (1, 2) and NOT IN <Set table> are accepted. The check does not depend on the key type. A scalar subquery creates no set and behaves exactly as on master.
h Backward compatible? (maintainer-approved exception only) Only a definition stated now is checked (is_fresh_definition, as in #117791). Stored tables still load and ALTER does not revalidate. Every rejected key already failed on INSERT, and on 26.8 it gave wrong results under optimize_skip_unused_shards. No setting changes.
i Invariants and contracts preserved? The expression is still built first, so a missing table in the key still gives UNKNOWN_TABLE (02111_global_context_temporary_tables unchanged). The check only reads the DAG and throws before the storage is published; no locks or shared state are involved.

Session id: cron:clickhouse-impl-slot-41:20261008-130122

@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1a95d8a]

Summary: ✅


AI Review

Summary

This PR closes the original FutureSetFromSubquery hole at the right layers: newly defined bad sharding keys are rejected in the constructor, stored legacy metadata now fails closed before INSERT selector execution and before shard pruning, and IN over a Set table is no longer treated as deterministic for shard pruning unless the user opts in with allow_nondeterministic_optimize_skip_unused_shards. I re-checked the current diff and the existing review threads against the current code and do not see a remaining correctness issue or a missing regression test in the changed surface.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 1a95d8a.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 42/42 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 8, 2026
Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Oct 8, 2026
…e by a Set table

A sharding key with `IN` over a subquery or a non-Set table is rejected only when
the definition is stated now (`is_fresh_definition`), so such a table created by an
older version still loads. Its set is still never built, so an `INSERT` that needs the
key failed with the `Not-ready Set` logical error and `optimize_skip_unused_shards`
folded the key to a wrong constant. Remember that the key holds such a set: the insert
selector throws the same `BAD_ARGUMENTS` before executing the key, shard pruning does
not use it (with `force_optimize_skip_unused_shards` the `BAD_ARGUMENTS` is thrown),
and an `INSERT` with `insert_shard_id` or into a one-shard cluster, which never
executes the key, keeps working.

`IN <Set table>` stays allowed, but the `Set` table can change after rows are placed
by it, so a key reading one is no longer treated as deterministic for shard pruning,
the same as a key reading a `Join` table through `joinGet`. Pruning by it now needs
`allow_nondeterministic_optimize_skip_unused_shards`. Measured on master: rows placed
while the set was empty, then `INSERT INTO set_t VALUES (1)`, and
`WHERE c0 = 1 SETTINGS optimize_skip_unused_shards = 1` returned 0 instead of 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

All good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
Merged via the queue into ClickHouse:master with commit 6786fe9 Oct 10, 2026
152 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
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-distributed Distributed table engine & query routing across shards (sharding/load balancing). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants