Skip to content

Fix logical error for RIGHT JOIN with parallel replicas - #113515

Merged
alexey-milovidov merged 28 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-113292-pr-right-join-descent
Sep 13, 2026
Merged

alexey-milovidov merged 28 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-113292-pr-right-join-descent

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #113292
Closes: #119408
Related: #108645

Changelog category (leave one):

  • Improvement

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

Fixed the logical error Can't determine table for parallel replicas for a RIGHT JOIN whose right side has no table eligible for parallel replicas, and made a RIGHT JOIN materialize a left side that is not a MergeTree instead of letting every replica read it independently.

Description

Master-only logical error at findParallelReplicasQuery.cpp:637; debug and sanitizer builds abort, reddening Stress and fuzzer jobs.

Root cause. For JoinKind::Right the side read with replicas is the right one, because buildQueryTreeForShard materializes the left table expression. getSupportingParallelReplicasQueries descended the left one, so a query was accepted for the side the rewrite then materialized and the lookup on the rewritten tree threw.

The fix descends the right expression again (RIGHT SEMI/ANTI too), then corrects three places that had the materialized side wrong:

  • rewriteJoinToGlobalJoin took locality from the right side for every kind; a RIGHT JOIN's materialized side must now be eligible for parallel replicas, not merely MergeTree.
  • It asked that of the raw storage, so an eligible View/MaterializedView lost its local join; the wrapper is resolved first.
  • The global-join collector skipped each global join's right child, leaving a nested global join in the offloaded subtree without a temporary table, and counted storages the initiator materializes anyway (a nested GLOBAL JOIN's materialized side, a GLOBAL IN).

The last two came from clickhouse-gh[bot]. No backport requested: the logical error is master-only, 26.2 to 26.7 still descend right. The local-read half may reach them, but no repro was measured on a release binary; that call is the maintainers'.

Validation. Five stateless tests, untagged and parallel-safe, split from one file whose single run exceeded the per-file 180s flaky-check budget; their references concatenate to the original plus one added arm pinning the nested global join to a temporary table. Each fails on unmodified master and passes 50 of 50 randomized runs at this head.

Disclosed and not fixed

All three are pre-existing on master or cost a plan rather than a result:

  • A nested local IN/JOIN over a multi-shard Distributed is auto-globalized only after this locality decision runs, so it still counts here and costs a local join master keeps. Reaching it needs prefer_global_in_and_join = 1 or distributed_product_mode = 'global', both off by default. Rows matched the parallel-replicas-off result on every arm, so this is a lost plan, not a wrong one.
  • A table function CollectStoragesVisitor does not collect leaves storages empty, which reads as all-MergeTree. This PR rejects that on a RIGHT JOIN's materialized side; a nested join of another kind still admits it, exactly as master does for every kind.
  • Eligibility is asked with the enclosing context, so a subquery that turns parallel_replicas_for_non_replicated_merge_tree or parallel_replicas_allow_view_over_mergetree off can still look eligible from outside. Decide parallel replicas eligibility with the subquery's own context #110020 threads the subquery's own context through both walks.

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

Version info

  • Backported to: 26.8.5.16

Fixes the logical error "Can't determine table for parallel replicas"
(findParallelReplicasQuery.cpp:630) for a RIGHT JOIN whose right side
has no table eligible for parallel replicas.

For JoinKind::Right, buildQueryTreeForShard materializes the LEFT table
expression into a temporary table, so the side actually read with
replicas is the RIGHT one, and findTableForParallelReplicas descends
right first. The eligibility decision in
getSupportingParallelReplicasQueries descended the LEFT expression
instead. A query was therefore accepted because the left side reads an
eligible MergeTree, rewriteJoinToGlobalJoin plus buildQueryTreeForShard
then materialized exactly that side, and the table lookup on the
rewritten tree found nothing eligible and threw.

Both halves used to agree: 88b22b8
("Introduce ITableExpressionNode in the query tree") changed this
descent target from right to left while renaming the getters. Every
other change that commit makes to this file is a mechanical rename and
it changes no tests, so the flip reads as an accidental slip. This
restores the pre-existing target under the renamed getter. The guard on
the left expression's node type is left untouched, being the existing
non-leftmost RIGHT JOIN gate rather than a descent target.

Two behaviour deltas, both improvements: queries that previously threw
now run without parallel replicas and return correct results, and the
left-ineligible / right-eligible shape regains the JOIN-level offload
that the flip had silently disabled.

Validated with a deterministic reproducer using a server-log oracle,
since a debug server aborts on the logical error and later client exit
codes are then meaningless. Checked across Nullable, LowCardinality,
LowCardinality(Nullable), Array and Const join keys, empty and
single-row inputs, and RIGHT ANY / SEMI / ANTI plus 3-way joins. EXPLAIN
output for LEFT, INNER and both-sides-eligible RIGHT joins is
byte-identical before and after, and the parallel-replicas join suite
gives identical results on both binaries.

The flipped line is master-only, so no backport is required.

Closes ClickHouse#113292.
…icas

getSupportingParallelReplicasQueries descended the LEFT table expression for
JoinKind::Right, so it accepted a query whose left side reads an eligible
MergeTree table while the right side does not. Only the right side is read with
replicas, so buildQueryPlanForParallelReplicas then failed to resolve a table
and threw "Can't determine table for parallel replicas".

Descend the right expression instead, and additionally require the left
expression to bottom out in an eligible table. The left side alone is not a
sufficient condition either: when the join is not rewritten to a global one the
left subtree is sent to every replica unchanged, which returns wrong results
rather than throwing. allowParallelReplicasForJoinTree already rejects that
shape for bare tables ("TODO: support parallel replicas for
(non_mt_table RIGHT JOIN mt_table) later"), so the two eligibility paths now
agree. Queries of either shape run without parallel replicas.

Closes ClickHouse#113292
Reverts the left-eligibility guard added in the previous commit and keeps only
the descent-target change, which is what every active release branch ships.

The guard was added on the argument that a RIGHT JOIN whose left side reads an
ineligible table returns silently wrong results when that side is not
materialized. That argument was never measured, and it is refuted from two
directions:

1. 25.8, 26.3, 26.5, 26.6 and 26.7 all ship the pre-regression form verbatim,
   a left node-type gate plus a right descent, with no left-eligibility check
   of any kind. If the hazard were real those releases would be returning wrong
   results for that shape today.

2. Measured here across four binaries (unfixed master, this fix, the guard, and
   a universal leaf predicate): the flat ineligible-left shape and both nested
   orderings return row sets identical to the enable_parallel_replicas = 0
   ground truth in every arm, at both parallel_replicas_prefer_local_join
   values.

The guard also narrowed behaviour relative to those releases: it rejects the
flat ineligible-left shape and the (table function LEFT JOIN table) nested
shape, which master and every release accept and offload correctly. That is the
"safe fallback is a silent performance regression" failure mode.

Provenance of the regression: 88b22b8
("Introduce ITableExpressionNode in the query tree", 2026-06-26) flipped the
JoinKind::Right descent target from the right expression to the left one. Every
other change that commit makes to this file is a mechanical getter rename, its
message describes only the refactor, and it changes no tests. c952d9d
("Right JOIN with parallel replicas") introduced the branch descending right,
and aa74846 added only the left node-type gate while keeping the right
descent. The flip is not an ancestor of any active release branch, so the
defect is master-only and needs no backport.

Mechanism: for JoinKind::Right, buildQueryTreeForShard materializes the LEFT
table expression into a temporary table (buildQueryTreeForShard.cpp:778-781),
so the side actually read with replicas is the right one, and
findTableForParallelReplicas descends right first. The decision half descended
the left expression and accepted because the left reads an eligible MergeTree;
rewriteJoinToGlobalJoin plus buildQueryTreeForShard then materialized exactly
that side, and the table lookup on the rewritten tree found nothing eligible
and threw at findParallelReplicasQuery.cpp:632.

The forward declaration of findTableForParallelReplicas is removed with the
guard: its remaining call sites are both below the definition.

Test: RIGHT SEMI and RIGHT ANTI reach the same branch (their strictness is not
RightAny), so they were bug arms too and are now covered. The parity arms pin
the shapes this deliberately keeps accepted, and each is refuted by one of the
rejected designs, so none of them is vacuous.
`RewriteJoinToGlobalJoinVisitor` decided globalization from the right table
expression for every join kind, and skipped the right child when recursing. For
a `JoinKind::Right` the side `buildQueryTreeForShard` materializes into a
temporary table is the left one, so with `parallel_replicas_prefer_local_join`
enabled (the default) an all-`MergeTree` right side kept the join local and left
a non-`MergeTree` left read unmaterialized in the tree sent to the replicas.
Every replica then read its own copy of it.

On master that was unreachable before the previous commit, because the decision
walk rejected a `RIGHT JOIN` whose right side has no eligible table and such a
query never reached `buildQueryTreeForShard`. Now that those queries are
offloaded, it is reachable there too. The active release branches already
descend right in that walk while still deciding locality from the right side,
so they are exposed to this independently of this change; no repro was measured
on a release binary, so no backport is requested.

Measured on three servers with separate data directories, so a `Log` or `Memory`
table can hold different content per replica: a
`(SELECT k FROM log_tbl) RIGHT JOIN (SELECT key FROM t_right)` returned rows
matching another replica's copy of `log_tbl` while losing the initiator's, in
1 of 10 runs at `parallel_replicas_prefer_local_join = 1`. Both consumers of
`rewriteJoinToGlobalJoin` pass `allow_global_join_for_right_table = true`, so
asking the same question `buildQueryTreeForShard` asks keeps them consistent.
`StorageDistributed` uses `rewriteJoinToGlobalJoinIfNeeded`, which is untouched.

The two new assertions in 04724 pin the structure rather than the row set: the
left read must reach the replicas as a `_data_*` temporary table, and the raw
table name must not appear in the `ReadFromRemoteParallelReplicas` step. A row
comparison is not usable here because the divergence needs the coordinator to
hand granules to more than one replica, which happens only sometimes. `Merge` is
the left engine because the stress runner rewrites `Log`, `TinyLog`,
`StripeLog` and `Memory` to `MergeTree`, which would turn both assertions into
controls.
…tion

CollectStoragesVisitor pushes a storage for every TableNode, but for a
TableFunctionNode only when the name is cluster, clusterAllReplicas, remote or
remoteSecure. Any other table function is therefore left out of the collected
vector, and a side that holds nothing else collects zero storages, which the
all-MergeTree loop reads as true because it is vacuously true of an empty
vector.

With parallel_replicas_prefer_local_join at its default the join then stays
local, buildQueryTreeForShard only materializes sides of joins whose locality
is Global, and the raw table-function read is shipped to every replica. For a
table function that can return different rows per node that is a wrong-results
path. The previous commit made a RIGHT JOIN over such a left side offloadable
in the first place, so it also has to keep it safe.

The predicate now reports the materialized side as unsafe to leave local when
its subtree contains a table function the visitor did not collect. It is scoped
to the RIGHT arm: for the other join kinds the same vacuity is pre-existing
behaviour of plans that already ship, and widening it here would change them.
The four collected names keep behaving exactly as before, so issue ClickHouse#77990 does
not regress.

Measured over the 42-shape EXPLAIN corpus, three verdicts change and all three
are RIGHT JOIN shapes whose left side reads a table function; the LEFT, INNER,
CROSS, three-way, UNION and single-table sections are byte-identical. One of
the three was already shipping a raw table-function read before this PR.

The new test arms pin query_plan_join_swap_table because their oracle asserts
GLOBAL ALL RIGHT JOIN, which encodes orientation, and the test runner
randomizes that setting.

Co-Authored-By: Claude Fable 5 <[email protected]>
`rewriteJoinToGlobalJoin` asks whether the side `buildQueryTreeForShard`
will materialize may instead be left for each replica to read on its
own. For a `RIGHT JOIN` that side is the left one, and the candidate
walk in `getSupportingParallelReplicasQueries` admits it by node type
alone (`{TABLE, QUERY, UNION}`), so no eligibility predicate is ever
evaluated against its storage. Answering with `isMergeTree()` alone was
therefore too weak: at the default
`parallel_replicas_for_non_replicated_merge_tree = 0` and
`parallel_replicas_prefer_local_join = 1`, a plain non-replicated
`MergeTree` left side reported "may stay local", the join kept
`JoinLocality::Local`, the side was never materialized, and its raw read
was serialized into the query sent to every replica. If the
non-replicated tables differ between replicas, which is the point of
"non-replicated", the result is wrong.

Ask the question the rest of the subsystem asks instead:
`isTableNodeEligibleForParallelReplicas`, which additionally requires
replication (or the opt-in setting) and rejects `FINAL`.
`allowParallelReplicasForJoinTree` (`PlannerJoinTree.cpp:1454-1458`)
already requires exactly this of a `RIGHT JOIN`'s left storage, via
`parallelReplicasEnabledForStorage`, which tests the same two
conjuncts.

`CollectStoragesVisitor` now retains a `TableNode *` alongside each
collected storage, because the predicate needs the node for its
table-expression modifiers. A collected table function has no
`TableNode`, so it keeps the `isMergeTree()` treatment and issue ClickHouse#77990
is unaffected.

Scoped to `JoinKind::Right`, like the neighbouring
`has_uncollected_table_function` conjunct. `LEFT` and `INNER` are
measured to keep a local join over an ineligible materialized side on
unmodified master too, so tightening them is a separate, pre-existing
question and not this change; doing it here would alter plans this
change has no reason to touch.

The predicate is strictly stronger on every reachable input, never
looser, even though it also accepts a `StorageDummy` whose
`isMergeTree()` is false: instrumenting the loop shows no dummy storage
ever reaches it, because `replaceTablesWithDummyTables` builds that tree
purely as a local probe inside `findQueryForParallelReplicas` and it
never escapes, while `rewriteJoinToGlobalJoin` runs on the real tree.
Its `FINAL` conjunct cannot fire from this call site either, since
`Planner` disables parallel replicas on any `FINAL` modifier before the
rewrite runs; it is retained because the predicate is shared, not
because this site reaches it.

Four assertions added to the regression test, pinning
`parallel_replicas_for_non_replicated_merge_tree = 0` per query so the
file-level `SET` does not neuter them. The right side has to be a
`ReplicatedMergeTree` for the shape to be offloaded at that default at
all, so one is used. Included is a replicated-left control asserting the
local join is still kept, so the change cannot degenerate into a blanket
globalization.

Suppressing only the new predicate with a runtime-false guard reddens
exactly the two new structural assertions and nothing else,
byte-identically to the pre-change tree. The 42-cell `EXPLAIN` corpus is
unchanged against that tree and differs from pre-PR master in 17 cells,
every one a `RIGHT JOIN` shape.

The `parallel_replicas_prefer_local_join` description said the decision
looks at the right JOIN part, which stopped being true once the visitor
started inspecting the materialized side; it now names that side and its
stronger requirement. Text only, so no `SettingsChangesHistory.cpp`
entry.
The replicated-left arm asserting `count() = 0` for
`%GLOBAL ALL RIGHT JOIN%` is the file's only absence assertion without a
positive companion on the same shape. Its job is to show the eligibility
tightening is not a blanket globalization, but `0` is equally what a
query returns when it never entered parallel-replicas planning, or when
it failed for an unrelated reason, and nothing in the file required that
shape to have been offloaded at all. A later change that quietly stopped
offloading it would leave the arm green and the claim unevidenced.

Add the missing half immediately before it, over a byte-identical inner
query so the two describe one cell. `RIGHT JOIN` is a substring of
`GLOBAL ALL RIGHT JOIN`, so neither predicate alone separates a local
join from a global one: the pair is the discriminator, one arm saying
the join reached the replicas and the other that it was not globalized.

Both halves are load-bearing. Suppressing the offload for every
`RIGHT JOIN` turns the new arm from `1` to `0`, while globalizing only a
materialized side that supports replication turns the existing control
from `0` to `1` and moves no other reference line.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review - 7 fix rounds, 1 replan; final round clean

I review my own changes with an independent model before asking for a human review. This diff went
through seven implementation rounds and one replan; the findings below are the ones that shaped it,
recorded so the eventual diff is readable. The final round found nothing in the code.

❌ Blocker - the first version fixed the symptom on the wrong side. An early revision required
both sides of a RIGHT JOIN to be eligible, which is a 56-line predicate that also rejects
shapes that work today. Reverted to the one-line descent fix once it was measured that all five
active release branches already descend the right expression, so the one-liner restores an existing
form rather than inventing one.

❌ Blocker - an uncollected table function read as "all MergeTree" on the materialized side.
CollectStoragesVisitor records a storage for every table node but, among table functions, only
cluster, clusterAllReplicas, remote and remoteSecure. Any other one contributes nothing, so
the loop returned true over an empty list. On the left side of a RIGHT JOIN at the default
parallel_replicas_prefer_local_join = 1 that keeps the join local, nothing materializes the left
side, and the raw read is shipped to every replica. Measured as introduced by this change rather
than pre-existing: the offloaded plan for (table function) RIGHT JOIN (table) contains the raw
read on the fixed binary and does not exist at all on unmodified master. Fixed, with the
system.one contrast case (a table node, collected, correctly gets a temporary table) as the
control.

❌ Blocker - MergeTree is not the right question on that side. Being a MergeTree is weaker
than being eligible for parallel replicas, and nothing else checks eligibility on a RIGHT JOIN's
materialized side, since the candidate walk admits it by node type alone. The predicate now asks
the subsystem's own question, which rejects a non-replicated MergeTree at the default
parallel_replicas_for_non_replicated_merge_tree = 0. Scoped to RIGHT by measurement: LEFT and
INNER already keep a local join over an ineligible materialized side on unmodified master, so
that is a pre-existing question this PR does not own.

⚠️ Major - an absence assertion with no positive companion. The arm proving the tightening is
not a blanket globalization asserted count() = 0 for GLOBAL ALL RIGHT JOIN on an eligible left
side. But 0 is also what a query returns when it never entered parallel-replicas planning, and it
was the file's only absence arm without a positive on the same shape. A companion asserting the
join reached the replicas at all was added over a byte-identical inner query. RIGHT JOIN is a
substring of GLOBAL ALL RIGHT JOIN, so neither predicate alone separates a local join from a
global one: the pair is the discriminator, and two mutants confirm it, one reddening only the new
arm and one only the existing control.

⚠️ Major - an assertion depended on a randomized setting. The assertions keying on
GLOBAL ALL RIGHT JOIN encode join orientation, and the runner randomizes
query_plan_join_swap_table. Pinned. Measured afterwards that they in fact pass at all three
values, so the pin is insurance rather than a crutch.

⚠️ Major - a validation claim outran its measurement. The description said the test survives
"30 concurrent runs", but that figure came from an earlier round whose test file had four fewer
arms and no ReplicatedMergeTree at all. Re-measured on the shipped file: 60 of 60 runs across two
independent batches, with per-test times summing to about five times wall elapsed, which is the
check that distinguishes a real concurrency run from a serialised one.

💡 Findings of my own that were withdrawn as wrong rather than acted on: that the randomized
50-run validation predated the assertions it was meant to cover (it did not); that the test should
carry a zookeeper tag (the tag only gates cloud coverage, so it would lose coverage for no
correctness gain); and that a FINAL arm was missing (parallel replicas are already disabled on
any FINAL modifier before this code runs, so such an arm would be a control, not a witness).

Out-of-scope observations noted and deliberately not chased: the pre-existing LEFT/INNER gap
above, and a left-side eligibility gate in the planner that is stricter than it now needs to be.
Neither has a user-reachable consequence I could demonstrate.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, two of them. (1) The logical error, 100% on unmodified master: SELECT * FROM (SELECT key FROM t) AS l RIGHT JOIN (SELECT number AS key FROM numbers(10)) AS r ON l.key = r.key with enable_analyzer=1, enable_parallel_replicas=1, max_parallel_replicas=2, cluster_for_parallel_replicas=test_cluster_one_shard_three_replicas_localhost, parallel_replicas_for_non_replicated_merge_tree=1, parallel_replicas_prefer_local_join=0. The oracle is the server-log occurrence delta of the error string, not the client return code: a debug server aborts on the logical error, so any later arm hits a dead server and returns 210/32/23, which reads as "no error". (2) The wrong results the first fix would otherwise have introduced, deterministic in EXPLAIN: with a Merge-engine or table-function left side at parallel_replicas_prefer_local_join=1, the raw left read appears in the ReadFromRemoteParallelReplicas step instead of a _data_* temporary table.
b Root cause explained? Yes, two coupled halves. (1) For JoinKind::Right, buildQueryTreeForShard materializes the LEFT table expression into a temporary table (buildQueryTreeForShard.cpp:772-781), so the side read with replicas is the right one, and findTableForParallelReplicas descends right first. getSupportingParallelReplicasQueries descended the LEFT expression, so a query was accepted for a side the rewrite then replaced; the lookup ran on the rewritten tree, got nullptr, and threw at findParallelReplicasQuery.cpp:632. (2) RewriteJoinToGlobalJoinVisitor decided globalization from the RIGHT expression for every join kind, so once those queries became offloadable, a RIGHT JOIN with an all-MergeTree right side stayed local and left a non-MergeTree LEFT read unmaterialized in the tree sent to every replica. CollectStoragesVisitor additionally collects no storage for a table function outside cluster/clusterAllReplicas/remote/remoteSecure (:906), so such a left side collected zero storages and the all-MergeTree loop returned true vacuously.
c Fix matches root cause? Yes, one change per half, each at the site of the asymmetry. The decision walk descends the right expression again, restoring the target 88b22b8fb66c115 changed while renaming getters. RewriteJoinToGlobalJoinVisitor asks which side buildQueryTreeForShard will materialize instead of assuming the right one; for a RIGHT JOIN it asks the subsystem's own question about that side, isTableNodeEligibleForParallelReplicas (findParallelReplicasQuery.cpp:45-60), rather than the weaker isMergeTree(), and reports an uncollected table function there as unsafe rather than letting an empty storage vector read as all-MergeTree. No widened bound, no no-random-* tag, no reduced dataset, no defensive check.
d Test intent preserved / new tests added? New stateless test, 29 labelled assertions over a 156-line reference: the bug shapes, the offload-preserved shapes, correctness rows, and six materialization-safety assertions for the globalization half. Those six cover a Merge left side, a table-function left side, and a non-replicated MergeTree left side at the DEFAULT parallel_replicas_for_non_replicated_merge_tree = 0, each asserted twice: once that the left side reaches the replicas as a _data_* temporary, and once that its raw name is ABSENT from ReadFromRemoteParallelReplicas. Two further arms are a PAIR on a replicated (eligible) left side, whose inner query text is byte-identical so they describe one cell: the first asserts the JOIN still reached the replicas at all, the second that it was not globalized. Both are needed, because RIGHT JOIN is a substring of GLOBAL ALL RIGHT JOIN, so neither predicate alone separates a local join from a global one, and an absence assertion is otherwise satisfied by a query that never entered parallel-replicas planning. Untagged and parallel-safe (60 of 60 runs pass across 6 concurrent copies × 5 runs, twice; the copies genuinely overlap, per-test times summing to ~5× wall elapsed, and each run gets its own {database}-scoped ZooKeeper path, measured as exactly 30 new /parallel_replicas/* parents per 30-run batch). The EXPLAIN arms pin query_plan_join_swap_table because their oracle asserts GLOBAL ALL RIGHT JOIN, which encodes orientation, and the runner randomizes that setting; measured, the arms in fact pass at auto, false and true.
e Both directions demonstrated? Yes, per change. On unmodified master (Build ID 1526a908c18d4b08) the test FAILS and the error string appears twice in the server log; with the fix (690396a265420779) it passes with zero occurrences. Against a build carrying only the first hunk (740457f02b2587c1), exactly the hunk-2 structural assertions redden and nothing else does. Against a build carrying both hunks but not the table-function conjunct (f9924ff1542b9f4e), exactly the two table-function assertions redden. Against a build carrying everything but the eligibility tightening (runtime-false mutant, 03b0995c079570ae), exactly the two non-replicated-MergeTree assertions redden and nothing else does, byte-identically to the pre-tightening tree (1f4ff8a0c965e7c6). The replicated-left pair is pinned from both sides by two further runtime-false mutants: suppressing the offload for every RIGHT JOIN (373e88239a5e795b) turns the "still offloaded" arm from 1 to 0, and globalizing only a materialized side that supports replication (6d733493370dfee6) turns the "local join is kept" control from 0 to 1 and moves nothing else at all. Each assertion group, and each half of that pair, is therefore independently load-bearing.
f Fix is general across code paths? Yes. RIGHT SEMI and RIGHT ANTI also reach the decision branch, since their strictness is not RightAny, and were affected too; both have assertions. Both consumers of rewriteJoinToGlobalJoin pass allow_global_join_for_right_table = true (findParallelReplicasQuery.cpp:620-621, ClusterProxy/executeQuery.cpp:1045-1046), so the same question is correct for both; StorageDistributed uses the separate rewriteJoinToGlobalJoinIfNeeded and is untouched. needChildVisit is changed together with the globality decision so the pass does not visit the materialized side and skip the shipped one. The eligibility tightening is scoped to JoinKind::Right because it is measured that LEFT and INNER already keep a local join over an ineligible materialized side on unmodified master, so tightening them is a separate, pre-existing question this PR does not own. An EXPLAIN corpus over 21 shapes at both parallel_replicas_prefer_local_join values (42 plans) changes 17 verdicts, every one a RIGHT JOIN shape, and leaves LEFT, INNER, CROSS, 3-way, UNION and single-table plans byte-identical. The 114 parallel_replicas tests give an identical deterministic pass/fail set on both binaries, bucketed by failure reason with zero timeouts.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. UInt64, Nullable(UInt64), String, Nullable(String), LowCardinality(String) and LowCardinality(Nullable(String)) keys with 0-, 1- and 2-row inputs: 9 arms, all throwing on master and all correct with the fix, at both parallel_replicas_prefer_local_join values. Both changed sites are node-pointer selections that key types cannot reach, so this is confirmation rather than discovery. The globalization half was additionally measured against Log, Memory, Merge, numbers, generateRandom, cluster and remote left sides; cluster and remote keep their pre-existing behaviour, so issue #77990 does not regress.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or re-defaulted, so no SettingsChangesHistory.cpp entry is needed (only the parallel_replicas_prefer_local_join description text is corrected, which is not a behaviour change), and no serialization or format change. The user-visible changes are that the affected shape stops throwing and that a RIGHT JOIN whose left side each replica cannot safely read on its own now materializes that side instead of reading it on each replica. The logical error is master-only. The second change's hazard is pre-existing on the active release branches, where the candidate walk already descends right; no backport is requested here.
i Invariants and contracts preserved? Yes, and the second change exists because the first one broke one. The invariant is that both the eligibility decision and the globalization decision must look at the side that survives buildQueryTreeForShard, and must judge it by the same eligibility predicate the rest of the parallel-replicas subsystem uses. The dummy-tree second pass still agrees with the real-tree pass: measured by instrumenting the predicate loop, a StorageDummy never reaches it, because replaceTablesWithDummyTables (findParallelReplicasQuery.cpp:221) builds that tree purely as a local probe inside findQueryForParallelReplicas and it never escapes, while rewriteJoinToGlobalJoin runs on the real tree. The predicate is therefore strictly stronger on every reachable input, never looser. Its FINAL conjunct cannot fire from this call site, since Planner.cpp:2292-2313 disables parallel replicas on any FINAL modifier before the rewrite runs; it is retained because the predicate is shared, not because this site reaches it. No lifetime, resource or concurrency surface: node-pointer selections and a parallel TableNode * vector inside a single-threaded planner walk.

Session id: cron:clickhouse-review-slot-51:20260805-140302

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @yakov-olkhovskiy, could you review this? For a RIGHT JOIN it is the left side that buildQueryTreeForShard materializes, so the candidate walk was accepting a query for the side the rewrite then replaced and the table lookup threw a logical error; the second hunk keeps that offload correct by deciding globalization from the materialized side and judging it by the subsystem's own eligibility predicate rather than isMergeTree.

@nickitat nickitat added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [801d300]

Summary: ✅


AI Review

Summary

The PR fixes the RIGHT JOIN candidate descent in the classic parallel-replicas path and closes several materialized-side safety gaps, but one new correctness regression remains and one earlier plan regression is still unresolved. In particular, the new materialized-side eligibility check now consults the enclosing query context, so a left subquery can no longer locally disable wrapper-table parallelization and a RIGHT JOIN can again leave a non-replicated underlying table to be read independently on each replica.

Findings

❌ Blockers

  • [src/Storages/buildQueryTreeForShard.cpp:1121] The new materialized-side check asks canUseTableForParallelReplicas with the outer query context, so a left subquery's own SETTINGS clause can no longer turn off parallel_replicas_allow_view_over_mergetree or parallel_replicas_allow_materialized_views. For a View or MaterializedView over a non-replicated MergeTree, an outer opt-in now unwraps the wrapper, keeps the RIGHT JOIN local, and lets every replica read its own copy even when the subquery explicitly disabled that path. Before this PR the raw wrapper storage failed the old isMergeTree() test here and forced GLOBAL, so this is a new wrong-results path.
    Suggested fix: evaluate eligibility with the table node's own subquery context, or thread per-subquery settings through this walk before calling canUseTableForParallelReplicas.

⚠️ Majors

  • [src/Storages/buildQueryTreeForShard.cpp:1075] A local IN or JOIN over a multi-shard Distributed table on the materialized side still forces the outer RIGHT JOIN to GLOBAL before buildQueryTreeForShard can auto-rewrite that nested operator to GLOBAL under prefer_global_in_and_join = 1 or distributed_product_mode = 'global'. Rows stay correct, but this is still a plan regression versus master for those shapes.
    Suggested fix: base this scan on the post-rewrite materialized subtree, or mirror the same auto-GLOBAL predicate here.
Tests
  • ⚠️ Add a focused stateless test where the left side of a RIGHT JOIN is a subquery over View or MaterializedView that sets parallel_replicas_allow_view_over_mergetree = 0 or parallel_replicas_allow_materialized_views = 0, while the outer query enables it and the underlying table is a non-replicated MergeTree. That is the smallest regression test for the new context-leak path.
Final Verdict

⚠️ One new blocker and one previously reported major remain; this is not ready to merge yet.

LLVM Coverage Report

Measured on commit 801d300.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 75/75 (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 Aug 5, 2026
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — fabe4a5

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

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan, s3) / Logical error: '(isConst() || isSparse() || isReplicated() || ...) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' (STID 2508-2e0c) trunk — a mixed JOIN ON condition evaluated over mismatched column types; stack is HashJoinMethodsImpl.h:807 buildAdditionalFilter -> IColumn::assertTypeEquality #113534 (external, open)
Integration tests (amd_msan, 4/8) / test_tcp_handler_connection_limits/test.py::test_query_count_limit flaky trunk — Expected exactly 1 connection closure, got 2 (assert 2 == (0 + 1); the baseline read is 0) a fix task is moved to pending (investigating at full effort — fixing-PR link to follow here)

CI is otherwise finished on this head: 174 check-runs, 0 incomplete, Config Workflow and
Finish Workflow both success, 155 success / 17 skipped.

Neither failure is caused by this PR: the diff touches Settings.cpp,
findParallelReplicasQuery.cpp and buildQueryTreeForShard.cpp plus its own new stateless test —
no hash-join code and no TCP-handler code.

A note on the first line, since the owner changed very recently. My own #107957 previously carried
this signature and was closed a few hours ago as superseded by #113534, which fixes the same abort
at the planning layer rather than reconciling the nullability mismatch inside
buildAdditionalFilter. #113534 is therefore the live owner. My merged #112831 is deliberately
not named here: it widened how often valid queries reach buildAdditionalFilter, but the abort
predates it, so it is not the fix and must not be read as needing a revert.

Build (arm_release) / Post Hooks is check-level success and is not a failure.

Session id: cron:our-pr-ci-monitor:20260806-020000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into ClickHouse:master with commit cc7a884 Sep 13, 2026
344 of 345 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 15, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 15, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 15, 2026
Backport #113515 to 26.8: Fix logical error for RIGHT JOIN with parallel replicas
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Sep 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Partial owner for the Inconsistent KeyCondition behavior row on my CI finish ledger here (STID 5182-6d6b, 2026-09-03): #121089. To be precise about what it covers, it narrows the nullable-key exactness safeguard that reached master on 2026-09-05, about 40 hours after this occurrence, so it owns only the post-2026-09-05 set-membership shape of that assert and does not explain the failure seen here.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 22, 2026
ConvertImpl's if-constexpr chain reaches Enum8/Enum16 as genuine FromDataTypes
(callOnTypeIndex.h maps TypeIndex::Enum8 to DataTypeEnum<Int8>), but the two
special-case branch lists for a date/time target enumerate the concrete integer
and float types and never name the Enums, and IsDataTypeNumber<DataTypeEnum<T>>
is unspecialised, so the IsDataTypeNumber-gated branches miss them too. An enum
source therefore fell through to the generic numeric path and was converted by
a plain static_cast, which is modular rather than saturating:
static_cast<UInt32>(Int8(-1)) is 4294967295.

ToDateTimeMonotonicity meanwhile accepts any source for which
isValueRepresentedByNumber() holds, true for Enum, and returns always-monotonic,
so KeyCondition::applyMonotonicFunctionsChainToRange mapped the key range
through the wrapping conversion with no guard against left > right. A range
spanning zero came out inverted: granules holding matching rows were discarded,
and MergeTreeSetIndex::checkInRange tripped its own begin > end consistency
check, which throws LOGICAL_ERROR under ifndef NDEBUG and returns {true, true}
in release. So the debug abort is the CI signature and the wrong query results
are the release-visible face of one defect.

Adding the two types to the two branch lists makes an enum equivalent to the
integer it is stored as at this seam: same FieldType, same ColumnVector, same
transform instantiation, and the same non-strict Monotonicity the struct already
returns for Int8/Int16, which is right for a saturating many-to-one map. No
monotonicity struct is touched and no new monotonicity semantics are introduced.
This is the design ClickHouse#118717 used for (U)Int128/(U)Int256 against the same defect,
and it restores the invariant ClickHouse#117394 states for numeric arguments.

Measured on 26.8.11.7 (LTS), each enum beside the integer it is stored as:

    toDateTime(Enum8('neg' = -1))       2106-02-07 06:28:15   vs 1970-01-01 00:00:00
    toDate(Enum8('neg' = -1))           2149-06-06            vs 1970-01-01
    toDateTime(Enum16('lo' = -32768))   2106-02-06 21:22:08   vs 1970-01-01 00:00:00
    toDate(Enum16('lo' = -32768))       2059-09-19            vs 1970-01-01

Over a MergeTree table keyed by Enum16('neg' = -1, 'zero' = 0) holding both
members, SELECT count() FROM t WHERE toDateTime(x) = toDateTime(0) returned 0
where the same predicate counted without the index returned 1, and the IN form
aborted a debug build in checkInRange. In-range enum values are unaffected: every
positive member is inside both result ranges.

Four other branch lists name Int8/Int16 and still omit the Enums, and are
deliberately not mirrored here because no carrier was measured behind them:
to Date32 (static_cast<Int32> of Int8/Int16 is exact over the whole enum range),
to Time (Time caps at plus or minus 3599999 seconds, so the whole enum range is
inside it), and to DateTime64 and Time64 (an enum source is rejected with
Code: 70, so the conversion is unreachable).

date_time_overflow_behavior has no effect for an enum source before or after
this change: the GENERATE_OVERFLOW_MODE_CASE switch sits inside a predicate that
is false for Enum, so ConvertImpl is always instantiated with the default Ignore.
Measured under ignore, saturate and throw, an enum agrees with Int8 in all three.
That is the pre-existing family-wide gap ClickHouse#118717's own merged test records, and
it is out of scope here.

05076_datetime_conversion_monotonicity_static_cast is deleted rather than
rebaselined: its wide-integer arms encode the pre-ClickHouse#118717 wrapping semantics, so
four of its reference values now pin behaviour master deliberately changed. The
new 05238_enum_to_datetime_overflow covers the conversion image beside the
integer, in-range controls, the CAST and wrapper forms, the overflow modes, and
the primary-key arms including the one that reproduces the assertion.

Related: ClickHouse#113515
Related: ClickHouse#116946
Related: ClickHouse#118717

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

7 participants