Repository navigation
Fix RIGHT JOIN with parallel_replicas_min_number_of_rows_per_replica - #111332
Conversation
…ows_per_replica Under automatic parallel replicas (parallel_replicas_min_number_of_rows_per_replica > 0), a RIGHT JOIN that projects a left-table column failed with NOT_FOUND_COLUMN_IN_BLOCK (or THERE_IS_NO_COLUMN when aggregating a right-table column, and a silently wrong result on some releases). Plain parallel replicas (= 0) and LEFT/INNER joins were fine. The initiator runs index analysis on the leftmost leaf to estimate the replica count and passes that analyzed scan to createLocalPlanForParallelReplicas. For a RIGHT JOIN the local plan parallelizes the right table (findReadingSteps descends the right child), so the leftmost leaf's analysis (its parts and column list) was applied to the right table's read, requesting the left table's columns from the right table. Reuse the pre-analyzed result only when the parallelized scan was not reached through a RIGHT JOIN right-branch descent; otherwise let that scan analyze itself, which is the same path already taken when no analysis is passed. This is also correct for self-joins, where the two sides share the same storage but are distinct table-expression occurrences. Closes: ClickHouse#111206 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-7:20260722-071200 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 findings across 1 full pass + 1 delta recheck).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-7:20260722-071200 |
|
cc @devcrafter @nickitat — could you review this? It fixes a RIGHT JOIN failing under automatic parallel replicas ( |
|
Workflow [PR], commit [148caf4] Summary: ✅
AI ReviewSummaryThis PR fixes the classic local-plan parallel-replicas bug where a Final Verdict✅ No new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 29/29 (100.00%) · Uncovered code |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 18/18 (100.00%) · Uncovered code |
CI finish ledger — 06eb503CI fully finished (Finish Workflow complete, no checks queued/in_progress, >20 min ingestion buffer). Every failure below has an owner; none is caused by this PR's diff (which touches only
Session id: cron:our-pr-ci-monitor:20260722-170000 |
|
Fixing PR for the The failure is the plain-rewritable |
| std::vector<QueryPlan::Node *> findReadingSteps(QueryPlan::Node * root, bool allow_view_over_mergetree) | ||
| /// | ||
| /// `right_branch_selected` (optional out-param) is set to true if the descent to any returned | ||
| /// reading step went through the right child of a `RIGHT JOIN`. The initiator only ever analyzes |
There was a problem hiding this comment.
The initiator only ever analyzes the leftmost leaf
I remember we also might do the PK analysis for JOIN cardinality estimation or something like that. It's not true already?
There was a problem hiding this comment.
You are right, that sentence was wrong and I have reworded it.
Index analysis does run on non-leftmost leaves in several places, including estimateReadRowsCount for join cardinality estimation. None of them is a second carrier for this bug though: ReadFromMergeTree::selectRangesToRead caches into the step's own analyzed_result_ptr, so each of those callers analyzes the very step it is asking about, which is the same self-analysis that happens when no analysis is passed down.
The bug needs an analysis of step A applied to step B, and there are only two places that do that:
PlannerJoinTree.cpp:1894analyzesreading_steps.front()and moves that step intoexecuteQueryWithParallelReplicas, where it arrives asanalyzed_read_from_merge_treeand is reused on the nodefindReadingStepspicked by join kind. That is this bug.considerEnablingParallelReplicas.cpp:384setAnalyzedResult. This one cannot hit a join at all: itsfindReadingStepreturnsnullptrfor any node with more than one child, so it bails before reaching one.
So the invariant the fix relies on is not "the initiator only ever analyzes the leftmost leaf" but the narrower "the analysis handed to createLocalPlanForParallelReplicas is always the leftmost leaf's". The comment now says that instead.
There was a problem hiding this comment.
Following up on this with the swap case, which is the natural next question about which leaf's analysis is in play: if query_plan_join_swap_table flips a RIGHT JOIN to LEFT, does findReadingSteps then follow child 0 and reuse the left analysis on the right table anyway?
It cannot. createLocalPlanForParallelReplicas calls findReadingSteps on the plan straight out of extractQueryPlan, and that is only Planner::buildQueryPlanIfNeeded plus a move; there is no optimize call anywhere in ParallelReplicasLocalPlan.cpp. flip_join lives in optimizeJoinLogical, which runs from optimizeTreeSecondPass, so the traversal sees a JoinStepLogical whose children are still in source order and reads the source kind.
Confirmed on a three-replica server with the left table at 1000 rows and the right at 5000 with a different schema, so the swap's size precondition holds and a cross-table analysis would surface rather than be benign. With the swap forced on, EXPLAIN reports the join as Type: left and the results are byte-identical to enable_parallel_replicas = 0 for the projected-left-column case, the uniqExact case and RIGHT ANTI JOIN. INNER JOIN under a forced swap matches as well.
| @@ -0,0 +1,43 @@ | |||
| -- Regression test for https://github.com/ClickHouse/ClickHouse/issues/111206 | |||
| -- Automatic parallel replicas (parallel_replicas_min_number_of_rows_per_replica > 0) used to fail | |||
There was a problem hiding this comment.
Automatic parallel replicas is a different feature, parallel_replicas_min_number_of_rows_per_replica has no relation to it.
There was a problem hiding this comment.
Agreed, and the naming was wrong throughout. Renamed the test to 04800_parallel_replicas_min_rows_per_replica_right_join, and fixed the PR title, body and comments to name the actual trigger. (The number had to change anyway: 04371 was taken by a test merged since I opened this.)
On the automatic_parallel_replicas_mode = 0 pin, I checked whether it was masking an interaction now that the two are unrelated. It is not: InterpreterSelectQueryAnalyzer::buildContext forces enable_parallel_replicas to 0 when the mode is non-zero, and the runner randomizes the mode to 2 in 25% of runs, so without the pin the query under test would simply run without parallel replicas. Kept the pin, with a comment saying that rather than implying the features are layered.
Checking this also turned up something worse in the test: every assertion was a plain result that ordinary execution produces too, so it would have passed even with the path bypassed. It now asserts via EXPLAIN that parallel replicas actually ran (1 with these settings, 0 with the mode at 2 or parallel replicas off). The fixture also had no right-only keys, so RIGHT JOIN semantics and the silently-wrong-result variant were never exercised; there are now 20 such keys and RIGHT ANTI JOIN returns 20 rows instead of 0. The reference is generated with parallel replicas disabled, so it is ground truth.
There was a problem hiding this comment.
The test number had to move once more: 04800 failed Style check's test_numbers_check, which rejects a gap of 100 or more between consecutive stateless test numbers, and master's highest is 4694. It is now 04717_parallel_replicas_min_rows_per_replica_right_join (3d3e350), checked against the merge tree rather than my branch so the numbering reflects what CI actually builds.
`automatic_parallel_replicas_mode` is a separate feature from `parallel_replicas_min_number_of_rows_per_replica`, and the two are mutually exclusive: a non-zero mode forces `enable_parallel_replicas` to 0 in `InterpreterSelectQueryAnalyzer::buildContext`. Only the row-estimation path driven by `parallel_replicas_min_number_of_rows_per_replica` is affected by this bug, so the test is renamed to name that trigger instead of "automatic". The number also had to change: 04371 was taken by a test merged since this branch was opened. The comment claiming the initiator "only ever analyzes the leftmost leaf" was overbroad. Many sites run index analysis on non-leftmost leaves, including `estimateReadRowsCount` for JOIN cardinality estimation. They are harmless because `ReadFromMergeTree::selectRangesToRead` caches into the step's own `analyzed_result_ptr`, i.e. every one of them analyzes the step it asks about. What matters here is narrower and is what the comment now says: the analysis handed down to `createLocalPlanForParallelReplicas` is always the leftmost leaf's, so it must not be applied to a scan reached through a RIGHT JOIN right branch. The other cross-step graft, `considerEnablingParallelReplicas`, cannot hit this because its `findReadingStep` bails on any node with more than one child, so it never crosses a join. No behavior change: the executable part of the test is byte-identical and the reference is unchanged.
The test asserted only query results, all of which plain execution also produces, so it would have passed even if the parallel-replicas path were bypassed entirely. Assert that the path runs, via an EXPLAIN check for a parallel-replicas step. Verified both ways: it prints 1 with the settings under test and 0 when parallel replicas are off or when `automatic_parallel_replicas_mode` is non-zero, which is exactly the bypass the mode pin guards against. The fixture also had no unmatched right-side rows, so RIGHT JOIN's defining behaviour was never exercised and the silently-wrong-result variant of the bug was unchecked. Add 20 right-only keys and assert the left side comes back as defaults. This also gives RIGHT ANTI JOIN something to return: it counted 0 rows before and counts 20 now. The reference is generated from the same queries with parallel replicas disabled, so it is ground truth rather than observed output.
Style check's test_numbers_check rejects a gap of 100 or more between consecutive stateless test numbers. Master's highest number is 4694, so 04800 left a gap of 106 and failed the check. 04717 is free on master, in every open pull request, and across the local trees.
Per the repository instructions in .claude/CLAUDE.md, literal names from the ClickHouse SQL language belong in inline code blocks. Comment-only change; the reference file is unaffected.
CI finish ledger - 3d3e350Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 175 check-runs completed and Two notes on the ownership above, since both are links rather than tasks:
This diff is Session id: cron:our-pr-ci-monitor:20260804-033000 |
| -- With `parallel_replicas_min_number_of_rows_per_replica` > 0 the initiator analyzes the leftmost | ||
| -- leaf to estimate the replica count and hands that scan to the local plan, but the local plan | ||
| -- parallelizes the RIGHT table for a `RIGHT JOIN`, so the left leaf's parts and columns were applied |
There was a problem hiding this comment.
Isn't this a bug in the parallel_replicas_min_number_of_rows_per_replica logic. If we parallelize reading from the rhs table, we should also use it for to estimate the number of rows to read.
There was a problem hiding this comment.
You are right that the estimate reads the wrong table, and it is a real bug. Measured on a three-replica server with a 1000-row left table, a 5000-row right table and parallel_replicas_min_number_of_rows_per_replica = 2000:
small RIGHT JOIN big:Estimated 1000 rows to readand parallel replicas switched off, while the stream that would be read isbigat 5000 rows.big RIGHT JOIN small:Estimated 5000 rows to read. It is enough work for 2 parallel replicas, while the stream actually read issmallat 1000 rows.
So the sizing is taken from the leftmost leaf regardless of which side gets parallelized. LEFT and INNER look right only because for them the leftmost leaf is the parallelized side.
It is a separate bug from this one, and it sits downstream rather than upstream: fixing the estimate alone does not fix the column resolution, it makes it more reachable. The step moved into executeQueryWithParallelReplicas is reading_steps.front() of the leftmost leaf's plan, and storage_id is that leaf's as well, so an RHS-based row count changes rows_to_read but not which analysis is grafted onto the RHS scan. On master with a 5000-row left table, which is the estimate an RHS-based count would produce for the fixture above:
SELECT sum(cityHash64(r.ver, l.a)) FROM lbig AS l RIGHT JOIN big AS r USING (k)
SETTINGS ..., parallel_replicas_min_number_of_rows_per_replica = 2000
-- master: Code: 10. Column `a` not found in table big
-- this branch: 8861214719640598305, identical to enable_parallel_replicas = 0
And the 1000-row-left query at min_number_of_rows_per_replica = 1000 returns the correct answer on master only because the undersized estimate disables parallel replicas; an RHS-based estimate there is 5, which engages the path and fails. So an estimation-only change converts queries that work today into NOT_FOUND_COLUMN_IN_BLOCK.
On feasibility: the join kind is available at the estimate site, since allowParallelReplicasForJoinTree already reaches getRightTableExpression, but the RHS read step is not. buildJoinTreeQueryPlan plans the leftmost leaf first and returns early once its stage is no longer FetchColumns, so the remaining leaves are not planned yet, and the trace confirms big is first touched after the decision is logged. Sizing from the RHS therefore needs either a fresh index analysis on the RHS storage at that point, or the decision moved to the plan-level pass where parallel_replicas_plan_based already puts it. Either is more than a bugfix, so I would keep this PR to the column resolution and open the sizing one separately, unless you would rather have them together.
There was a problem hiding this comment.
Let's at least create an issue to track it.
There was a problem hiding this comment.
Agreed, it should be tracked. I do not open issues on this repo without a maintainer
confirming the report is wanted, so: confirm and I will file it, with the measurement from
above (1000-row left table, 5000-row right table, three replicas; the min_rows estimate
reads tl while tr is the side actually parallelized, and LEFT/INNER look correct only
because for those kinds the leftmost leaf is the parallelized side). I will link it here.
If you would rather file it yourself, that is fine too and I will add the measurement as a
comment.
There was a problem hiding this comment.
Filed as #113665, with the measurement from above rather than a fresh derivation.
Two corrections to what I wrote earlier in this thread, both found while writing it up:
- I said the fix would need a new estimate path on the right-hand side. It does not:
MergeTreeData::estimateNumberOfRowsToReadalready estimates from the primary key with no read plan in hand, andInterpreterSelectQuery.cpp:1192already uses it for this exact replica-count calculation. What is actually open is constructing the rightSelectQueryInfofor the right-hand table expression, plus the multi-read cases. - I framed the plan-level route as moving the decision to a pass that does not see joins. That was wrong.
applyParallelReplicasresolves the parallelized side correctly today (coordinatedJoinSideIndexreturns 1 forRIGHT, andcollectReadsToDistributedescends that side), and so doesfindReadingStepinconsiderEnablingParallelReplicas. Both already know which side is parallelized; neither implements row-count sizing. The sizing exists only on the query-tree path, which is the one that picks the wrong side, so that is the more accurate way to state the gap.
I could not apply the performance label, only file the issue.
| @@ -249,7 +252,8 @@ std::pair<QueryPlanPtr, bool> createLocalPlanForParallelReplicas( | |||
| auto query_plan = std::make_unique<QueryPlan>(std::move(interpreter).extractQueryPlan()); | |||
|
|
|||
| const bool allow_view_over_mergetree = context->getSettingsRef()[Setting::parallel_replicas_allow_view_over_mergetree]; | |||
| auto reading_nodes = findReadingSteps(query_plan->getRootNode(), allow_view_over_mergetree); | |||
| bool right_branch_selected = false; | |||
| auto reading_nodes = findReadingSteps(query_plan->getRootNode(), allow_view_over_mergetree, &right_branch_selected); | |||
There was a problem hiding this comment.
What is the relationship between reading_nodes and analyzed_read_from_merge_tree. Can we assume that analyzed_read_from_merge_tree should belong to one of the reading_nodes? Can it be non-null if reading_nodes.size() > 1? It looks very fragile that we take some external analyzed_read_from_merge_tree as a parameter then independently search for read nodes and emplace it somewhere. Can we at least check that reading_node->step == analyzed_read_from_merge_tree?
There was a problem hiding this comment.
Good questions, and the last one turned out to be measurable, so I built it.
Is analyzed_read_from_merge_tree one of the reading_nodes? No, and it never can be:
the two belong to different plans. PlannerJoinTree.cpp:2048 does QueryPlanStepPtr reading_step = std::move(reading_node->step) and ships that step out of the initiator's
plan (:2049-2057). createLocalPlanForParallelReplicas then builds a completely fresh plan
from the query tree (ParallelReplicasLocalPlan.cpp:250-251; extractQueryPlan is just
buildQueryPlanIfNeeded plus a move) and searches that new plan at :254. So the parameter
is a step taken out of a plan that was discarded, and reading_nodes are nodes of a plan
built afterwards. They cannot alias.
Which means reading_node->step == analyzed_read_from_merge_tree is never true. I
instrumented the function and ran it over plain, LEFT, INNER, RIGHT, self RIGHT JOIN,
and UNION ALL-view shapes plus the whole parallel_replicas stateless suite: 184
invocations, pointer equality false in all 184, including the plain single-table case the
reuse exists for. Then I added your check literally as a LOGICAL_ERROR and SELECT sum(a) FROM tl with parallel_replicas_min_number_of_rows_per_replica = 100 aborts the server:
<Fatal> : Logical error: 'NICKCHECK: analyzed_read_from_merge_tree is not among reading_nodes (n=1)'.
So it is not a cheap safety net, it is unsatisfiable.
Can it be non-null with reading_nodes.size() > 1? Not today, but only because of a
producer-side gate: PlannerJoinTree.cpp:2003 requires reading_steps.size() == 1 before
running the analysis, so a view over UNION never gets one. I did see size() == 2 in the
local plan (view over UNION ALL), always with a null analysis, and never saw reuse together
with size() > 1. That the invariant lives in the caller and not here is exactly the
fragility you are describing.
You are right that the shape is bad, and there is a check that does work: table identity
instead of step identity. The analysis carries a MergeTreeData, so reading_nodes.front()'s
storage id must equal the analyzed step's. That held in every invocation where reuse actually
happened (20 of the 184; the other 164 pass no analysis, so there is nothing to check), and
it would have caught the original bug at the assertion rather than in
getSampleBlockForColumns. Worth being explicit about its limit: a storage id does not
distinguish two occurrences of the same table, so it can supplement the right-branch gate but
not replace it. For a self RIGHT JOIN the gate suppresses reuse first, so the assertion is
never even reached there.
Happy to add that assertion in this PR if you want it. On tracking the estimation bug: I would
rather not open an issue without a maintainer confirming it is wanted, so if you confirm, I
will file it with the measurement from my earlier comment (1000-row left table, 5000-row right
table, three replicas: the min_rows estimate reads the left table while the right one is the
side actually read).
There was a problem hiding this comment.
Let's add a storage id assert and mention that it is still best-effort attempt to catch a bug.
There was a problem hiding this comment.
Added in b95c49b, with the comment saying it is
best-effort rather than an invariant.
/// Best-effort bug catcher, not an invariant: the analysis is built by the caller from a
/// different plan, and a storage id cannot tell two occurrences of one table apart.
const auto * reused_by = typeid_cast<const ReadFromMergeTree *>(reading_nodes.front()->step.get());
chassert(reused_by && reused_by->getStorageID() == analyzed_merge_tree->getStorageID(),
"pre-analyzed result belongs to a different table than the scan that reuses it");I checked that it catches the bug it is for rather than only that it stays quiet. With the
right_branch_selected guard removed, so the original bug is back, small RIGHT JOIN big
aborts at the assertion:
<Fatal> : Logical error: 'pre-analyzed result belongs to a different table than the scan that reuses it'
front_sid=default.m1r (9b24661e-...) analyzed_sid=default.m1l (bc14a106-...)
That is the failure being reported at the graft instead of downstream in
getSampleBlockForColumns. On the shipped code the same instrumentation says the assertion
is evaluated 106 times with 0 mismatches: the 04717 test plus the whole parallel_replicas
suite, in a debug build where chassert is live.
Two details worth stating, since both could have made this worse than nothing:
chassert compiles to (void)sizeof(!(x)) outside DEBUG_OR_SANITIZER_BUILD
(base/base/defines.h:85, :100-102), so release builds neither evaluate getStorageID()
nor take its lock. The unevaluated operand still counts as a use, so reused_by does not
trip -Wunused-variable under -Werror; I compiled the release form on its own to confirm
that, with a control that drops the chassert and is correctly rejected.
StorageID::operator== calls assertNotEmpty, which throws UNKNOWN_TABLE on an empty id
(src/Interpreters/StorageID.cpp:72, :74). Both sides here come from
MergeTreeData::getStorageID on a table the plan is reading (ReadFromMergeTree.h:286), so
neither is empty, and none of the 106 evaluations threw. It is worth knowing that this
particular comparison is not free of side effects if it is ever moved somewhere the operands
are less constrained.
Limit, as in the comment: a storage id does not distinguish two occurrences of one table, so
this supplements the reading_steps.size() == 1 gate at PlannerJoinTree.cpp:2003 and does
not replace it. For a self RIGHT JOIN the right-branch gate suppresses the reuse first, so
the assertion is never reached there.
`createLocalPlanForParallelReplicas` receives `analyzed_read_from_merge_tree` from the caller and independently searches its own freshly built plan for the scan to graft it onto, so nothing tied the two together. Compare the storage id of the scan that reuses the analysis against the analyzed step's. This is best-effort, not an invariant, and the comment says so: the two steps live in different plans, so pointer identity is unavailable, and a storage id cannot distinguish two occurrences of one table. It supplements the `reading_steps.size() == 1` gate in `PlannerJoinTree.cpp` rather than replacing it. `chassert` is active in debug and sanitizer builds only, so release builds are unaffected. Co-Authored-By: Claude Fable 5 <[email protected]>
CI finish ledger - b95c49bEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The Session id: cron:our-pr-ci-monitor:20260807-113000 |
|
Closing the loop on the That row is fixed by #112443 (merged 2026-07-30, Frame-keyed over 40 days, the eager |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units10 translation units recompiled, 67 s compile time in total, 10 of them have a recent master baseline. |
…o-read-setting Re-merge `master` now that #111332 "Fix RIGHT JOIN with `parallel_replicas_min_number_of_rows_per_replica`" has landed (`68867e5f0a3`, 2026-08-13). It fixes `NOT_FOUND_COLUMN_IN_BLOCK` / `THERE_IS_NO_COLUMN` and wrong results for `RIGHT JOIN` when this PR's randomized setting is greater than zero, which is one of the red classes this canary tracks. The diff against `master` stays exactly the single `SettingsRandomizer` line.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
NOT_FOUND_COLUMN_IN_BLOCK/THERE_IS_NO_COLUMNerrors (and, on some releases, silently wrong results) for aRIGHT JOINwhenparallel_replicas_min_number_of_rows_per_replicais set and a left-table column is projected.Description
Closes: #111206
With
parallel_replicas_min_number_of_rows_per_replica> 0, aRIGHT JOINthat projects a left-table column failed:It also surfaced as
Code: 8 THERE_IS_NO_COLUMNwhen aggregating a right-table column, throughRIGHT ANTI JOIN, and as a silently wrong result on some releases. Leaving the setting at 0, andLEFT/INNERjoins, were unaffected.Root cause: the initiator runs index analysis on the leftmost leaf to estimate the replica count and hands that scan to
createLocalPlanForParallelReplicas. For aRIGHT JOINthe local plan parallelizes the right table (findReadingStepsdescends the right child), so the leftmost leaf's parts and column list were applied to the right table's read, requesting the left table's columns from the right table.Fix: reuse the pre-analyzed result only when the parallelized scan was not reached through a
RIGHT JOINright-branch descent; otherwise let that scan analyze itself, which is what already happens when no analysis is passed. This is also correct for self-joins, where the two sides share the same storage but are distinct occurrences.Note this is unrelated to
automatic_parallel_replicas_mode, which is a separate feature: a non-zero mode forcesenable_parallel_replicasto 0, so the two never apply at once. An earlier revision of this PR mislabelled the bug as "automatic parallel replicas"; thanks to @nickitat for catching it.