Repository navigation
Fix logical error for RIGHT JOIN with parallel replicas - #113515
alexey-milovidov merged 28 commits into
Conversation
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.
Internal second-model review - 7 fix rounds, 1 replan; final round cleanI review my own changes with an independent model before asking for a human review. This diff went ❌ Blocker - the first version fixed the symptom on the wrong side. An early revision required ❌ Blocker - an uncollected table function read as "all MergeTree" on the materialized side. ❌ Blocker -
💡 Findings of my own that were withdrawn as wrong rather than acted on: that the randomized Out-of-scope observations noted and deliberately not chased: the pre-existing |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-51:20260805-140302 |
|
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. |
|
Workflow [PR], commit [801d300] Summary: ✅
AI ReviewSummaryThe PR fixes the Findings❌ Blockers
Tests
Final VerdictLLVM Coverage ReportMeasured on commit 801d300.
Changed lines: Changed C/C++ lines covered: 75/75 (100.00%) · Uncovered code |
CI finish ledger — fabe4a5Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
CI is otherwise finished on this head: 174 check-runs, 0 incomplete, Neither failure is caused by this PR: the diff touches A note on the first line, since the owner changed very recently. My own #107957 previously carried
Session id: cron:our-pr-ci-monitor:20260806-020000 |
…-pr-right-join-descent
cc7a884
Backport #113515 to 26.8: Fix logical error for RIGHT JOIN with parallel replicas
…with parallel replicas
|
Partial owner for the |
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]>
Closes: #113292
Closes: #119408
Related: #108645
Changelog category (leave one):
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 replicasfor aRIGHT JOINwhose right side has no table eligible for parallel replicas, and made aRIGHT JOINmaterialize a left side that is not aMergeTreeinstead 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::Rightthe side read with replicas is the right one, becausebuildQueryTreeForShardmaterializes the left table expression.getSupportingParallelReplicasQueriesdescended 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/ANTItoo), then corrects three places that had the materialized side wrong:rewriteJoinToGlobalJointook locality from the right side for every kind; aRIGHT JOIN's materialized side must now be eligible for parallel replicas, not merelyMergeTree.View/MaterializedViewlost its local join; the wrapper is resolved first.GLOBAL JOIN's materialized side, aGLOBAL IN).The last two came from
clickhouse-gh[bot]. No backport requested: the logical error is master-only,26.2to26.7still 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:
IN/JOINover a multi-shardDistributedis auto-globalized only after this locality decision runs, so it still counts here and costs a local join master keeps. Reaching it needsprefer_global_in_and_join = 1ordistributed_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.CollectStoragesVisitordoes not collect leavesstoragesempty, which reads as all-MergeTree. This PR rejects that on aRIGHT JOIN's materialized side; a nested join of another kind still admits it, exactly as master does for every kind.parallel_replicas_for_non_replicated_merge_treeorparallel_replicas_allow_view_over_mergetreeoff 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
26.8.5.16