Skip to content

Fix optimize_skip_unused_shards on global distributed joins with shared column names - #111126

Open
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111089-skip-unused-shards-distributed-join-column-binding
Open

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111089-skip-unused-shards-distributed-join-column-binding

Conversation

@groeneai

@groeneai groeneai commented Jul 20, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111089

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

Fixed optimize_skip_unused_shards = 1 misbehaving on global distributed joins (distributed_product_mode = 'global'): a valid query such as SELECT DISTINCT l.c, r.c + 2 ... where both sides have a column of the same name threw ILLEGAL_TYPE_OF_ARGUMENT, and grouping by a right-side column whose name matched the left table's sharding key could return unmerged per-shard partial results.

Description

On 26.3.42.3 and 26.8.18.2, SELECT DISTINCT l.c, r.c + 2 FROM nb_dl AS l INNER JOIN nb_dr AS r ON l.a = r.a SETTINGS distributed_product_mode = 'global', optimize_skip_unused_shards = 1 throws ILLEGAL_TYPE_OF_ARGUMENT when both Distributed tables have a column c of different types; with optimize_skip_unused_shards = 0 it runs.

Root cause: getOptimizedQueryProcessingStageAnalyzer probes the DISTINCT / GROUP BY / LIMIT BY key with isShardingKeySuitsQueryTreeNodeExpression, which builds an ActionsDAG over unqualified column names. Same-named columns from different join sides collapse onto one node (the exception above), and a right-side column named like the left table's sharding key (GROUP BY r.k) was matched to the sharding key, so shards returned unmerged partials.

The fix adds a precheck before that DAG is built. The shard-local stage is kept only when no unqualified name the DAG will see (including constant-backed ALIAS columns) comes from more than one source, every sharding-key column comes from this table, and no outer join can null-extend this table. Otherwise the initiator merges, as with optimize_skip_unused_shards = 0. Joins that group by this table's sharding key plus other-side columns with distinct names keep the optimization.

The test covers the exception (INNER, LEFT, comma join, GROUP BY, LIMIT BY, constant ALIAS), the GROUP BY r.k wrong result, RIGHT joins, a non-GLOBAL RIGHT/FULL join with a local right table (master returned a group once per shard), and EXPLAIN checks that the sound cases (CROSS join, ARRAY JOIN, ALIAS of the sharding key) stay shard-local.

Not covered: a column whose name equals a generated expression name (for example a column literally named toString(a)) can still collide; covering it would mean building the probe over qualified identifiers.


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

@groeneai

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

Pre-publication review by an independent model (engine: codex; 2 findings across an initial pass and a delta recheck; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ A blanket "disable for every join" fallback would also disable the optimization for joins without a name collision (perf regression). AGREE Verified GROUP BY l.<sharding_key> on a global join is sound (skip=1 == skip=0, incl. right-side fan-out). Replaced the blanket guard with a per-source check so sound joins keep the optimization.
2 ❌ A narrow name-collision guard still lets a right-side column whose name equals the left sharding key match it by name and wrongly select a shard-local Complete stage → wrong results. AGREE Verified a REAL, pre-existing (present on master) wrong-results bug: cross-shard GROUP BY r.k (left sharded by k) returned 7 → 5, 7 → 5 with skip=1 vs the correct 7 → 10 with skip=0. Fixed by the final guard (below) and covered by a new regression case.

Final fix: isShardingKeySuitsQueryTreeNodeExpression now requires every column in the probed expression to come from this distributed table's own source (query_info.table_expression); otherwise the analyzer falls back to merging on the initiator. This addresses both findings with one guard — it fixes the crash and the wrong-results while preserving single-table and same-table sharding-key aggregation. Rebuilt and re-verified both directions plus 50/50 randomized runs.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-author-slot-2:20260720-163500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a 2-shard cluster, SELECT DISTINCT l.c, r.c + 2 FROM nb_dl AS l INNER JOIN nb_dr AS r ON l.a = r.a SETTINGS distributed_product_mode='global', optimize_skip_unused_shards=1 throws Code 43 every time; optimize_skip_unused_shards=0 runs fine.
b Root cause explained? Yes. getOptimizedQueryProcessingStageAnalyzer → isShardingKeySuitsQueryTreeNodeExpression builds a type-checked ActionsDAG over unqualified column names (use_column_identifier_as_action_node_name=false). In a join, l.c (String) and r.c (Int64) collapse onto one action node, so r.c + 2 builds plus(String, UInt8) → throw on the initiator during planning.
c Fix matches root cause? Yes. Unqualified-name reasoning is only valid for a single source; the fix restricts the optimization to expressions whose columns all come from this distributed table's source, otherwise falls back to initiator merge (the optimize_skip_unused_shards=0 behavior). Not a symptom guard.
d Test intent preserved / new tests added? Yes. New stateless test 03471_... covering DISTINCT/LEFT/GROUP BY/comma-join, a non-colliding join (optimization preserved), and a cross-shard GROUP BY r.k wrong-results regression. Reference equals the optimize_skip_unused_shards=0 oracle. No existing test weakened.
e Both directions demonstrated? Yes. Pristine binary: crash queries throw Code 43, cross-shard GROUP BY r.k returns 7→5, 7→5. Fixed binary: all match optimize_skip_unused_shards=0 (7→10).
f Fix general across code paths? Yes. The guard is at the single owning function isShardingKeySuitsQueryTreeNodeExpression, covering all three call sites (DISTINCT, GROUP BY, LIMIT BY). The old non-analyzer path uses AST name-set membership (no DAG build) and is unaffected.
g Fix generalizes across inputs? Yes. The guard triggers on column source, independent of column type/wrappers; it covers String/Int64 and any type pair, and any sharding-key name shared across sides. Verified same-type columns (previously "correct values, wrong header") also take the safe path.
h Backward compatible? Yes. No setting default / wire / on-disk / metadata change. A query that threw now succeeds; a query that optimized keeps optimizing unless it is an unsound join case (then it merges on the initiator, as it already did with optimize_skip_unused_shards=0). No SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. Returning {} is an already-supported result of this function (used for extremes, grouping sets, rollup, window); the caller falls back to WithMergeableState. No new invariant introduced; distributed aggregation correctness (merge on initiator when a group can span shards) is restored.

Session id: cron:clickhouse-author-slot-2:20260720-163500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @devcrafter - could you review this? optimize_skip_unused_shards on a global distributed join builds the shard-stage probe (isShardingKeySuitsQueryTreeNodeExpression) over unqualified column names, so a same-named column from another join side either collapses onto the wrong node and throws ILLEGAL_TYPE_OF_ARGUMENT (issue #111089) or is matched to the sharding key by name and returns unmerged per-shard partials. The fix restricts the optimization to expressions whose columns all come from this distributed table's source.

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b990620]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
03759_distinct_json_paths_optimization FAIL cidb
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) ERROR
LLVM Coverage DROPPED

AI Review

Summary

This PR closes the correctness holes around same-named columns in distributed joins, but the new shard-local precheck is still too conservative in two realistic shapes that used to keep optimize_distributed_group_by_sharding_key: equivalent join keys carried by the non-distributed side, and trivial VIEWs that were inlined by optimize_trivial_view_pushdown_to_distributed. I do not think it is ready to approve until those regressions are addressed.

Findings

⚠️ Majors

  • [src/Storages/StorageDistributed.cpp:907] The new carrier check still requires the grouped sharding-key name to come directly from query_info.table_expression, so sound INNER equi-join cases like ... ON l.k = r.k GROUP BY r.k or INNER JOIN ... USING (k) now fall back to initiator-side merge even though the join predicate already proves that value is the left sharding key on every output row. That is a real regression of optimize_distributed_group_by_sharding_key for a common join shape.
    Suggested fix: teach the precheck to accept join-key carriers that are proven equal to this table's sharding key by JOIN ON / USING, instead of requiring the surviving ColumnNode source to be the left table verbatim.
  • [src/Storages/StorageDistributed.cpp:901] sourceIsAlwaysPreserved still stops at QueryNode, but trivial-view pushdown rewrites the outer table expression to an inlined QueryNode while keeping query_info.table_expression pointed at the underlying distributed table (src/Planner/PlannerJoinTree.cpp:2634). After that rewrite even a simple SELECT k FROM v GROUP BY k loses the shard-local Complete path, so this fix regresses pushed-down trivial VIEWs back to initiator merging.
    Suggested fix: make the preservation walk descend through pushed-down QueryNode/UnionNode wrappers (or otherwise compare against the underlying table expression after pushdown) and cover it with a focused stateless regression.
Tests
  • ⚠️ Please add focused stateless coverage for the two missing plan shapes above: one INNER equi-join / USING case where the right-hand key is provably equal to the left sharding key, and one trivial pushed-down VIEW grouped by that sharding key under optimize_trivial_view_pushdown_to_distributed = 1.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • preserve the shard-local path for proven-equal INNER join keys instead of requiring the grouped column to originate from the distributed table directly;
    • look through pushed-down trivial-view wrappers when checking whether the distributed source is preserved, and add regression coverage for both cases.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 20, 2026
Comment thread src/Storages/StorageDistributed.cpp Resolved
…gation

The previous guard disabled optimize_distributed_group_by_sharding_key for any
DISTINCT / GROUP BY / LIMIT BY key that referenced a column from another join
side, which regressed sound cases: grouping by this table's own sharding key
(e.g. GROUP BY l.k, r.v with the table sharded by k) keeps every group on a
single shard, so shards can still process it to Complete.

Accept the shard-local shortcut only when it stays sound and reject the three
situations the unqualified-name matching breaks on:
- an unqualified name is exposed by more than one source: the type-checked DAG
  collapses them and can throw (issue ClickHouse#111089);
- a sharding-key column name is not backed by this table's own column: a
  same-named column from another side does not pin the shard (wrong results);
- a RIGHT/FULL join can null-extend this table: an unmatched row carries no
  sharding key and is produced on every shard, so a group keyed by it spans
  shards (wrong results).

Add EXPLAIN-based assertions that GROUP BY over this table's sharding key
alongside another side's column stays shard-local, while a RIGHT JOIN that can
null-extend it merges on the initiator and matches the non-optimized result.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-111089-skip-unused-shards-distributed-join-column-binding branch from e788f21 to 4779b18 Compare July 20, 2026 20:57
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in 4779b18. You were right, the previous guard over-corrected.

The guard now accepts the shard-local shortcut whenever it stays sound and rejects only three cases:

So GROUP BY l.k, r.v and DISTINCT l.k, r.v keep the optimization when l.k is this table's sharding key, while GROUP BY r.k (wrong side) and the crash case fall back to initiator merge.

Verified on a 2-shard cluster (EXPLAIN indexes for the plan, oracle = optimize_skip_unused_shards = 0 for correctness):

  • fires (no MergingAggregated): single-table GROUP BY k, INNER/LEFT GROUP BY l.k and GROUP BY l.k, r.w;
  • merges: RIGHT/FULL GROUP BY l.k, r.v, GROUP BY r.k, and the same-named collision cases.

While checking the RIGHT/FULL case I found the first narrow version still returned unmerged partials for RIGHT JOIN ... GROUP BY l.k, r.v (an unmatched right row is broadcast to every shard with a null l.k); that is covered by the null-extension check and a regression case. Test 03471_... now also covers the LIMIT BY path and pins the two governing settings instead of skipping the flaky check.

Note: #111123 guards the same function for the related optimize_distributed_group_by_sharding_key JOIN wrong-result and has the same over-broad shape (and the same RIGHT/FULL gap). Happy to unify them if that is preferred.

Comment thread src/Storages/StorageDistributed.cpp Resolved
The shard-local precheck for optimize_distributed_group_by_sharding_key
collected an unqualified name for every ColumnNode, including ALIAS columns.
The type-checked DAG it guards is built with
use_column_identifier_as_action_node_name = false, where an expression-backed
column is represented by its expression (PlannerActionsVisitor::visitColumn
recurses into it) and never materialized under its own name. So the precheck
saw name collisions the DAG never produces and disabled the optimization for
sound keys, e.g. GROUP BY l.k_alias, r.k_alias where l.k_alias is ALIAS of the
sharding key and the two aliases wrap different physical columns.

Record only leaf physical column names (skip expression-backed wrappers; the
visitor still descends into their expressions to reach the leaves), and do not
descend into a constant-backed column, mirroring how the DAG treats constants.

This keeps the correctness guards from issue ClickHouse#111089 (the type-mismatch throw,
the wrong-side sharding-key wrong-results, and the RIGHT/FULL null-extension
cases) while restoring the optimization for alias-backed sound keys.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
sourceIsAlwaysPreserved only recognized JoinNode, so it returned false for
every other join-tree node. The query tree keeps CROSS and comma joins under
CrossJoinNode and ARRAY JOIN under ArrayJoinNode, so grouping by this table's
own sharding key over such a join (e.g. GROUP BY l.k, r.c with l.k the sharding
key) was wrongly forced to merge on the initiator instead of taking the
shard-local path, a performance regression for a sound query.

Descend through every node the join tree can hold: leaf, binary JoinNode
(null-extension aware), N-ary CrossJoinNode (CROSS/comma never null-extends any
child), and unary ArrayJoinNode (ARRAY JOIN, including LEFT ARRAY JOIN, only
replicates the input rows and never nulls the base table columns). Mixed joins
are left-associative, so the recursion must reach a table nested under a
CrossJoinNode.

Add CROSS-join regression coverage to 03471 (EXPLAIN preservation and result
equality) and regenerate the reference.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
return false;
}

return true;

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 is still too conservative for INNER equi-joins where the other side's key is proven equal to the distributed table's sharding key. For example, if l is sharded by k, SELECT r.k, count() FROM dist AS l INNER JOIN dim AS r ON l.k = r.k GROUP BY r.k is still shard-local: every output row has r.k = l.k, and l.k pins the shard. This branch forces that query (and the same DISTINCT / LIMIT BY shapes) back to initiator merge because the carrier of k is r, even though the join condition already proves it is the same value.

…-analyzer job

The guarded optimization under test (getOptimizedQueryProcessingStageAnalyzer)
only runs under the analyzer. In the old-analyzer stateless job the server
defaults enable_analyzer=0, so the MergingAggregated plan-shape assertions took
a different code path and the RIGHT-join cases flipped (deterministic 3/3 FAIL).
Pin enable_analyzer=1 at statement level so the test exercises the guarded path
regardless of the job's analyzer default. Results and correctness cases unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 44/47 (93.62%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ba4d7ac

CI fully finished (Finish Workflow / Mergeable Check / Config Workflow / CH Inc sync all green). One red check, owned:

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter Chronic flaky, not caused by this PR (109 failures on master + many unrelated PRs in the last 30d; this PR only touches StorageDistributed shard-pruning). #111029 (external, open)

Session id: cron:our-pr-ci-monitor:20260721-130000

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 4, 2026
groeneai and others added 4 commits October 7, 2026 13:02
…-skip-unused-shards-distributed-join-column-binding

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep only the invariants a reader needs at each spot: the source collector
follows the plain-name ActionsDAG builder's column visibility, null-extended
rows carry no sharding key, and the guard must run before the DAG is built.
The examples and the per-case reasoning live in the earlier commit messages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PlannerActionsVisitor::visitColumn materializes a column whose expression is a
constant as a constant action named after the column, instead of looking
through it. The source collector skipped such columns entirely, so a constant
ALIAS `x` on one join side and a physical `x` of another type on the other
side still collapsed onto one plain-named node and threw
ILLEGAL_TYPE_OF_ARGUMENT, e.g. `x String ALIAS 'abc'` against `x Int64` with
`SELECT DISTINCT l.k, l.x, r.x + 2`. Record them under their own name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The guarded probe only runs with the setting enabled, and the runner turns it
off for about 5% of runs, so the exception and r.k cases passed vacuously then.
Measured through system.query_log: 5 of 65 runs had it off without the clamp,
0 of 85 with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
if (!expected_source)
return false;

if (!sourceIsAlwaysPreserved(join_tree, expected_source))

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.

query_info.table_expression is not always a direct child of the top-level join tree here. When optimize_trivial_view_pushdown_to_distributed inlines a trivial VIEW, PlannerJoinTree rewrites query_info.query_tree to contain the view-body QueryNode but keeps query_info.table_expression pointed at the underlying dist_table_node. Because sourceIsAlwaysPreserved stops at QueryNode, even a simple SELECT k FROM v GROUP BY k now fails this check and loses the shard-local Complete path although the view is only passing k through. We need a query-node-aware preservation check (or some other way to recognize passthrough view projections); otherwise this correctness fix becomes a broad performance regression for pushed-down views.

groeneai and others added 2 commits October 7, 2026 16:37
After the master merge the file already includes `Analyzer/ArrayJoinNode.h`
near the top of the analyzer block, so this PR's copy tripped
`readability-duplicate-include` in `Build (arm_tidy)`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The existing RIGHT JOIN cases group by `l.k, r.k`, so the same-name check
alone already forces the merge, and master now rewrites a GLOBAL RIGHT JOIN
into a LEFT JOIN before the stage is chosen. Neither case reached the
null-extension check: with it disabled the test still passed.

A non-GLOBAL RIGHT or FULL JOIN with a local right table runs on every shard
against the whole table, so an unmatched right row gets a default `l.k` on
each shard. Grouping by `l.k` alone then has no name collision, and on master
returns the group `0` twice (8 and 7 rows instead of one row of 15).

Verified: with the check disabled the two new assertions flip to 0 (default,
parallel replicas and serialize_query_plan configurations); with it, 33/33,
20/20 and 15/15 randomized non-environment runs pass.

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

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b990620

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 03759_distinct_json_paths_optimization flaky, not from this PR (which changes optimize_skip_unused_shards for distributed joins): with the randomized use_columns_cache, the distinct-paths subcolumn is split over two rows when only some granules are cached, so the per-row output differs while the union is the same. It failed on 9 other pull requests and 2 master runs since 2026-10-05 #123942 (mine, open)
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) job timeout: the job hit its 9000 s limit at test 12964 of 15479 with 0 failed tests. This job hit the same limit on 32 other pull requests and 2 master runs in 14 days #116209 (mine, open): splits this job into 2 batches
Mergeable Check, PR rollups, red only because of the rows above #123942, #116209

All 149 check runs completed, Finish Workflow and CH Inc sync are green, and CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261008-020432

This branch has not been deployed

No deployments
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-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

2 participants