Skip to content

Fix wrong results for a join tree with an unsafe non-leftmost join - #112317

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-pr-nway-join-non-leftmost-strictness
Sep 13, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-pr-nway-join-non-leftmost-strictness

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #109414 (comment)

Found by 04490_any_join_constant_condition_reorder in Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel): CI report.

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

Fix wrong results with enable_parallel_replicas = 1 when a join tree contains a join other than the leftmost one that cannot be applied independently per replica: a strictness other than ALL outside a LEFT join, for example t1 INNER JOIN t2 ON t1.c = t2.c ANY INNER JOIN t3 ON 1, which returned the row once per replica instead of once; a FULL join, which emitted every row twice; or a PASTE join, which pairs rows by position. Parallel replicas are now disabled for such a join tree, as they already are for the equivalent two-table join.

Description

Symptom. SELECT * FROM t1 INNER JOIN t2 ON t1.c = t2.c ANY INNER JOIN t3 ON 1 returns 3 rows instead of 1 on a three-replica cluster: measured 60/60 runs with parallel_replicas_local_plan = 0 and 60/60 correct with it on, which is why CI sees it intermittently.

Root cause. Parallel-replicas eligibility is decided by allowParallelReplicasForJoinTree, evaluated only on the first join node of the post-order table-expression stack. For (t1 ALL INNER JOIN t2) ANY INNER JOIN t3 that node is the Inner/All join, so the outer ANY join is never examined. The initiator then ships the whole join tree to every replica while only the leftmost leaf's reads are coordinated, so each replica applies ANY to its own slice and the initiator concatenates the results.

Fix. should_disable_parallel_replicas already walks the whole stack and already vetoes n-way trees on other grounds (FULL/GLOBAL/CROSS, a misplaced RIGHT); it never looked at strictness. It now also vetoes a non-leftmost join whose strictness is not ALL outside a LEFT kind (a whitelist, so a future JoinStrictness fails closed), or whose kind is PASTE (pairs rows by position) or FULL (emits unmatched right rows, which each replica would decide from its own slice of the left side). An ARRAY JOIN also occupies the leftmost slot, so the veto is not gated on joins_count, which that node does not increment. The change only ever removes queries from the parallel-replicas path.

Force mode (enable_parallel_replicas = 2) still downgrades silently at this call site, as it has for its four other checks since 2024.

Measurements and what the new test pins

Three-replica cluster (ReplicatedMergeTree, cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost'), row counts against a parallel-replicas-off oracle on the same fixture, pristine master vs this branch:

shape local_plan master this PR
INNER ... ANY INNER ON 1 (oracle 1) 0 3 rows in 60/60 1 row in 60/60
ARRAY JOIN ... ANY INNER ON 1 (oracle 1) 0 3 rows in 60/60 1 row in 60/60
ARRAY JOIN ... FULL JOIN (oracle 5) 0 15 rows in 60/60 5 rows in 60/60
the three shapes above 1 correct in 60/60 correct in 60/60
3-way ALL LEFT (oracle 2, control) 0 and 1 correct in 20/20, plan keeps parallel replicas same

parallel_replicas_local_plan = 1 keeps all three shapes correct on both binaries, and the runner randomizes that setting, which is why CI sees the failure intermittently.

The test asserts the decision rather than the row count: whether the plan contains a ReadFromRemoteParallelReplicas step. Of its 20 assertions, ten flip on a master binary (the three ANY INNER shapes, ARRAY JOIN ... FULL, the four ARRAY JOIN ... RIGHT strictness shapes, ASOF INNER, PASTE); the other ten are guards that read the same value on both. Each term is pinned on its own: reverting only the FULL term flips exactly array join then full, only PASTE exactly paste non-leftmost, deleting && join_kind != JoinKind::Left exactly the two LEFT lines.

ARRAY JOIN ... ALL RIGHT JOIN is deliberately left eligible: vetoing it would disable parallel replicas for 03452_array_join_global_right_join_parallel_replicas, whose purpose is to exercise that path. That residual is master's behaviour; its row counts match a parallel-replicas-off oracle in 60/60 runs on both binaries.

No setting default changes, so no SettingsChangesHistory.cpp entry. No serialization or format change.


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

Version info

  • Merged into: 26.9.1.1336 (included in 26.9 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

This change went through 11 internal review rounds before being opened. Every finding below
was adjudicated against the code; verdicts and the evidence for each are recorded.

Blockers found and fixed (❌ -> fixed):

# Finding Resolution
1 An ARRAY JOIN before a single unsafe ordinary join bypassed the veto entirely, because the ARRAY_JOIN branch of the loop continues before ++joins_count, so no joins_count-gated rule can fire for t1 ARRAY JOIN [1, 2] AS a ANY INNER JOIN t3 ON 1. Fixed: the veto is not gated on joins_count, and ARRAY_JOIN counts as occupying the leftmost join-tree slot. That shape returned 2 rows instead of 1 in 19 / 60 runs before, 0 / 60 after.
2 An ARRAY JOIN followed by a FULL JOIN stayed eligible: a FULL join carries ALL strictness, so a strictness-only test cannot see it, and the pre-existing FULL/GLOBAL/CROSS rule is unreachable for that tree shape for the same joins_count reason. Each replica would decide which right rows are unmatched from its own slice of the left side. Fixed by a kind-level term. That shape emitted every row twice in 8 / 60 runs before, 0 / 60 after; a row-level control now asserts the unmatched right row is emitted exactly once.
3 A non-leftmost PASTE JOIN also bypassed the veto: it pairs rows by position, yet reaches the planner carrying ALL strictness, and isCrossOrComma excludes Paste. Fixed by a second kind-level term. On master that shape did not merely duplicate rows -- 15 / 40 runs failed outright with Code: 62 ... You must not specify ANY or ALL for PASTE JOIN, raised by a remote replica re-parsing the shipped fragment; 40 / 40 clean after.

Majors found and fixed (⚠️ -> fixed):

  • An earlier revision vetoed RIGHT by kind. Measured, that would have disabled parallel replicas for
    03452_array_join_global_right_join_parallel_replicas, whose entire purpose is to exercise the
    ARRAY_JOIN branch reachable only from the parallel-replicas callers -- the test would have kept
    passing while covering nothing. The veto was narrowed to strictness, and ARRAY JOIN ... ALL RIGHT
    is now a disclosed residual pinned by its own assertion in both directions.
  • The RIGHT strictness matrix was incomplete in two successive revisions: ANTI RIGHT is accepted by
    the parser, and ANY RIGHT under any_join_distinct_right_table_keys = 1 becomes RightAny rather
    than being rewritten to SEMI LEFT (that rewrite fires only for INNER). Both are reachable and
    both are vetoed; each now has its own assertion, so no single strictness can be dropped unnoticed.
  • The test inherited join_algorithm and join_use_nulls, which the stress runner injects as
    per-thread client options -- partial_merge/grace_hash make the ASOF assertion throw, and
    join_use_nulls = 1 turns the FULL join's default-filled cells into NULL. Both are now pinned.
  • Two counts in the description were stale (18 assertions / 8 flipping). Re-derived by script from the
    test's own output against a pristine binary: 20 assertions, 10 flipping.
  • Two mechanism claims in the description were wrong and were corrected against the source: the
    ConstantJoin line citations for INNER ANY and RIGHT ANY had been swapped, and an earlier
    revision asserted ANY INNER ... ON 1 emits one match per left row (it emits one pair in total).

Disagreed, with evidence (⚠️ -> not changed):

  • It was argued that the veto should be restricted to the whole-query shipping mode, because with
    parallel_replicas_plan_based = 1 a join stays above the split step and executes on the
    coordinator, so this failure mechanism would not apply. The mechanism is correct and was
    confirmed
    -- the veto clears the enable_parallel_replicas alias, which reaches
    QueryPlanOptimizationSettings and short-circuits applyParallelReplicas, so the plan-based mode
    is disabled too. It is not adopted here for three reasons. The lever being narrowed is shared by
    all four disjuncts, three of which are pre-existing and identically mode-blind on master, so
    gating it changes master's own behaviour for FULL/GLOBAL/CROSS and misplaced-RIGHT trees:
    a separate concern in the same function. It would also be behaviour-widening on an experimental
    path with no verification available -- that setting defaults false, no runner randomizes it, and
    none of the in-tree tests that enable it contains a JOIN, so plan-based-mode-with-a-join is
    unexercised in tree. And this change's contract is that it strictly reduces the set of queries
    using parallel replicas, so it cannot alter a result that was already correct; re-enabling an
    unverified path is the opposite direction. Tracked separately instead.

Noted, not blocking (💡):

  • ASOF INNER is vetoed conservatively: it is not ALL, so the whitelist rejects it, even though it
    was not observed to duplicate. It has its own assertion so the strictness term cannot silently
    narrow to == Any.
  • The ARRAY JOIN ... ALL RIGHT JOIN residual and the joins_count-vs-ARRAY_JOIN gap in the
    pre-existing FULL/GLOBAL/CROSS disjunct are master's own behaviour, deliberately unchanged
    here, disclosed in the description and tracked separately.
  • The Code: 62 PASTE formatter/parser asymmetry is reachable through the other query shippers
    (StorageDistributed, IStorageCluster) and is a parser/formatter fix in a different subsystem;
    issue Unexpected syntax error when using paste join with IcebergS3Cluster #88957 reports it for icebergS3Cluster. Left to a separate PR.

Session id: cron:clickhouse-review-slot-48:20260728-155200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT countIf(explain ILIKE '%ReadFromRemoteParallelReplicas%') FROM (EXPLAIN SELECT * FROM t1 INNER JOIN t2 ON t1.c = t2.c ANY INNER JOIN t3 ON 1 ORDER BY ALL) with SET explain_query_plan_default = 'legacy' returns 1 on master, 0 with the fix, on every run; the same oracle over ... PASTE JOIN t3 likewise returns 1 on master, 0 with the fix, and over t1 ARRAY JOIN [1, 2] AS a FULL JOIN t2 ON t1.c = t2.c it returns 1 on master, 0 with the fix. The row-level forms are nondeterministic but frequent: the original three-way shape returned a duplicated row in 51 / 300 runs on a three-replica cluster, t1 ARRAY JOIN [1, 2] AS a ANY INNER JOIN t3 ON 1 returned 2 instead of 1 in 19 / 60 runs, the non-leftmost PASTE JOIN shape failed outright in 15 / 40 runs with Code: 62 ... You must not specify ANY or ALL for PASTE JOIN. (SYNTAX_ERROR) raised by a remote replica (0 / 40 with the fix), and t1 ARRAY JOIN [1] AS a FULL JOIN t2 ON t1.c = t2.c returned every row twice in 8 / 60 runs (0 / 60 with the fix). The committed test fails 10 / 10 runs on a master binary.
b Root cause explained? Yes. allowParallelReplicasForJoinTree is evaluated on parent_join_tree_for_leftmost, which the loop at PlannerJoinTree.cpp:2681-2692 sets to the first JOIN / CROSS_JOIN / ARRAY_JOIN node of the post-order table_expressions_stack. For (t1 ALL INNER t2) ANY INNER t3 the stack is [t1, t2, JOIN Inner/All, t3, JOIN Inner/Any], so only the Inner/All join is checked and the outer ANY join is never examined. The initiator then ships the whole join tree (ANY included) to every replica while coordinating only the leftmost leaf's reads, so each replica applies ANY strictness independently and the initiator concatenates the per-replica rows. Hence the extra row is a duplicate of the same row, not a different right-side value.
c Fix matches root cause? Yes. The eligibility predicate is extended in should_disable_parallel_replicas, which already walks the whole stack and already vetoes n-way trees for FULL / GLOBAL / CROSS and misplaced RIGHT joins -- it simply never inspected strictness, nor the two non-distributive kinds (PASTE, which pairs rows by position, and FULL, which emits unmatched right rows) that reach the planner carrying ALL. No widened bound, no no-random-* tag (the failing job already runs --no-random-settings --no-random-merge-tree-settings, so the randomizer had nothing to pin), and no assertion is weakened. The new test does pin two settings that the stress runner injects as per-thread client options (stress.py:163-179), join_algorithm = 'hash' and join_use_nulls = 0: neither is what the test measures, and both are load-bearing, since join_algorithm='partial_merge' / 'grace_hash' make the ASOF assertion throw Code: 48 ... Can't execute any of specified algorithms for specified strictness/kind and right storage type and join_use_nulls=1 turns the FULL join's default-filled cells into \N.
d Test intent preserved / new tests added? The carrier test 04490_any_join_constant_condition_reorder is untouched and passes. New test 04651_pr_nway_join_non_leftmost_strictness pins both the decision -- 20 EXPLAIN-based assertions, 12 of which expect no ReadFromRemoteParallelReplicas step (the two three-way ANY INNER shapes, the ARRAY JOIN + ANY INNER shape, the ARRAY JOIN + FULL shape, the four ARRAY JOIN + RIGHT strictness shapes ANY, SEMI, ANTI and the RightAny that any_join_distinct_right_table_keys = 1 produces, the ASOF INNER shape, the non-leftmost PASTE shape, and the already-covered two-way ANY INNER and two-way PASTE) and 8 of which expect the step to still be present for a replica-safe tree -- and the row-level contract in 4 further assertions. Two of them are deliberate negative controls that pin the kind != Left exemption: non-leftmost ANY LEFT and SEMI LEFT, without which both would be wrongly disabled. ARRAY JOIN + FULL is a discriminator rather than a control: it reads 1 on master and 0 with the fix, and a row-level control asserts that the unmatched right row t2.c = 3 is emitted exactly once. The RIGHT axis is pinned in both directions by five further assertions, because the shipped condition decides it through the strictness term alone: ARRAY JOIN ... ALL RIGHT JOIN reads 1 (deliberately still eligible -- the residual described in the description, which keeps 03452_array_join_global_right_join_parallel_replicas exercising that path) while the ANY, SEMI, ANTI and RightAny spellings all read 0, so neither the residual nor any single one of the four vetoes can flip unnoticed. The ASOF INNER assertion pins the strictness term itself, which a narrower == JoinStrictness::Any form would leave open, and the PASTE pair pins the kind term: the non-leftmost one is the discriminator (1 on master, 0 with the fix) and the two-way one is a guard that reads 0 on both because a leftmost PASTE is already ineligible. The row-level control is the constant-key ALL INNER sibling of the buggy statement -- the same non-leftmost ON 1 join differing only in strictness -- which returns two rows, so it can actually observe a duplicate; the earlier INNER ... INNER ON t1.c = t3.c form returned the empty set for this fixture and was therefore blind to the defect class.
e Both directions demonstrated? Yes. New test: 10 / 10 FAIL on a pristine master binary, 50 / 50 PASS with randomized settings on the fixed binary. On master exactly ten plan-shape assertion lines flip 0 -> 1 (inner/any non-leftmost, the same under a LEFT leftmost join, array join then inner/any, array join then full, the four `array join then any
f Fix is general across code paths? Yes. getSupportingParallelReplicasQueries and findTableForParallelReplicas (findParallelReplicasQuery.cpp:100, :412) apply the same per-node check while descending the tree and are already whole-tree correct, so they need no change; they are also reached from a different path than this bug takes. The plan-based path behind parallel_replicas_plan_based (applyParallelReplicas.cpp) is deliberately not touched here: that setting defaults false, is set by no test config and randomized by no runner, and none of the 15 in-tree tests that enable it contains a JOIN, so a change there would be unverifiable. It is also already covered by this veto, which clears the enable_parallel_replicas alias that QueryPlanOptimizationSettings.cpp:361 reads before applyParallelReplicas runs. Whether that path needs its own guard is tracked separately. The kind axis was swept as well as the strictness one, rather than assumed: PASTE is the only kind that reaches the Planner with ALL strictness while being non-distributive (it pairs rows by position, PasteJoinTransform.cpp:95-114), and it is invisible to every pre-existing disjunct -- isCrossOrComma excludes Paste (Joins.h:35), is_full_join needs JoinKind::Full, and first_join_pos / last_right_join_pos track only Left/Inner/Right. FULL/GLOBAL/CROSS are covered by the pre-existing rule, misplaced RIGHT by the position rule, and Comma is rewritten to Inner/All by crossToInner before the Planner sees it.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The condition is a whitelist over the whole JoinKind x JoinStrictness space, so it is fail-closed for future enumerators, and it applies to an unsafe join placed after any preceding join-tree node -- another JOIN, a CROSS_JOIN, or an ARRAY JOIN (measured for both the array-literal and the Array(Int32)-column spelling, which build the identical [t1, ARRAY_JOIN, t3, JOIN] stack). Measured a 16-shape JoinKind x JoinStrictness matrix on both binaries (master -> fix), which agrees cell-for-cell with a 26-shape simulation of the loop: the shapes that change are ARRAY JOIN followed by ANY INNER, ANY RIGHT, SEMI RIGHT, ASOF INNER or an unspecified-strictness INNER, an n-way INNER/LEFT tree followed by ANY INNER (the reported failure) or ASOF, the non-leftmost PASTE kind, and the ARRAY JOIN + FULL/GLOBAL FULL kind. A 12-shape re-measurement of the FULL term alone confirms it changes those two shapes and no other, leaving ARRAY JOIN followed by RIGHT, GLOBAL RIGHT, GLOBAL LEFT, INNER or PASTE, two-way leftmost FULL, 3-way INNER then FULL, CROSS-leftmost then FULL and 3-way INNER then INNER all unchanged. (Inner, Asof) is conservative: ASOF INNER JOIN is valid syntax and is now disabled on this path even though it was not observed to duplicate. A non-leftmost FULL in an ordinary n-way tree reads 0 on master already (pre-existing `joins_count > 1 && (FULL
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changes, so no SettingsChangesHistory.cpp entry is required (verified -- the diff does not touch that file). No serialization or format change. The change only ever disables parallel replicas, so it cannot alter the result of a query that was already correct and cannot enable parallel replicas anywhere new; the previous behaviour is recoverable per query by the existing enable_parallel_replicas setting.
i Invariants and contracts preserved? Yes. Both new locals are computed inside the existing single pass over table_expressions_stack, with no early exit between their assignment and their use. leftmost_join_tree_node_seen is set for JOIN / CROSS_JOIN / ARRAY_JOIN, so "leftmost" denotes exactly the node the break loop at :2681-2692 selects, keeping the new flag consistent with the eligibility check it complements. has_unsafe_non_leftmost_join can only be set once such a node has been seen, so it already implies "not the leftmost join-tree node" and needs no separate count gate -- an ARRAY JOIN occupies that slot without incrementing joins_count, so gating on the count would have left that shape broken. The strictness term stays scoped to strictness and the unsafe kinds are expressed as separate disjuncts beside it rather than by relaxing it, because a PASTE or FULL node carries ALL strictness and a kind that is not Left, so neither existing term can reach it. The kind list is deliberately PASTE and FULL only: a non-leftmost RIGHT shares FULL's unmatched-right-row mechanism, but vetoing it would, for an ARRAY_JOIN-leftmost tree where no pre-existing disjunct can fire, silently make 03452_array_join_global_right_join_parallel_replicas stop exercising the getSubqueryFromTableExpression ARRAY_JOIN branch it was written for while still passing -- measured, and left as a disclosed residual. Each term is independently pinned by a mutation: reverting Full flips only the ARRAY JOIN + FULL line, reverting Paste only the paste non-leftmost line, and deleting && join_kind != JoinKind::Left only the two LEFT lines. The already-correct two-table case stays untouched because there the ANY join is the leftmost join-tree node. Plain stack booleans -- no lifetime, ownership or concurrency contracts involved.

Session id: cron:clickhouse-impl-slot-41:20260728-060900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @yakov-olkhovskiy — could you review this? Parallel-replicas eligibility for a join tree is decided by allowParallelReplicasForJoinTree, which only ever sees the parent join of the leftmost leaf, so a non-leftmost ANY INNER JOIN ... ON 1 is never examined: the whole tree is shipped to every replica while only the leftmost leaf's reads are coordinated, each replica applies ANY independently, and the initiator concatenates the results. This adds the missing strictness and kind check to should_disable_parallel_replicas, which already walks the whole tree for the other veto rules, and also closes a non-leftmost PASTE JOIN and an ARRAY JOIN followed by FULL JOIN.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [517c8a6]

Summary: ✅


AI Review

Summary

This PR fixes the wrong-result class where task-based parallel replicas can duplicate rows when an unsafe non-leftmost join in the join tree is never examined by allowParallelReplicasForJoinTree. The new join-tree scan closes that correctness hole for the normal enable_parallel_replicas = 1 path, but it currently breaks the separate force-mode contract by silently downgrading newly unsupported join shapes instead of failing.

Findings

⚠️ Majors

  • [src/Planner/PlannerJoinTree.cpp:3563] The new veto unconditionally sets enable_parallel_replicas = 0, so queries that now become unsupported under this fix silently fall back even when the user explicitly requested enable_parallel_replicas = 2. Neighboring planner/analyzer gates treat that setting as "must use parallel replicas or throw" and raise SUPPORT_IS_DISABLED for unsupported shapes; this change makes forced mode indistinguishable from a successful parallel-replicas execution. Suggested fix: mirror the existing pattern from Planner.cpp by throwing when allow_experimental_parallel_reading_from_replicas >= 2, and add a stateless force-mode regression for one of the newly rejected join trees.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 517c8a6.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 81.40% 81.30% -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 28, 2026
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.10% 92.00% -0.10%
Branches 78.40% 78.30% -0.10%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 039bc64

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error: Got read request from replica A for unknown stream B (STID 5217-505b) trunk bug in the parallel-replicas reading coordinator, not related to this diff #111689 (mine, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Server died same job, same event: the coordinator abort above killed the server, so this row is its consequence rather than a separate failure #111689 (mine, open)

Not caused by this PR: the diff here touches PlannerJoinTree.cpp join strictness plus one new
stateless test, and cannot reach the parallel-replicas coordinator. The for unknown stream
signature has 145 hits across 121 distinct PRs (11 of them on master) in the last 30 days,
so it predates and is independent of this branch. All 174 checks completed; this was the only
failing job.

Session id: cron:our-pr-ci-monitor:20260729-010000

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Sep 4, 2026
… join

With `enable_parallel_replicas = 1`, `t1 INNER JOIN t2 ON t1.c = t2.c ANY INNER
JOIN t3 ON 1` returns the row once per replica instead of once: 3 rows in 60 of
60 runs on a three-replica cluster with `parallel_replicas_local_plan = 0`, and
correct in 60 of 60 with the local plan on, which is why CI sees it
intermittently. Found by 04490_any_join_constant_condition_reorder in
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel).

Parallel-replicas eligibility for a join tree is decided by
allowParallelReplicasForJoinTree, which is evaluated only on the first join node
of the post-order table-expression stack. For (t1 ALL INNER JOIN t2) ANY INNER
JOIN t3 that node is the Inner/All join, so the outer ANY join is never
examined. The initiator then ships the whole join tree to every replica while
only the leftmost leaf's reads are coordinated, so each replica applies ANY to
its own slice and the initiator concatenates the results. This is why the extra
rows are duplicates rather than different right-side values: the strictness is
not lost, it is applied once per replica.

should_disable_parallel_replicas already walks the whole stack and already
vetoes n-way trees on other grounds (FULL/GLOBAL/CROSS, and a misplaced RIGHT);
it simply never looked at strictness. It now also vetoes a non-leftmost join
whose strictness is not ALL outside a LEFT kind, or whose kind is PASTE (pairs
rows by position) or FULL (emits unmatched right rows, which each replica would
decide from its own slice of the left side). Outside LEFT the strictness test is
a whitelist, so a future JoinStrictness enumerator fails closed there; under
LEFT every strictness is admitted, because those strictnesses are decided per
left row. The veto is not gated on joins_count, because an ARRAY JOIN can occupy
the leftmost slot without incrementing it.

ARRAY JOIN ... ALL RIGHT JOIN is left eligible on purpose: vetoing it would
disable parallel replicas for
03452_array_join_global_right_join_parallel_replicas, whose purpose is to
exercise that path, and its row counts match a parallel-replicas-off oracle in
60 of 60 runs. That residual is master's own behaviour.

The new test asserts the decision rather than the row count: whether the plan
contains a ReadFromRemoteParallelReplicas step. Ten of its twenty assertions
flip on a master binary, the other ten are guards that read the same value on
both, and each term of the veto is pinned on its own.

Brought up to master 77fa254. One conflict, in the flag
declarations in front of the table-expression-stack loop, where both sides only
append: master adds has_global_join_preserving_broadcast_rows, read at the
distributed left-table wrapping decision, and this branch adds
leftmost_join_tree_node_seen and has_unsafe_non_leftmost_join, read in
should_disable_parallel_replicas. The readers are disjoint, so both declarations
are kept; a duplicate-name census over the declaration block reports 10 names,
10 unique.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-pr-nway-join-non-leftmost-strictness branch from 039bc64 to 637c36c Compare September 12, 2026 13:03
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 517c8a6bd with master 3476b12ea (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

A non-leftmost `ASOF INNER JOIN` decides each left row on its own, so the veto's comment
("a non-leftmost join must be distributive over a partition of the left side") made its
rejection look arbitrary. That criterion is not what decides.

A leaf's reads are coordinated only for the join shapes the search for that leaf descends:
`LEFT`, `INNER` with `ALL`, and a qualifying `RIGHT` (`getSupportingParallelReplicasQuery`,
src/Planner/findParallelReplicasQuery.cpp:161, and `findTableForParallelReplicas`, :476).
`Inner` with `Asof` is in neither set, so nothing partitions the left side, every replica
evaluates the whole join and the initiator concatenates the copies.

Measured on master without this veto, three replicas, `parallel_replicas_local_plan = 0`:
a non-leftmost `ASOF INNER JOIN` returns every row once per replica, 290 rows becoming 870
over a 300-row left side in 60/60 runs, and 3 rows becoming 9 on a minimal fixture in 40/40.
The count tracks `max_parallel_replicas` (1, 2, 3 give 3, 6, 9 rows). The ASOF picks are
correct: no row differs from the single-replica answer, so the defect is pure duplication.
`ASOF LEFT`, `ANY LEFT` and `SEMI LEFT` keep parallel replicas and stay correct in 40/40 runs
on both binaries, which is what the kind exemption is for; the kind, not per-left-row
semantics, is what makes a strictness safe here.

The comment now states that rule, at its previous length. The ASOF assertions move to a `t4`
fixture whose keys overlap `t1` (`t3`'s do not, so that ASOF answer was empty and no row
assertion on it could ever fail) and gain the row assertion, which returns the row three
times on a build that exempts `JoinStrictness::Asof`. The plan-shape line and the new row
line are the only two assertions that flip on such a build.

/// A non-leftmost join that is not replica-safe (e.g. INNER ... ANY INNER). Deliberately not gated on
/// `joins_count`: an ARRAY JOIN can occupy the leftmost slot without incrementing it.
if (has_unsafe_non_leftmost_join)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

enable_parallel_replicas = 2 is the "must use parallel replicas or fail" mode, and the neighboring planner gates preserve that contract by throwing SUPPORT_IS_DISABLED before they clear the setting (for example Planner.cpp:2615-2702, and 04604_join_using_nested_projection_alias_remote.sql has the regression test for the join side of that rule). This new veto clears the alias unconditionally instead, so a query like ... ARRAY JOIN ... ANY INNER JOIN ... SETTINGS enable_parallel_replicas = 2 now silently falls back to a plain local read. That makes an explicitly forced configuration indistinguishable from a supported plan that actually used parallel replicas. Please branch here the same way the other unsupported-shape checks do: if allow_experimental_parallel_reading_from_replicas >= 2, throw SUPPORT_IS_DISABLED; otherwise disable parallel replicas and add a focused force-mode test for one of these newly rejected join trees.

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.

Both citations check out, and force mode does throw where master implements it: on this build at enable_parallel_replicas = 2, additional_table_filters and the custom-key JOIN gate both give Code: 344 ... (SUPPORT_IS_DISABLED), so the "no exception" results below are not an artifact of a probe that never reaches force mode. enable_parallel_replicas is the alias of allow_experimental_parallel_reading_from_replicas (Settings.cpp, DECLARE_WITH_ALIAS), verified in both directions at runtime, so your predicate would read the value this site clears.

What that clear is not is this PR's line. It is the call site of should_disable_parallel_replicas, unconditional since d8f1f6f266392 (2024-12-09), and each of its four pre-existing checks reaches it the same way. Measured on a three-replica ReplicatedMergeTree cluster at = 2, pristine master 1b86f9d3f25a9 against this branch:

shape at enable_parallel_replicas = 2 master this branch
LEFT ... ALL RIGHT (master's misplaced-RIGHT check) no exception, no parallel replicas in the plan same
INNER ... FULL (master's n-way FULL check) no exception, no parallel replicas in the plan same
INNER ... ANY INNER ON 1 (what this PR vetoes) no exception, parallel replicas used, 3 rows against an oracle of 1 no exception, 1 row

The not-enough-rows clear in the same file behaves the same way at = 2, and a supported shape does plan parallel replicas there, so those zeroes are the veto and not a dead fixture. Three of the five unconditional clears in this file log the downgrade; this call site is not one of them, which is the other half of "silently".

So force mode is already advisory at this site for four shapes this PR does not touch, and this PR's own delta at = 2 is three duplicated rows becoming one correct row, not an error anyone loses.

I did not fold the branch in. At the call site it changes behaviour for those four other shapes; scoped to my check alone it makes one of five sibling checks throw. Either way that is a ruling about this site's contract rather than about a wrong-results fix, so I also left today's force-mode behaviour unpinned in 04651, and a later change will not have to fight it.

The lever is small: the >= 2 branch, the missing LOG_DEBUG, and a force-mode test for one of the newly rejected trees. If a reviewer wants it in this PR, say so and I will push it; otherwise it belongs in its own PR and I will keep it out of a bug fix.

@alexey-milovidov alexey-milovidov left 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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit c6aa627 Sep 13, 2026
174 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
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-ci-master PR origin: master/nightly CI monitoring finding 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.

4 participants