Skip to content

Fix optimize_distributed_group_by_sharding_key wrong result for JOIN - #111123

Open
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:fix-distributed-group-by-sharding-key-join-111087
Open

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:fix-distributed-group-by-sharding-key-join-111087

Conversation

@groeneai

@groeneai groeneai commented Jul 20, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111087
Closes: #111274

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 a wrong result with optimize_distributed_group_by_sharding_key when grouping a distributed JOIN by a column from the other join side that shares the sharding key's name (e.g. GROUP BY r.k over a LEFT JOIN where r.k is not the distributed table's sharding key). Such groups can span shards, so the per-shard aggregation shortcut is no longer applied for them, avoiding duplicate group keys with split aggregate values.

Description

On 26.8, grouping a distributed LEFT JOIN by the right side's r.k, where k is the left table's sharding key, returns the same group several times with the aggregate split between the copies instead of one merged row per key, whenever optimize_distributed_group_by_sharding_key = 1.

optimize_distributed_group_by_sharding_key lets StorageDistributed skip the cross-shard merge when the GROUP BY key is the sharding key, assuming each group lives on one shard. isShardingKeySuitsQueryTreeNodeExpression compared the grouping expression to the sharding key by column name alone, because qualifiers are stripped when the comparison DAG is built, so a foreign r.k took the shortcut. Unmatched left rows pad r.k = 0 on every shard, so that group does span shards and the per-shard partials came back unmerged.

The shortcut is now skipped when the grouping, DISTINCT or LIMIT BY expression references a column that is not the distributed table's own, and when that table sits on a side an outer join pads. GROUP BY over its real sharding key still takes it. Padding is not the necessary condition: an INNER JOIN whose condition is not an equality on the sharding key reaches the defect through the same foreign column, and the regression covers it.

#111274, where optimize_skip_unused_shards = 1 duplicates every group of a distributed self-join on intHash64(k), is the same root cause and the same guard fixes it: GROUP BY negate(r.k) reads r.k from the broadcast side, matching the sharding key name once qualifiers are stripped. Measured 1000 rows (500 duplicated) before and the correct 500 after.


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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 2-shard cluster, SELECT r.k, count(), max(l.k) FROM dl AS l LEFT JOIN dr AS r ON l.k=r.k AND l.k>29 GROUP BY r.k ... SETTINGS distributed_product_mode='global', optimize_skip_unused_shards=1, optimize_distributed_group_by_sharding_key=1 returns the r.k=0 group twice (unmerged per-shard partials) every run on master.
b Root cause explained? Yes. In the new analyzer isShardingKeySuitsQueryTreeNodeExpression matches the GROUP BY expression against the sharding key by column NAME only (qualifiers stripped). A right-side r.k sharing the left table's sharding-key name k matches, but LEFT JOIN pads unmatched rows with r.k=0 on every shard, so that group spans shards and per-shard aggregates are returned unmerged.
c Fix matches root cause? Yes. Skips the shortcut when the expression references any column not from the distributed table's own table_expression (the exact "single-shard groups" precondition), via the canonical hasUnknownColumn helper. Not a symptom band-aid.
d Test intent preserved / new tests added? Yes. New test 04613_distributed_group_by_sharding_key_join_wrong_side asserts both correctness (GROUP BY r.k matches the non-optimized result) and that the optimization still fires for the legitimate GROUP BY l.k case. No existing test weakened.
e Both directions demonstrated? Yes. Pristine master: r.k=0 duplicated. With fix: single merged group, equal to optimize=0. Committed .sql output matches .reference only with the fix.
f Fix is general across code paths? Yes. The single guard covers all three consumers (DISTINCT / GROUP BY / LIMIT BY). The old analyzer path was verified already correct (qualified ASTIdentifier::name() "r.k" != "k"), so there is no sibling path to patch.
g Fix generalizes across inputs? Yes. Verified across LEFT/RIGHT/INNER/FULL joins, l.k vs r.k, function-over-column, and distributed table on either side. The guard is column-source based (not type/wrapper specific), so a type-wrapper matrix is N/A — no type gating is introduced.
h Backward compatible? Yes. The change only NARROWS when the shortcut fires; it can only disable an unsound optimization, never enable anything new. No setting default / on-disk / wire format change, so no SettingsChangesHistory.cpp entry needed.
i Invariants and contracts preserved? Yes. Upholds the optimization's disjoint-shard precondition (each group's rows on a single shard). Uses the same column_source == table_expression pointer-identity property already relied on by CollectTableExpressionData / PlannerJoins. No block-structure or concurrency contract touched.

Session id: cron:clickhouse-author-slot-1:20260720-172200

@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; 0 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).

No blockers, majors, or nits were raised. The reviewer saw the full diff (3 files, +71) and reported a clean result.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @vdimir — could you review this? It fixes a silent wrong result: optimize_distributed_group_by_sharding_key matched the GROUP BY key against the sharding key by column name only, so grouping a distributed LEFT JOIN by a right-side column that shares the left table's sharding-key name wrongly took the shard-local aggregation shortcut and returned duplicate unmerged groups. The fix skips the shortcut when the expression references columns outside the distributed table (via hasUnknownColumn).

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a457d26]

Summary: ✅


AI Review

Summary

This PR hardens optimize_distributed_group_by_sharding_key for join shapes where a GROUP BY, DISTINCT, or LIMIT BY key can span shards even though it matches the sharding-key name. I read the current diff and all prior PR discussion/review threads, then checked the current head against the reported edge cases. The foreign-column guard, outer-join padded-side guard, CROSS JOIN / ARRAY JOIN traversal, and the wrapped-expression regression for #111274 are all covered in the current code and test file, and I did not find a new blocker or major issue to raise on the updated diff.

Final Verdict

✅ No new blockers or majors from me on the current version of this PR.

LLVM Coverage Report

Measured on commit a457d26.

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

Changed lines: Changed C/C++ lines covered: 9/25 (36.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 Jul 20, 2026
Comment thread src/Storages/StorageDistributed.cpp Resolved
@groeneai
groeneai force-pushed the fix-distributed-group-by-sharding-key-join-111087 branch 2 times, most recently from 68aa6b9 to 9ef09d5 Compare July 20, 2026 20:31
@groeneai
groeneai force-pushed the fix-distributed-group-by-sharding-key-join-111087 branch from 9ef09d5 to 2fc654d Compare July 20, 2026 21:56
Comment thread src/Storages/StorageDistributed.cpp Resolved
@groeneai
groeneai force-pushed the fix-distributed-group-by-sharding-key-join-111087 branch from 2fc654d to 9afc60e Compare July 21, 2026 03:21
optimize_distributed_group_by_sharding_key let StorageDistributed skip the
cross-shard merge when GROUP BY matched the sharding key, but the match was by
column name only. Two ways this produced unmerged per-shard partials (duplicate
group keys with split aggregate values):

1. For a distributed LEFT JOIN, GROUP BY on a right-side column that shares the
   left table's sharding-key name wrongly triggered the shortcut. Skip the
   shortcut when the grouping expression references any column not from the
   distributed table's own table expression, using the existing hasUnknownColumn
   helper.

2. Even when the grouping expression is over the distributed table's own
   columns, the shortcut is unsound if the table is on an outer-join padded side
   (left side of a RIGHT/FULL join, or right side of a LEFT/FULL join): unmatched
   rows default the sharding-key column to the same value on every shard, so that
   group spans shards. Walk the join tree and skip the shortcut when the table
   expression is on such a padded side. The walk also descends through
   cross/comma joins (CrossJoinNode): a cross join never pads its own operands,
   but does not shield them from an enclosing outer join, e.g.
   t CROSS JOIN u RIGHT JOIN v builds JoinNode(RIGHT){CrossJoinNode[t, u], v}, so
   t and u are on the padded left side.

Both guards are applied to the analyzer path
(isShardingKeySuitsQueryTreeNodeExpression) and the padded-side guard is also
applied to the old-analyzer AST path (getOptimizedQueryProcessingStage). The old
analyzer already resolved gap 1 correctly (it compares qualified ASTIdentifier
names, so a right-side r.k does not match the bare sharding key k), but it had no
padded-side check: for GROUP BY over the table's own sharding key under a
RIGHT/FULL join it still took the shortcut. Since the old analyzer works on a
flat, left-associative table list where this table is always the main/leftmost
operand, it is on a padded side iff any join in the list is RIGHT or FULL.

GROUP BY over the table's actual sharding key with no padding (single table,
inner join, or the non-padded side of an outer join) is unaffected.

The regression test 04613 exercises all of the above over a two-shard cluster;
its many distributed JOIN self-checks make a single run slow, so it is tagged
long to exempt it from the flaky check's 180s cap (which also runs it ~10x
instead of ~50x). The queries, assertions and expected results are unchanged.

Closes: ClickHouse#111087

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-distributed-group-by-sharding-key-join-111087 branch from f0cab3f to 2e24380 Compare July 21, 2026 06:27
Comment thread src/Storages/StorageDistributed.cpp Resolved
The outer-join padded-side guard added earlier disabled
optimize_distributed_group_by_sharding_key for any RIGHT/FULL join based
on JoinKind alone. SEMI joins keep only matched rows and emit no
default-padded rows, so RIGHT/FULL SEMI does not create a synthetic
cross-shard group when grouping by the distributed table's own sharding
key, and the shard-local shortcut stays sound. Exclude JoinStrictness::Semi
from the padded-side check in both the analyzer helper
(isTableExpressionOnOuterJoinNullSide) and the old-analyzer AST helper
(selectHasOuterJoinPaddingMainTable). ANTI keeps unmatched rows and does
default the other side's columns, so it remains treated as padding.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ession

The padded-side/foreign-column guard for optimize_distributed_group_by_sharding_key
is shared by DISTINCT and LIMIT BY, not only GROUP BY: the analyzer path reaches it
from the projection and LIMIT BY nodes, the old AST path from select.select() and
select.limitBy(). 04613 only asserted GROUP BY, so add focused DISTINCT and LIMIT BY
cases over the RIGHT JOIN padded side (both analyzer paths) plus the foreign-column
DISTINCT shape. Each case returns duplicated per-shard rows without the guard and the
merged result with it.

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

Copy link
Copy Markdown
Collaborator Author

Added in a647d84. The guard is shared by DISTINCT and LIMIT BY (analyzer: projection and LIMIT BY nodes; old AST: select.select() and select.limitBy()), so 04613 now asserts both for the RIGHT JOIN padded side, both analyzer paths, plus the foreign-column-name DISTINCT shape.

Verified both directions on a 2-shard rig (debug):

  • Without the guard (revert to merge-base, build bc17f564): the new cases return duplicated per-shard rows (e.g. DISTINCT l.k opt=1 -> [0,0,30,30,...,39,39], LIMIT 1 BY l.k opt=1 duplicates every (k,g)).
  • With the guard (309c9d66): every self-check equals the merged (opt=0) result.

New selfcheck results (0 = bug present on pristine, 1 = fixed):

Case pristine analyzer=0 pristine analyzer=1 fixed
DISTINCT l.k RIGHT JOIN (padded) 0 0 1
LIMIT 1 BY l.k RIGHT JOIN (padded) 0 0 1
DISTINCT r.k LEFT JOIN (foreign name) n/a* 0 1

*In the old AST path r.k is a qualified identifier that does not match the sharding key name, so that path never took the shortcut here; only the analyzer resolves r.k to the sharding-key expression, so this case is analyzer-only.

50/50 randomized pass with the long tag preserved.

/// holds only if the expression is over this distributed table's own columns. In a JOIN a column
/// from another table (e.g. the right side of a LEFT JOIN) may share the sharding-key name but
/// span shards, so exclude expressions that reference columns outside this table_expression.
if (query_info.table_expression && hasUnknownColumn(expr, query_info.table_expression))

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.

hasUnknownColumn is still too coarse for RIGHT SEMI JOIN ... USING (...). In the analyzer, a USING key is resolved through createProjectionForUsing, and that helper returns the right-side key for every JoinKind::Right regardless of JoinStrictness (src/Analyzer/Resolve/IdentifierResolver.cpp:1068-1069, 1361-1364). So GROUP BY k over bug_dl AS l RIGHT SEMI JOIN bug_dr AS r USING (k) reaches this check as the right table's k, and this line disables optimize_distributed_group_by_sharding_key before the existing DAG match can see that SEMI keeps only matched rows and the merged key is still equal to the left sharding key on every output row. That is an analyzer-only regression for a still-sound query shape (and it affects DISTINCT / LIMIT BY too because they share this helper). Please add a focused RIGHT SEMI JOIN ... USING (k) regression and make either the USING projection selection or this guard JoinStrictness::Semi-aware.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed the mechanism: createProjectionForUsing returns arguments.back() for JoinKind::Right (IdentifierResolver.cpp:1062), so USING (k) over a RIGHT join binds k to r.k regardless of strictness, and hasUnknownColumn(r.k, bug_dl) then disables the shortcut here.

Verified on a 2-shard cluster (count(bug_dl) = 80), fired = opt=1 returns unmerged per-shard partials (row count > opt=0), remerge = opt=1 partials re-summed on the initiator equals the opt=0 result:

shape analyzer=1 old AST remerge==opt=0
RIGHT SEMI ... USING (k) GROUP BY k not fired fired yes
LEFT SEMI ... USING (k) GROUP BY k fired fired yes
INNER ... USING (k) GROUP BY k fired fired yes
RIGHT JOIN ... USING (k) GROUP BY k not fired not fired yes
RIGHT SEMI ... ON l.k=r.k GROUP BY l.k fired fired yes

So this is a missed optimization on a still-sound shape, and only there: analyzer path, RIGHT SEMI ... USING. Results are already correct in every case (the old AST path already fires it; the analyzer path returns the fully-merged result). It also reaches DISTINCT / LIMIT BY through the same guard and USING resolution.

Enabling it safely means proving r.k is the equi-join partner of the leading table's sharding key: extract the join key pairs (USING list, or flatten the ON and tree), require JoinStrictness::Semi, map the foreign column to its kept-side partner, and accept only when that partner is the sharding key. That has to reject non-identity ON (l.k = r.k + 1), multi-column USING, self-joins, and ANTI; a false positive re-introduces exactly the padded/foreign-column wrong result this PR fixes.

Since it is perf-only and adds new equivalence analysis whose failure mode is the wrong-result class this PR closes, I am keeping #111123 focused on the correctness fix and tracking the RIGHT SEMI ... USING shortcut (plus its DISTINCT / LIMIT BY variants) as a separate follow-up with its own regression matrix.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Two corrections after re-measuring this on current master, plus one blocker that is
actionable for this PR itself.

1. The RIGHT SEMI JOIN ... USING gap is a property of this branch, not of master.
The hasUnknownColumn rejection is added by this PR; it does not exist upstream.
git show origin/master:src/Storages/StorageDistributed.cpp | grep -c hasUnknownColumn
returns 0, as does every active release branch (26.7, 26.6, 26.5, 26.3, 25.8), and
git log -S hasUnknownColumn origin/master -- src/Storages/StorageDistributed.cpp
returns 0 commits, so it has never been there. Measured on a 2-shard rig against the
master debug build at 25d677a44eb4be5 (buildId 3460f97598eaa277), all four shapes
already take the no-merge shortcut (opt=1 returns 40 rows vs 20 for opt=0):
RIGHT SEMI USING(k), LEFT SEMI USING(k), INNER USING(k) and RIGHT JOIN USING(k).
So on master this shape is not losing the optimization. Incidentally that also means the
RIGHT JOIN USING(k) GROUP BY k case fires on master too, so it is not a stays-disabled
control either. Both facts follow from master having no guard at all.

2. Therefore the SEMI-aware relaxation is not worth doing as a follow-up. It would
have to be written against unmerged code, and .claude/CLAUDE.md asks that a change
depending on unmerged work wait for that work to merge rather than be stacked. I am not
raising it and not planning to send it: there is no user-reachable consequence on master,
and the relaxation carries exactly the false-positive risk that would re-introduce the
wrong result this PR fixes. I would rather this PR stay focused on the correctness fix
for #111087.

3. Blocker: this branch no longer compiles against master. The patch still applies
cleanly, but building it gives 4 errors:

StorageDistributed.cpp:430,431,435,709: error: no matching function for call to
  'isTableExpressionOnOuterJoinNullSide'
note: no known conversion from 'const ITableExpressionNode' to 'const QueryTreeNodePtr'

The analyzer accessors changed to return the node by reference as ITableExpressionNode:
getLeftTableExpression is const QueryTreeNodePtr & at this branch's base
(9f4940328474268:src/Analyzer/JoinNode.h:51) but
const ITableExpressionNode & on master (src/Analyzer/JoinNode.h:52). CrossJoinNode
also moved into JoinNode.h (getTableExpressions at src/Analyzer/JoinNode.h:247).
The base here is 7893 commits behind master, so isTableExpressionOnOuterJoinNullSide
needs its signature and recursion updated before CI on this branch means anything.

@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 48.20% 86.20% +38.00%
Functions 56.90% 92.00% +35.10%
Branches 36.60% 78.30% +41.70%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a647d84

CI fully finished (Finish Workflow pass; Mergeable Check pass; Style / arm_tidy / all flaky-check jobs pass; 0 checks queued/in-progress; CH Inc sync pass). One failure, not caused by this PR's diff (optimize_distributed_group_by_sharding_key JOIN-side guard in StorageDistributed.cpp + the 04613 regression test).

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (replicated-DDL structure-alter race; unrelated to the distributed-GROUP-BY sharding-key change) fixing PR #109245 (ours, open; #110036)
PR rollup of the above owned via the row above

Note: the earlier Style / Build(arm_tidy) / 04613 flaky-check reds were PR-caused on prior heads (2e24380, f4639a3) and are all GREEN on this head a647d84.

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

Resolve the include-ordering conflict in src/Storages/StorageDistributed.cpp
(keep both Parsers/ASTSetQuery.h from master and Parsers/ASTTablesInSelectQuery.h
from this branch, alphabetically ordered).

Adapt the padded-side guard to the analyzer accessors master introduced with
ITableExpressionNode: the plain getLeftTableExpression/getRightTableExpression/
getTableExpression/getJoinTree accessors now return const ITableExpressionNode&,
so isTableExpressionOnOuterJoinNullSide and its call site take the pointer-returning
getLeftTableExpressionNode/getRightTableExpressionNode/getTableExpressionNode/
getJoinTreeNode forms. Guard semantics are unchanged.

Verified in the merged tree with two binaries differing only in this file:
without the guards 04613_distributed_group_by_sharding_key_join_wrong_side fails
under both analyzers (the padded group comes back as two unmerged per-shard
partials), with them it matches the committed reference byte for byte under both.
A single-table GROUP BY over the sharding key still takes the shard-local
shortcut, so the guard is not over-broad.
@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit a457d26246705d78f8eb663eafbff676b4515efb was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — dc10df5

Every failure below has an owner: a fixing PR (ours 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_tsan, s3 storage, parallel, 3/3) / 04676_adaptive_aggregation_replicated_argument flaky: reference diff on a per-arm normalization assertion whose oracle is nondeterministic. The in-job randomized-settings diagnosis reran it and reported Runs: 5, Failed: 1 verbatim. Onset today, 22 unrelated PRs in 30 days, 0 on master; this branch touches only StorageDistributed.cpp plus its own new 04613 test #115204 (ours, open)

Session id: cron:our-pr-ci-monitor:20260817-210000

@groeneai groeneai added the groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR 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
…ssion

The regression only exercised outer joins, whose comments explain the
unsoundness through default padding of unmatched rows. Padding is not the
necessary condition: the shortcut is unsound whenever the grouping expression
is a foreign column that merely shares the sharding key's name, because such
a group is not shard-local with respect to the sharding key. An INNER JOIN
whose condition is not an equality on the sharding key produces exactly that,
with no padded rows anywhere.

Without this case a later narrowing of the guard to outer-join padded sides
would look safe and silently restore the wrong result for INNER JOIN.

Reported on issue ClickHouse#111087 as a separate shape. Measured on this branch with
two binaries differing only in src/Storages/StorageDistributed.cpp: without
the guard the new assertion returns 0 (80 group rows instead of 40), with it
1, under both the analyzer and enable_analyzer = 0. GROUP BY over the
distributed table's own sharding key still takes the shard-local shortcut.
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 42efc99

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
AST fuzzer (amd_debug) / Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1 (STID 2270-3258) pre-existing LOGICAL_ERROR in RemoteSource::prepare(): a zero-column window function (count() IGNORE NULLS OVER ()) over cluster(..., view(...)) leaves the analyze header empty while the replica streams one column. Not caused by this branch: 130 hits over 80 distinct PRs plus master in the last 30 days, and this head's diff is test-only #113469 (mine, open)

The only other red is the PR rollup, which aggregates the row above.

Session id: cron:our-pr-ci-monitor:20260908-203055

master removed the query analysis that preceded the analyzer (ClickHouse#120311), deleting
StorageDistributed::getOptimizedQueryProcessingStage outright. The AST half of
this fix lived inside that function, so it goes with it, together with its helper
selectHasOuterJoinPaddingMainTable and the Parsers/ASTTablesInSelectQuery.h
include that existed only for it: an unused function in an anonymous namespace
does not survive -Werror. master's own hasLimitAfter()/hasLimitUntil() addition
to the surviving analyzer path is preserved.

The analyzer-path guard, now the entire fix, is placed below the collectSets()
call that 999d6ea added to isShardingKeySuitsQueryTreeNodeExpression
rather than above it. Registering the expression's IN sets is precisely what
that commit fixed, and ordering the guard after it leaves master's side effects
on the reject path unchanged; the cost is one tree traversal on a path that then
returns false.

The regression test loses its five old-analyzer arms. executeQuery.cpp now
raises INCORRECT_QUERY for any SETTINGS allow_experimental_analyzer = 0 found in
the query AST, the setting being IMPORTANT | OBSOLETE and frozen at 1, so each
of those arms errored and failed the test on current master. Every one was a
byte-for-byte twin of the analyzer arm above it, so the coverage that proves the
guard is untouched; the "(analyzer)" label suffixes, which no longer contrast
with anything, are dropped with them.
The RIGHT SEMI arm asserted that the shard-local shortcut keeps firing, on the
grounds that SEMI emits no default-padded rows and so is exempted from the
padded-side guard by strictness. On current master that no longer holds, and the
strictness exemption is not the reason: the analyzer resolves `l.k` in this shape
to the join's right column, so the provenance check sees a column foreign to
bug_dl and blocks the shortcut before strictness is ever consulted.

Blocking is conservative rather than required, the column it resolves to being
bug_dr's own sharding key, but it is not unsound, and the arm as written asserted
something that is now false. Assert instead the property that does hold and that
the guard exists for: optimize=1 agrees with optimize=0. Measured on two binaries
differing only in src/Storages/StorageDistributed.cpp, the new assertion returns
1 with the guard and 0 without it, so the arm still reddens on an unguarded build
and the regression now covers eight assertions rather than seven.

The LEFT SEMI arm still asserts that the shortcut fires, which is what shows the
SEMI exemption was not over-broadened into a blanket block on SEMI joins: there
`l.k` stays bug_dl's own column and the shortcut is reached.
The preceding two sentences already state the property the reader cannot derive
from the code, namely that a cross join does not shield its operands from an
enclosing outer join. The third only described what the loop below it does.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master and resolved the conflict in src/Storages/StorageDistributed.cpp.

master removed the query analysis that preceded the analyzer (#120311), deleting StorageDistributed::getOptimizedQueryProcessingStage. The AST half of this fix lived inside that function, so I dropped it rather than porting it, with its helper and the ASTTablesInSelectQuery.h include that existed only for it. The analyzer guard is the whole fix now, and it sits below the collectSets call that 999d6ea added to isShardingKeySuitsQueryTreeNodeExpression, so master's side effects on the reject path are unchanged. The five old-analyzer test arms are gone for the same reason: allow_experimental_analyzer = 0 is rejected outright now, so each of them errored.

One behaviour change worth flagging. The RIGHT SEMI arm asserted that the shortcut keeps firing, since SEMI emits no padded rows and the padded-side guard exempts it by strictness. On current master it no longer fires, and strictness is not the reason: the analyzer resolves l.k in that shape to the join's right column, so the provenance check sees a column foreign to the left table and blocks before strictness is consulted. Blocking is conservative rather than required there, the column it resolves to being the right table's own sharding key, but it is not unsound. I changed that arm to assert that optimize=1 agrees with optimize=0, which is what holds and what reddens without the guard. Keeping the optimization for that shape instead would need the guard to reason about join-condition column equivalence, and I would rather not add that here without your call.

Validation, on two binaries differing only in src/Storages/StorageDistributed.cpp: the test passes with the guard and fails without it, eight assertions flipping plus the duplicate-group rows. Style checks are clean, and the defect is still present on 26.8.

Residual I am noting rather than raising: the FULL JOIN and CROSS-under-RIGHT arms now pass on an unguarded build too, so they prove nothing for those shapes. Not wrong, only weak.

@groeneai
groeneai requested a review from devcrafter September 23, 2026 13:57
The regression file asserted the padded-side behaviour only through shapes where
the foreign-column check answers first, so nothing in it actually covered the
padded-side guard. Removing that guard outright left every assertion green, and
so did disabling its RIGHT/FULL half, its cross-join recursion and its SEMI
exemption individually. The FULL JOIN and CROSS-JOIN-under-RIGHT-JOIN arms held
even with no guard at all.

Both padded-side arms now run the join on the shards and keep the sharding key
out of the ON condition, which is what leaves the padded-side check as the
deciding rejection. Added a RIGHT SEMI positive control for the strictness
exemption, a DISTINCT arm blocked by the padded-side check rather than by the
foreign-column one, and the wrapped grouping expression of ClickHouse#111274 over an
expression sharding key.

Measured on a two-shard rig against per-clause mutants of the guard, counting
assertions that flip:

  no guard at all             13 (was 8)
  foreign-column check off    10
  padded-side check off        3 (was 0)
  RIGHT/FULL half off          3 (was 0)
  cross-join recursion off     1 (was 0)
  SEMI exemption off           1 (was 0)

The LEFT/FULL half remains uncovered. The right operand of a LEFT or FULL join
is the build side, never the side that aggregates per shard, so no shape I could
construct reaches it as the deciding rejection.

The two ClickHouse#111274 arms pin both settings that consult the sharding key instead of
leaving them to the test runner: with optimize_distributed_group_by_sharding_key
at 0 that shape never reaches the shortcut, and the assertion would then hold on
an unguarded build too.
…ssion

The padded-side check in StorageDistributed recurses through an array join, so a
table wrapped by ARRAY JOIN under an outer join is still recognised as sitting on
the padded side. Nothing in 04613 exercised that recursion: with the recursion
removed the whole file still passed, so the branch was covered by nothing.

Measured with an env-gated mutation of the guard's individual clauses:

  * unguarded build: the new assertion flips (80 unmerged rows against 40)
  * recursion removed, everything else intact: the new assertion is the only one
    in the file that flips
  * foreign-column check removed, or cross-join recursion removed: the new
    assertion is unaffected, so it is attributable to the array-join branch alone

The arm needs the join to run on the shards and the ON condition not to equate
the sharding key, for the same reasons as the FULL arm above it: a broadcast
right side resolves the grouping column to the other side, and an ON that
equates the sharding key lets the foreign-column check answer first. Either
relaxation makes the assertion pass with no padded-side check at all.

Reported by clickhouse-gh[bot] on ClickHouse#111123.
@devcrafter devcrafter self-assigned this Sep 27, 2026
@devcrafter
devcrafter requested a balanced review from Copilot September 27, 2026 22:21

Copilot AI left a comment

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.

Note

Copilot was unable to run its full agentic suite in this review.

Copilot review overview

Review effort: Lite
Findings: 3 High severity · 2 Medium severity · 1 Low severity

Open (6)
What changed in this PR

Fixes incorrect results from optimize_distributed_group_by_sharding_key for distributed JOIN queries where grouping/DISTINCT/LIMIT BY expressions can span shards despite sharing the sharding key’s column name.

Changes:

  • Add analyzer-based guards to disable the shard-local aggregation shortcut when the expression references non-owned columns or when the distributed table is on an outer-join padded side.
  • Introduce a comprehensive stateless regression test for JOIN shapes (LEFT/RIGHT/FULL/CROSS/ARRAY JOIN, SEMI/ANTI) and for expression-based sharding keys.
File Description
src/​Storages/​StorageDistributed.cpp Prevents unsafe shard-local optimization when grouping keys can span shards due to JOIN provenance/padding.
tests/​queries/​0_stateless/​04613_distributed_group_by_sharding_key_join_wrong_side.sql Adds regression coverage reproducing the wrong-result scenarios and validating the fix.
tests/​queries/​0_stateless/​04613_distributed_group_by_sharding_key_join_wrong_side.reference Defines expected outputs for the new regression test.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +7 to +25
DROP TABLE IF EXISTS bug_l;
DROP TABLE IF EXISTS bug_r;
DROP TABLE IF EXISTS bug_dl;
DROP TABLE IF EXISTS bug_dr;
DROP TABLE IF EXISTS bug_sk;
DROP TABLE IF EXISTS bug_dsk;

CREATE TABLE bug_l (k UInt32, g UInt32) ENGINE = MergeTree ORDER BY k;
CREATE TABLE bug_r (k UInt32) ENGINE = MergeTree ORDER BY k;
INSERT INTO bug_l SELECT number, number % 3 FROM numbers(40);
INSERT INTO bug_r SELECT number FROM numbers(40);

CREATE TABLE bug_dl (k UInt32, g UInt32) ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), bug_l, k);
CREATE TABLE bug_dr (k UInt32) ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), bug_r, k);

-- Second fixture, for issue #111274: the sharding key is an EXPRESSION over k, and the query
-- self-joins the distributed table on a column unrelated to it.
CREATE TABLE bug_sk (k UInt32, g UInt16, n Int64, lc String) ENGINE = MergeTree ORDER BY k;
INSERT INTO bug_sk SELECT number, number % 5, number, toString(number % 4) FROM numbers(60);
Comment on lines +7 to +25
DROP TABLE IF EXISTS bug_l;
DROP TABLE IF EXISTS bug_r;
DROP TABLE IF EXISTS bug_dl;
DROP TABLE IF EXISTS bug_dr;
DROP TABLE IF EXISTS bug_sk;
DROP TABLE IF EXISTS bug_dsk;

CREATE TABLE bug_l (k UInt32, g UInt32) ENGINE = MergeTree ORDER BY k;
CREATE TABLE bug_r (k UInt32) ENGINE = MergeTree ORDER BY k;
INSERT INTO bug_l SELECT number, number % 3 FROM numbers(40);
INSERT INTO bug_r SELECT number FROM numbers(40);

CREATE TABLE bug_dl (k UInt32, g UInt32) ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), bug_l, k);
CREATE TABLE bug_dr (k UInt32) ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), bug_r, k);

-- Second fixture, for issue #111274: the sharding key is an EXPRESSION over k, and the query
-- self-joins the distributed table on a column unrelated to it.
CREATE TABLE bug_sk (k UInt32, g UInt16, n Int64, lc String) ENGINE = MergeTree ORDER BY k;
INSERT INTO bug_sk SELECT number, number % 5, number, toString(number % 4) FROM numbers(60);
Comment on lines +271 to +276
DROP TABLE bug_dl;
DROP TABLE bug_dr;
DROP TABLE bug_dsk;
DROP TABLE bug_l;
DROP TABLE bug_r;
DROP TABLE bug_sk;
{
if (const auto * query_node = query_info.query_tree->as<QueryNode>())
{
if (isTableExpressionOnOuterJoinNullSide(query_node->getJoinTreeNode(), query_info.table_expression, /*padded_by_ancestor=*/ false))
Comment on lines +40 to +46
SELECT groupArray((k, c, m)) = (
SELECT groupArray((k, c, m)) FROM (
SELECT r.k AS k, count() AS c, max(l.k) AS m FROM bug_dl AS l LEFT JOIN bug_dr AS r ON l.k = r.k AND l.k > 29
GROUP BY r.k ORDER BY ALL SETTINGS optimize_distributed_group_by_sharding_key = 0))
FROM (
SELECT r.k AS k, count() AS c, max(l.k) AS m FROM bug_dl AS l LEFT JOIN bug_dr AS r ON l.k = r.k AND l.k > 29
GROUP BY r.k ORDER BY ALL SETTINGS optimize_distributed_group_by_sharding_key = 1);
Comment on lines +366 to +368
/// True if `target` sits, within the join tree `node`, on a side that an outer join fills with
/// defaults for unmatched rows. `padded_by_ancestor` carries that state down from enclosing joins.
bool isTableExpressionOnOuterJoinNullSide(const QueryTreeNodePtr & node, const QueryTreeNodePtr & target, bool padded_by_ancestor)
groeneai and others added 2 commits October 8, 2026 14:41
With the default `optimize_injective_functions_in_group_by = 1` the analyzer
rewrites `GROUP BY negate(r.k)` to `GROUP BY r.k` before the storage checks
the sharding key, so the ClickHouse#111274 arm only ever exercised a bare foreign
column. A guard that stopped looking through functions kept the file green.

Pin the setting to 0 in the `optimize_distributed_group_by_sharding_key` arm
so the wrapped key reaches the check, and to 1 in the `optimize_skip_unused_shards`
arm, which keeps the report's default shape. Both shapes return duplicated
groups without the fix (120 rows instead of 60) and the correct 60 with it.
A build whose foreign-column check sees only bare columns now fails exactly
that one assertion, and passed the file before this change.

Also wrap the SQL join kinds and the query tree shape in the guard's comments
in inline code. Comment-only; the binary is byte-identical.

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

clickhouse-gh Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

Dear @devcrafter, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

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-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

4 participants