Repository navigation
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-1:20260720-172200 |
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. |
|
cc @devcrafter @vdimir — could you review this? It fixes a silent wrong result: |
|
Workflow [PR], commit [a457d26] Summary: ✅
AI ReviewSummaryThis PR hardens Final Verdict✅ No new blockers or majors from me on the current version of this PR. LLVM Coverage ReportMeasured on commit a457d26.
Changed lines: Changed C/C++ lines covered: 9/25 (36.00%) · Uncovered code |
68aa6b9 to
9ef09d5
Compare
9ef09d5 to
2fc654d
Compare
2fc654d to
9afc60e
Compare
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]>
f0cab3f to
2e24380
Compare
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]>
|
Added in a647d84. The guard is shared by DISTINCT and LIMIT BY (analyzer: projection and LIMIT BY nodes; old AST: Verified both directions on a 2-shard rig (debug):
New selfcheck results (0 = bug present on pristine, 1 = fixed):
*In the old AST path 50/50 randomized pass with the |
| /// 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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 20/42 (47.62%) · Uncovered code |
CI finish ledger - a647d84CI 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).
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.
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger — dc10df5Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260817-210000 |
…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.
CI finish ledger - 42efc99Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The only other red is the 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.
|
Merged master and resolved the conflict in master removed the query analysis that preceded the analyzer (#120311), deleting 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 Validation, on two binaries differing only in 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. |
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.
There was a problem hiding this comment.
Note
Copilot was unable to run its full agentic suite in this review.
Copilot review overview
Review effort: Lite
Findings: 3
Open (6)
The test claims data is inserted directly into both shards’ local tables, but the localMergeTree… · New The test claims data is inserted directly into both shards’ local tables, but the localMergeTree… · New The test claims data is inserted directly into both shards’ local tables, but the localMergeTree… · Newquery_node->getJoinTreeNode()is passed unconditionally to `isTableExpressionOnOuterJoinNullSide(.… · New These self-checks comparegroupArray(...)results and rely onORDER BYin subqueries to make… · New The function name saysNullSide, but the comment/logic is about sides that are default-padded for… · New
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.
| 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); |
| 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); |
| 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)) |
| 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); |
| /// 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) |
…up-by-sharding-key-join-111087
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]>
|
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. |



Closes: #111087
Closes: #111274
Changelog category (leave one):
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_keywhen grouping a distributedJOINby a column from the other join side that shares the sharding key's name (e.g.GROUP BY r.kover aLEFT JOINwherer.kis 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 JOINby the right side'sr.k, wherekis 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, wheneveroptimize_distributed_group_by_sharding_key = 1.optimize_distributed_group_by_sharding_keyletsStorageDistributedskip the cross-shard merge when theGROUP BYkey is the sharding key, assuming each group lives on one shard.isShardingKeySuitsQueryTreeNodeExpressioncompared the grouping expression to the sharding key by column name alone, because qualifiers are stripped when the comparison DAG is built, so a foreignr.ktook the shortcut. Unmatched left rows padr.k = 0on every shard, so that group does span shards and the per-shard partials came back unmerged.The shortcut is now skipped when the grouping,
DISTINCTorLIMIT BYexpression references a column that is not the distributed table's own, and when that table sits on a side an outer join pads.GROUP BYover its real sharding key still takes it. Padding is not the necessary condition: anINNER JOINwhose 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 = 1duplicates every group of a distributed self-join onintHash64(k), is the same root cause and the same guard fixes it:GROUP BY negate(r.k)readsr.kfrom 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]