Skip to content

Fix RIGHT JOIN with parallel_replicas_min_number_of_rows_per_replica - #111332

Merged
nickitat merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111206-autopr-right-join
Aug 13, 2026
Merged

nickitat merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111206-autopr-right-join

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed NOT_FOUND_COLUMN_IN_BLOCK / THERE_IS_NO_COLUMN errors (and, on some releases, silently wrong results) for a RIGHT JOIN when parallel_replicas_min_number_of_rows_per_replica is set and a left-table column is projected.

Description

Closes: #111206

With parallel_replicas_min_number_of_rows_per_replica > 0, a RIGHT JOIN that projects a left-table column failed:

SELECT r.ver, (l.a + 2) FROM tl AS l RIGHT JOIN tr AS r USING (k);
-- Code: 10. Column `a` not found in table default.tr (NOT_FOUND_COLUMN_IN_BLOCK)

It also surfaced as Code: 8 THERE_IS_NO_COLUMN when aggregating a right-table column, through RIGHT ANTI JOIN, and as a silently wrong result on some releases. Leaving the setting at 0, and LEFT / INNER joins, 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 a RIGHT JOIN the local plan parallelizes the right table (findReadingSteps descends 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 JOIN right-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 forces enable_parallel_replicas to 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.

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT r.ver, (l.a + 2) FROM tl AS l RIGHT JOIN tr AS r USING (k) with parallel_replicas_min_number_of_rows_per_replica=100 on a 3-replica cluster fails every run with Code: 10 NOT_FOUND_COLUMN_IN_BLOCK: Column a not found in table tr.
b Root cause explained? Yes. The initiator runs index analysis on the leftmost leaf (tl) 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 = tr), and the leftmost leaf's analysis (its parts + column list [a,k]) is then reused for tr's read, requesting tl's columns from tr. Confirmed by instrumentation: reading step tr, but reused analyzed_result had column_names_to_read=[a,k] and parts from tl.
c Fix matches root cause? Yes. Reuse the pre-analyzed result only when the parallelized scan was NOT reached via a RIGHT-JOIN right-branch descent; otherwise pass nullptr so the scan analyzes itself (the same path the working min_rows=0 case takes). Directly addresses the mismatched-analysis reuse.
d Test intent preserved / new tests added? New test 04371_parallel_replicas_automatic_right_join added; asserts correct results across RIGHT JOIN (project left col), aggregate-of-right-col, RIGHT ANTI, self RIGHT JOIN, and LEFT/INNER regressions. No existing test weakened.
e Both directions demonstrated? Yes. Pristine binary: [FAIL] Code 10. Fixed binary: [OK], 50/50 with full randomization. Distinct Build IDs verified.
f Fix is general across code paths? Yes. The only site that reuses the initiator's analysis is createLocalPlanForParallelReplicas; the remote-plan path (createRemotePlanForParallelReplicas) re-analyzes fresh and needs no change. Covers Error 10, Error 8, RIGHT ANTI, and the silent-wrong-result variant (all funnel through this reuse). Not a symptom guard.
g Fix generalizes across inputs? Yes. Verified RIGHT / RIGHT ANTI / RIGHT SEMI, ON and USING, scalar and aggregate projections, overlapping and fully non-overlapping keys, self-join (same storage, distinct occurrences), and max_parallel_replicas 2/3/10 — all match the no-parallel-replicas reference.
h Backward compatible? Yes. No setting/format/protocol change. Only fixes an erroring / wrong-result path; the LEFT/INNER analysis-reuse optimization is preserved.
i Invariants and contracts preserved? Yes. Enforces the invariant "the reused analysis must belong to the parallelized scan". LEFT/INNER keep reuse (leftmost leaf == parallelized scan). Uses the join-kind descent (a robust property), not storage-pointer identity (which would be unsound for self-joins).

Session id: cron:clickhouse-author-slot-7:20260722-071200

@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; 3 findings across 1 full pass + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ Regression test could silently bypass parallel replicas: the runner randomizes automatic_parallel_replicas_mode=2 in ~25% of runs, which for joins skips building the parallel-replicas plan. AGREE — fixed Verified via EXPLAIN: mode=2 has no ReadFromRemoteParallelReplicas (path bypassed), mode=0 has it. Pinned automatic_parallel_replicas_mode = 0 in the test; re-ran 50/50.
2 💡 New C++ comments should backtick SQL / function names. AGREE — fixed Backticked RIGHT JOIN, createLocalPlanForParallelReplicas, NOT_FOUND_COLUMN_IN_BLOCK.
3 ⚠️ The left-scan analysis still drives the max_parallel_replicas sizing decision, so a RIGHT JOIN may under/over-size the replica count. DISAGREE Performance-only, not correctness: the asymmetric case (1 left / 1000 right / threshold 100) returns the correct result identical to the no-parallel-replicas reference. The sizing/estimation code (PlannerJoinTree.cpp:1893-1921) is untouched by this patch (git show HEAD --stat: 0 refs) — pre-existing and orthogonal, not introduced here. Re-pointing the estimate at the right-hand scan is a separate performance improvement (one root cause per PR).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-author-slot-7:20260722-071200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @nickitat — could you review this? It fixes a RIGHT JOIN failing under automatic parallel replicas (parallel_replicas_min_number_of_rows_per_replica > 0): the initiator's leftmost-leaf index analysis was reused for the right-side scan that the local plan actually parallelizes, so the left table's columns were requested from the right table (NOT_FOUND_COLUMN_IN_BLOCK). The fix skips that reuse when the parallelized scan is reached via a RIGHT-JOIN right-branch descent. Closes #111206.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [148caf4]

Summary: ✅


AI Review

Summary

This PR fixes the classic local-plan parallel-replicas bug where a RIGHT JOIN could reuse the leftmost leaf's ReadFromMergeTree analysis for the right-side scan, which is what produced NOT_FOUND_COLUMN_IN_BLOCK / THERE_IS_NO_COLUMN and the wrong-result variant. In the current diff, the reuse is skipped exactly on the RIGHT JOIN right-branch descent that makes the analyzed scan and the parallelized scan diverge, there is now a debug-only storage-id sanity check around the reuse point, and the regression test became discriminating enough to prove both that parallel replicas are actually used and that unmatched right-side rows stay correct. I did not find a new correctness or coverage gap in the current code beyond the separate replica-count sizing issue that is already tracked on the PR thread and in #113665.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.10% +0.10%

Changed lines: Changed C/C++ lines covered: 29/29 (100.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 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 18/18 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 06eb503

CI 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 ParallelReplicasLocalPlan.{cpp,h} plus the new 04371_parallel_replicas_automatic_right_join test).

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / ScatterExchangeStep should have one source shard (STID 4636-3f0c) chronic trunk fuzzer logical error (30+ unrelated PRs + master over 30d; first seen 2026-06-24, long predates this PR) #108401 (ours, merged 2026-07-22) fixes this signature; this failing build predates the merge and picks it up on the next rebase
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table::test_check_all_tables chronic integration flaky (60 unrelated PRs/30d; unrelated to a join-algorithm-selection change) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
PR / Mergeable rollup rollup of the two rows above owned via the rows above
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260722-170000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_check_all_tables flaky (Integration amd_asan_ubsan, db disk, old analyzer): #111353 (merged 2026-07-22, backported to 26.7 by #111574).

The failure is the plain-rewritable metadata_dropped concurrent-create race, not anything in this PR. Every occurrence after that merge is on a build whose base predates it: I checked all 49 distinct commits that produced this failure since 2026-07-22 17:31Z, and 49 of 49 lack the fix. Merging master into this PR picks it up. Details: #111477 (comment)

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

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.

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:1894 analyzes reading_steps.front() and moves that step into executeQueryWithParallelReplicas, where it arrives as analyzed_read_from_merge_tree and is reused on the node findReadingSteps picked by join kind. That is this bug.
  • considerEnablingParallelReplicas.cpp:384 setAnalyzedResult. This one cannot hit a join at all: its findReadingStep returns nullptr for 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.

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.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Automatic parallel replicas is a different feature, parallel_replicas_min_number_of_rows_per_replica has no relation to it.

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.

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.

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.

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.
@groeneai groeneai changed the title Fix RIGHT JOIN under automatic parallel replicas with min_number_of_rows_per_replica Fix RIGHT JOIN with parallel_replicas_min_number_of_rows_per_replica Aug 3, 2026
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.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3d3e350

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
Stress test (arm_msan) / Hung check failed, possible deadlock found Trunk bug, not caused by this branch: one CANCELLED INSERT INTO test SELECT number, toString(number) FROM numbers(1000000) runs 621 s (is_cancelled = 1). The artifact shows the working thread inside the wide-part granule loop at MergeTreeDataPartWriterWide::getCurrentMarksForColumn -> SerializationNullable::enumerateStreams -> ISerialization::getFileNameForStream, with the executor thread parked on ThreadPool::wait and the initiator on the completion event #108357 (external, open)
Stress test (amd_asan_ubsan) / Hung check failed, possible deadlock found Trunk bug, not caused by this branch: one CANCELLED AsyncInsertFlush (INSERT INTO test_2.test_json (data) FORMAT TSV) runs 587 s inside the JSON parse loop, SerializationJSON::deserializeObject -> SimpleObjectPool<SimdJSONParser>::Deleter #112646 (mine, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Cannot serialize FutureSetFromSubquery with no query plan (STID 2678-3c21) Trunk bug, not caused by this branch: the fuzzed query is a merge(...) with GLOBAL NOT IN (SELECT ... FROM remote(...)), and the plan-based path serializes a set whose source plan was already consumed. Frames are MultiplexedConnections::sendQueryPlan -> QueryPlan::serializeSets. Breadth over 30 d: 63 rows / 29 PRs / 0 master rows a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)
Build (arm_release) / Post Hooks CI harness, not a test result: build_profile_hook.py fails uploading build telemetry (LogCluster query failed with code 500 on the INSERT INTO build_time_trace). Job-level check_status = success, so the build itself is green. Breadth over 7 d: 887 rows / 301 PRs / 502 master rows a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)

All 175 check-runs completed and Finish Workflow is green.

Two notes on the ownership above, since both are links rather than tasks:

  • I did not link Make column data write during INSERT respond to query cancellation #108357 from its title alone. getCurrentMarksForColumn is called at
    MergeTreeDataPartWriterWide.cpp:622, inside the for (const auto & granule : granules) loop at
    :610, which is exactly where Make column data write during INSERT respond to query cancellation #108357 inserts its checkWriteCancellation(). On a sibling
    occurrence of this signature I built that PR and measured the same fuzzed INSERT ending at the
    limit with TIMEOUT_EXCEEDED (10.8 s) instead of running the block out (38.4 s).
  • The two hung rows share the waiting shape (PipelineExecutor on ThreadPool::wait, initiator on
    the Poco event) but have different working frames, so they are separate defects with separate
    owners. The bare Hung check failed test name covers 493 rows / 329 PRs / 90 master rows over
    30 d across many causes, so I attributed these by stack rather than by test name.

This diff is ParallelReplicasLocalPlan.cpp/.h plus its own new test 04717. None of the four rows
touches that path.

Session id: cron:our-pr-ci-monitor:20260804-033000

Comment on lines +2 to +4
-- 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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.

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 read and parallel replicas switched off, while the stream that would be read is big at 5000 rows.
  • big RIGHT JOIN small: Estimated 5000 rows to read. It is enough work for 2 parallel replicas, while the stream actually read is small at 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's at least create an issue to track it.

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.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Create the issue yourself.

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.

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::estimateNumberOfRowsToRead already estimates from the primary key with no read plan in hand, and InterpreterSelectQuery.cpp:1192 already uses it for this exact replica-count calculation. What is actually open is constructing the right SelectQueryInfo for 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. applyParallelReplicas resolves the parallelized side correctly today (coordinatedJoinSideIndex returns 1 for RIGHT, and collectReadsToDistribute descends that side), and so does findReadingStep in considerEnablingParallelReplicas. 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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

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.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's add a storage id assert and mention that it is still best-effort attempt to catch a bug.

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.

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]>
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b95c49b

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
Integration tests (arm_binary, distributed plan, 4/4) / test_dirty_pages_force_purge/test.py::test_dirty_pages_force_purge flaky, fresh onset 2026-08-06: TimeoutError: Timed out waiting for MemoryAllocatorPurge event at test.py:54. Breadth over 30 days: 3 rows across 3 distinct unrelated PRs, 0 master failures against 1530 master OK runs, and this branch does not touch the test or anything allocator-related a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Build (arm_release) / Post Hooks CI telemetry, not a build failure: the build-profile hook's INSERT INTO build_time_trace into the shared CI logs cluster failed with code 500 on all 8 attempts during a cluster memory-pressure spike. The build itself succeeded #113409 (external, merged), not yet on this branch

The Build (arm_release) row is a fix that has landed on master but is not on this branch yet: the
retry hardening in #113409 merged 2026-08-06T00:05Z, and ci/jobs/scripts/log_cluster.py at this
commit still lacks it (the marker it adds is absent here and present at master). Merging master
into the branch will pick it up. Mergeable Check also reports 23 dropped jobs on this commit.

Session id: cron:our-pr-ci-monitor:20260807-113000

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Closing the loop on the Cannot serialize FutureSetFromSubquery with no query plan row of my CI finish ledger above.

That row is fixed by #112443 (merged 2026-07-30, 26.8.1.392), which disables distribution for any plan still carrying a DelayedCreatingSetsStep. Re-tested on master f9801d56: the deterministic nested-IN repro under parallel_replicas_plan_based=1 now returns the oracle value instead of aborting, and EXPLAIN shows no parallel-replicas step for that plan while a plain tuple IN (1, 2, 3) is still distributed.

Frame-keyed over 40 days, the eager ParallelReplicasLocalPlan variant went 5 occurrences before that merge to 0 after. The remaining occurrences of the same message reach it through RemoteQueryExecutor::sendQueryUnlocked -> MultiplexedConnections::sendQueryPlan with no parallel-replicas frame, so they are the classic serialize_query_plan path rather than the one on this ledger row; #112849 covers that side. Both parallel_replicas_plan_based and serialize_query_plan are default off, and there are no master occurrences in the window.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 148caf403 with master e4b9fd740 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 91b700711; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.09 MiB 689.08 MiB -3.01 MiB (-0.43%)

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 units

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

Job report

@nickitat
nickitat added this pull request to the merge queue Aug 13, 2026
Merged via the queue into ClickHouse:master with commit 68867e5 Aug 13, 2026
180 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
alexey-milovidov added a commit that referenced this pull request Aug 13, 2026
…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.
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 pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Automatic parallel replicas (parallel_replicas_min_number_of_rows_per_replica > 0) fails RIGHT JOIN with NOT_FOUND_COLUMN_IN_BLOCK

4 participants