Skip to content

Do not rewrite the sharding-key IN set in the SELECT projection - #117252

Merged
alexey-milovidov merged 11 commits into
masterfrom
fix-skip-unused-shards-rewrite-in-projection
Sep 27, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
fix-skip-unused-shards-rewrite-in-projection

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #116908

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

Fix THERE_IS_NO_COLUMN for a Distributed
query that has an IN over the sharding key outside its WHERE - in the SELECT projection, in
GROUP BY, in ORDER BY or in LIMIT BY. The default-enabled
optimize_skip_unused_shards_rewrite_in rewrote that IN per shard, which changed the result
column's name, so the initiator could not bind the column the shard returned.

Description

The rewrite prunes the elements of an IN set over the sharding key to the ones routed to each
shard. That is sound as a filter, and even the value of such an expression stays correct - a row
that lives on a shard can only equal an element routed to that shard. What breaks is the column
identity: in(key, (1, 4)) becomes in(key, tuple(4)) on one shard and in(key, tuple(1)) on the
other, and the header a shard returns for a distributed intermediate stage is matched by name on the
initiator (ReadFromRemote).

That header is not limited to the final SELECT outputs - it also carries the aggregation keys and
the before_order_by results - so the rewrite is now confined to the filtering clauses: the visitor
descends into WHERE and PREWHERE only, plus the join tree so that a subquery in FROM keeps
being pruned by its own filters. Within the join tree only the table expressions are visited: the
ON section of a JOIN, the expressions of an ARRAY JOIN and the arguments of a table function
belong to a different source, which is not partitioned by the sharding key of this table even when
its column shares the name, so pruning b.key IN (1, 4) in ... JOIN b ON a.key = b.k AND b.key IN (1, 4)
would change the join result. An aliased IN is skipped entirely, since the aliased node is shared
with the other clauses that reference the alias.

Only the query-tree rewriter is changed: since 26.9 enable_analyzer = 0 is refused by the
settings constraints, so the AST rewriter of the old analyzer is unreachable and stays as it is.

The shard-pruning behaviour the existing 01756_/01930_optimize_skip_unused_shards_rewrite_in
tests pin is unchanged - none of their queries has an IN over the sharding key outside WHERE.

New test 05071_skip_unused_shards_rewrite_in_projection covers the projection, GROUP BY,
ORDER BY, LIMIT BY and the two aliased shapes, asserts that the filter-only shape still prunes,
that a subquery spelling the same IN in its projection does not disable the rewrite of the outer
WHERE, and that the IN in a JOIN ON keeps its set. Note that both shards of
test_cluster_two_shards read the same system.one, which does not respect the sharding key, so
the pruning legitimately changes the row count there.


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

Version info

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

`optimize_skip_unused_shards_rewrite_in` prunes the elements of an `IN` set over the sharding
key to the ones routed to each shard. Applied to an `IN` in the projection, the value of the
expression stays correct - a row on a shard can only equal an element routed to that shard -
but the result column's name changes with the set, so the initiator could not bind the column
the shard returned and the query threw `NOT_FOUND_COLUMN_IN_BLOCK` (or `THERE_IS_NO_COLUMN`
under the analyzer, with diverging `__set_*` hashes) instead of returning rows.

Both arms of the visitor now skip the projection and keep rewriting everywhere else.

Closes: #116908
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [17d9766]

Summary: ✅


AI Review

Summary

The PR confines optimize_skip_unused_shards_rewrite_in to query-tree filters and now rewrites only IN predicates whose left-hand column comes from the distributed table expression itself. I did not find unresolved correctness issues in the current head: the earlier remote-header mismatch and cross-source join/subquery rewrite problems are covered by the current code shape and by the added stateless regression cases.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 17d9766.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 32/37 (86.49%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

The same per-shard set-name mismatch survives in every other position that is shipped by name, with both analyzers, at the same settings (optimize_skip_unused_shards = 1, the rewrite setting default ON). Verified on a 26.9 development build without this patch, and the diff still visits these children by construction:

  • GROUP BY: SELECT count() FROM dist WHERE k IN (1,2) GROUP BY k IN (1,2) → Not found column in(k, (1, 2)) in block... (new analyzer: THERE_IS_NO_COLUMN on the __set_... column).
  • ORDER BY: SELECT k FROM dist WHERE k IN (1,2) ORDER BY k IN (1,2), k → same.
  • LIMIT BY: ... LIMIT 1 BY k IN (1,2) → same.
  • An alias defined in WHERE and projected: SELECT f, k FROM dist WHERE (k IN (1,2)) AS f → same (the IN node lives in the WHERE child, which is still visited).
  • An alias defined in the projection and reused in WHERE: SELECT k, (k IN (1,2)) AS f FROM dist WHERE f — in the new analyzer the resolved tree shares the aliased node between the projection and WHERE, so the visitor reaches and mutates it through the un-skipped WHERE child.

Also worth noting: the rewrite fires on every matching IN once any WHERE IN triggers pruning, even when no shard is actually skipped (WHERE k IN (0,1,2,3) over both shards still rewrites the other positions). A robust shape might be to skip every IN that can survive into the remote-stage header, or to rewrite only inside filter clauses.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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.

Compile time of recompiled translation units

8 translation units recompiled, 23 s compile time in total, 8 of them have a recent master baseline.

Job report

…g clauses

Skipping only the `SELECT` projection was not enough. The header a shard returns for a distributed
intermediate stage is not limited to the final `SELECT` outputs: it also carries the aggregation
keys and the `before_order_by` results, and `ReadFromRemote` matches the shard result to it by
column name. So `GROUP BY key IN (...)`, `ORDER BY key IN (...)` and `LIMIT 1 BY key IN (...)` could
still rename a required remote column per shard and fail with the same `NOT_FOUND_COLUMN_IN_BLOCK` /
`THERE_IS_NO_COLUMN` class of exception.

Both rewriters now descend only into `WHERE` and `PREWHERE` (and into the join tree, so a subquery
in `FROM` keeps being pruned by its own filters). An aliased `IN` is skipped entirely: the alias is
shared with the other clauses in the analyzer and expanded into a copy of the expression in the old
analyzer, where rewriting only the filter left `MULTIPLE_EXPRESSIONS_FOR_ALIAS` behind.

The test now covers every remote-header carrier under both analyzers.
Confining the rewrite to `WHERE` / `PREWHERE` is still not enough on the old-analyzer path, because
the header the initiator expects can contain a column that only the filter computes. Verified
locally: `SELECT dummy FROM dist WHERE dummy IN (0, 2) ORDER BY dummy LIMIT 1 BY dummy IN (0, 2)`
kept throwing `Not found column in(dummy, (0, 2)) in block`, since `before_order_by` on the initiator
carries the column that `WHERE` produced while the shard now names it `in(dummy, tuple(0))`.

The AST rewriter therefore first collects the names of the `IN` expressions that are reachable
without going through a filter, and skips those. The analyzer resolves the remote columns by node
rather than by name and handles this shape already, so its rewrite stays as wide as it can be.

All the shapes in the test - projection, `GROUP BY`, `ORDER BY`, `LIMIT BY` and the two aliased ones
- were checked against a local two-shard cluster under both analyzers, and the filter-only shape
still prunes.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @zlareb1 thank you - every shape you listed reproduced, and they are all covered now.

Both rewriters descend only into WHERE / PREWHERE (plus the join tree, so a subquery in FROM keeps being pruned by its own filters), which closes GROUP BY, ORDER BY and the projection.

Your two alias cases and LIMIT BY needed more than that on the old-analyzer path:

  • An aliased IN in the filter is expanded into a copy of the expression wherever the alias is referenced, so rewriting only the filter left MULTIPLE_EXPRESSIONS_FOR_ALIAS behind (that was the stateless red on the previous commit). An aliased IN is now skipped outright.
  • WHERE can be the only place that computes a column a later stage consumes by name: SELECT dummy FROM dist WHERE dummy IN (0, 2) ORDER BY dummy LIMIT 1 BY dummy IN (0, 2) still threw Not found column in(dummy, (0, 2)) in block with a filter-only rewrite, because before_order_by on the initiator carries the column WHERE produced while the shard now names it in(dummy, tuple(0)). The AST rewriter therefore first collects the names of the IN expressions reachable without going through a filter and skips those.

The analyzer binds the remote columns by node rather than by name and handles that last shape already, so its rewrite stays as wide as it can be. That is why the two blocks of the test's reference differ in row count: with the same IN in WHERE and elsewhere, the old analyzer no longer prunes and both shards keep their row, while the analyzer still prunes. Neither throws, which is the point.

On your last remark - the rewrite firing even when no shard is actually skipped - that is unchanged here and is a separate (pre-existing) matter: the rewrite is entered whenever optimize_skip_unused_shards produced an optimized cluster with more than one shard, and pruning the set of a surviving shard is still value-preserving. Happy to look at narrowing it further in a follow-up.

The test now covers the projection, GROUP BY, ORDER BY, LIMIT BY and both aliased shapes under enable_analyzer = 0 and = 1, verified against a local two-shard cluster, and still asserts that the filter-only shape prunes.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: AST fuzzer (amd_debug, targeted) and provide a fix in a separate PR. If the fix is already in progress, link it here.

SELECT dummy NOT IN (NULL) FROM merge(REGEXP('^'), '.+') GROUP BY ALL WINDOW w_fuzz_3 AS (RANGE BETWEEN CURRENT ROW AND CURRENT ROW) hits Logical error: No set is registered for key __set_...(UInt8) in PlannerActionsVisitorImpl::makeSetForInFunction, reached from StorageDistributed::isShardingKeySuitsQueryTreeNodeExpression (src/Storages/StorageDistributed.cpp:627), which rebuilds an actions DAG for an expression outside the planner context that registered the set.

It is unrelated to this pull request: the query uses neither optimize_skip_unused_shards nor the IN rewrite this pull request touches, and the same signature has been recurring in the fuzzer across unrelated pull requests for weeks (#117140, #114883, #116363, #110626, #111873, #107700, #111920 ...). The closest tracked instance, #113712, was for ReadFromMerge::getModifiedQueryInfo and is closed; this StorageDistributed path has no open issue that I could find.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. No fix is in progress for this path, so I am investigating it and will follow up here with the separate pull request (or with my findings, if it turns out not to be actionable).

On the "already in progress" question: the open pull requests on this same message all cover different paths. #107603 and #112219 are analyzer-side (a table expression shared between the join tree and an IN argument) and touch only src/Analyzer/. #111126 does touch isShardingKeySuitsQueryTreeNodeExpression, but for an unrelated defect: the probe builds its DAG with unqualified column names, which collide on a global distributed join. None of them affects set registration in the sharding-key probe, and I found no other open pull request or issue covering it either.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Fixed in #117817: the check now registers the expression's sets in the planner context it is about to resolve them from, which is what the other consumers of that visitor already do. One line, plus a stateless test covering the three clauses the check is evaluated for (GROUP BY, DISTINCT, LIMIT BY) and the four IN second-argument kinds.

On the recurring signature, the 14 rows CIDB has for it in the last 35 days are three separate things. 8 are the ReadFromMerge ALIAS route that #113757 fixed, all between 2026-08-03 and 08-10. 4 are this sharding-key check, on 3 pull requests, the first on 2026-08-31. The other 2 are not occurrences at all: the log parser lifted the phrase out of a test file's own text. None of the 14 is on master, as expected when only per-pull-request jobs run the fuzzer and the stress test.

@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 4, 2026
alexey-milovidov and others added 3 commits September 16, 2026 08:48
…pressions of the join tree

Since 26.9 `enable_analyzer = 0` is refused by the settings constraints, so the AST arm of
`optimizeShardingKeyRewriteIn` is unreachable. Drop the changes to it (the per-`SELECT`
exclusion set of the `IN` names used outside the filters and the alias skip) and keep the
old-analyzer rewriter as it is on master; the test no longer has an `enable_analyzer = 0` block
either, which also removes the failure of `01930_optimize_skip_unused_shards_rewrite_in` in
the old-analyzer CI job.

In the query-tree arm, address the review: within the join tree only the table expressions
are visited now. The `ON` section of a `JOIN`, the expressions of an `ARRAY JOIN` and the
arguments of a table function belong to a different source, which is not partitioned by the
sharding key of this table even when its column shares the name, so pruning
`b.dummy IN (0, 2)` in `... JOIN b ON a.dummy = b.key AND b.dummy IN (0, 2)` changed the join
result rather than the coverage of the optimization.

The test covers both review shapes: a subquery that spells the same `IN` in its projection
does not disable the rewrite in the outer `WHERE`, and the `IN` in a `JOIN ON` keeps its set.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117252&sha=c9049df6653e294129d4285dbfb6c3c7d3093e35&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%203%2F3%29
PR: #117252

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov and others added 3 commits September 23, 2026 02:32
… table

`optimize_skip_unused_shards_rewrite_in` matched the sharding column by name only,
so in a joined query a `WHERE` filter over another source (the other side of a
`JOIN`, a subquery over another table) whose column shares the name of the
sharding column was pruned per shard as well, dropping rows from the join result.
Match the column source against the distributed table expression, which is
recognized in the query for the shard by its (unique) alias.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Sep 27, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 27, 2026
Merged via the queue into master with commit 323e263 Sep 27, 2026
173 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). 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.

optimize_skip_unused_shards_rewrite_in rewrites IN in the SELECT projection, throwing NOT_FOUND_COLUMN_IN_BLOCK instead of returning rows

4 participants