Skip to content

Do not rewrite a join into a shape no enabled algorithm can execute - #118315

Merged
alexey-milovidov merged 16 commits into
masterfrom
join-algorithm-capability-check-111075
Oct 14, 2026
Merged

alexey-milovidov merged 16 commits into
masterfrom
join-algorithm-capability-check-111075

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

query_plan_convert_any_join_to_semi_or_anti_join turns the ANY join of a decorrelated EXISTS - or of a user's own query - into a SEMI or ANTI join whenever the filter above it allows. The sort-merge algorithms implement neither, so under join_algorithm = 'full_sorting_merge' the conversion turned a query that runs into one that throws:

CREATE TABLE t (a UInt32, b UInt32) ENGINE = MergeTree ORDER BY a;
INSERT INTO t SELECT number, number % 7 FROM numbers(100);

SELECT count() FROM t AS o WHERE EXISTS (SELECT 1 FROM t AS i WHERE i.b = o.b AND i.a = 5)
SETTINGS join_algorithm = 'full_sorting_merge';
-- Code: 48. None of the algorithms enabled by the 'join_algorithm' setting [full_sorting_merge]
--   can execute this SEMI LEFT JOIN with the given right table storage type (NOT_IMPLEMENTED)

The pass now converts only into a strictness one of the enabled algorithms can execute. rewrite_in_to_join reaches the same conversion through the EXISTS it builds out of x IN (subquery), so that path is fixed by the same check.

The decorrelation join itself had the same problem one step earlier: it is built as ANY RIGHT, which no sort-merge algorithm executes and which partial_merge does not do at all beyond INNER/LEFT, so a correlated subquery under join_algorithm = 'partial_merge' failed even with the conversion pass off. As the buffered case in the same function already does, the join now gets the hash algorithms when the user-facing list cannot execute it - that list describes the user's joins, not an internal decorrelation detail.

A third reported shape needs neither of those settings: an always-false WHERE over a user-written
ANY LEFT JOIN against an ENGINE = Join table is FALSE for the rows the join does not match, so the
pass converted the join to SEMI LEFT and the query failed under join_algorithm = 'full_sorting_merge'
while the unoptimized plan ran. The same check covers it.

The capability question is answered in one place, JoinCommon::canBeExecutedByEnabledAlgorithm, so the sort-merge restrictions are not spelled out twice.

grace_hash counts only where the join pickers run it on every node, which is decided by JoinSettings::canRunGraceHash. That means legacy mode, an absolute max_bytes_before_external_join, or grace_hash listed alone. A threshold given only as a ratio does not count, because a server without memory limits resolves it to 0. The runtime filter pass uses the same predicate. Before, it cut join_algorithm = 'full_sorting_merge,grace_hash' of a swapped ANY RIGHT join down to grace_hash alone, and without a threshold that is refused with BAD_ARGUMENTS.

Closes: #111075
Closes: #111207
Closes: #111877
Related: #103294

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 to CHANGELOG.md):

Fixed NOT_IMPLEMENTED ("None of the algorithms enabled by the 'join_algorithm' setting ... can execute this SEMI/ANTI JOIN") for a correlated EXISTS/NOT EXISTS subquery, for an IN (subquery) under rewrite_in_to_join, or for an ANY LEFT JOIN of an ENGINE = Join table under an always-false WHERE, when join_algorithm is set to full_sorting_merge or partial_merge.


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

Version info

  • Merged into: 26.10.1.2346-master (included in 26.10 and later)

`query_plan_convert_any_join_to_semi_or_anti_join` turns the `ANY` join of a
decorrelated `EXISTS` - or of a user's own query - into a `SEMI` or `ANTI` join
whenever the filter above it allows. The sort-merge algorithms implement
neither, so under `join_algorithm = 'full_sorting_merge'` the conversion turned
a query that runs into one that throws:

    SELECT count() FROM t AS o WHERE EXISTS (SELECT 1 FROM t AS i WHERE i.b = o.b AND i.a = 5)
    SETTINGS join_algorithm = 'full_sorting_merge';
    Code: 48. None of the algorithms enabled by the 'join_algorithm' setting [full_sorting_merge]
    can execute this SEMI LEFT JOIN with the given right table storage type

The pass now converts only into a strictness one of the enabled algorithms can
execute. `rewrite_in_to_join` reaches the same conversion through the `EXISTS` it
builds out of `x IN (subquery)`, so that path is fixed by the same check.

The decorrelation join itself had the same problem one step earlier: it is built
as `ANY RIGHT`, which no sort-merge algorithm executes and which `partial_merge`
does not do at all beyond `INNER`/`LEFT`. As the buffered case in the same
function already does, the join now gets the hash algorithms when the
user-facing list cannot execute it - that list describes the user's joins, not
an internal decorrelation detail.

The capability question is answered in one place, `JoinCommon::canBeExecutedByEnabledAlgorithm`.

Closes: #111075
Closes: #111207

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f17c0c7]

Summary: ✅


AI Review

Summary

This PR closes a real optimizer contract gap: it now prevents ANY→SEMI/ANTI rewrites and correlated-subquery decorrelation joins from picking a join shape that the enabled algorithms cannot execute, and it keeps the runtime-filter pass from cutting join_algorithm down to a non-runnable grace_hash configuration. I reviewed the current diff, the existing review threads, and the updated stateless coverage, and I do not see any remaining correctness or safety issues in the current head.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit f17c0c7.

Metric Baseline Current Δ
Lines 88.30% 88.20% -0.10%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 86/90 (95.56%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 5, 2026
Comment thread src/Interpreters/JoinUtils.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit f17c0c77c952168f0e92d082a503d9b8623c058e was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

alexey-milovidov and others added 5 commits September 6, 2026 11:04
…`WHERE`

The same guard fixes a second reported shape, which needs neither `rewrite_in_to_join` nor a
correlated subquery: an always-false `WHERE` over a user-written `ANY LEFT JOIN` against an
`ENGINE = Join` table is `FALSE` for the not matched rows, so the pass converted the join to
`SEMI LEFT`, which no sort-merge algorithm can execute, and the query failed with `NOT_IMPLEMENTED`
under `join_algorithm = 'full_sorting_merge'` while the unoptimized plan ran.

Closes: #111877

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The correlated `EXISTS` whose decorrelated join the test is about is not supported without the
analyzer, where the query fails with `Missing columns` instead.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…a hash fallback

`canBeExecutedByEnabledAlgorithm` treated `PREFER_PARTIAL_MERGE` as if it
only enabled `MergeJoin`, but `tryCreateJoin` in both `PlannerJoins` and
`ExpressionAnalyzer` falls through to the hash algorithms whenever
`MergeJoin` cannot execute the requested kind and strictness. The helper
therefore reported `false` for shapes such as `ANY RIGHT` or `ANTI` that
the planner would have executed, which suppressed the safe
`ANY` -> `SEMI`/`ANTI` rewrites and made `PlannerCorrelatedSubqueries`
override the algorithm list for nothing.

Treat `prefer_partial_merge` as able to execute every kind and strictness,
and cover it in `05093_any_join_to_semi_anti_algorithm_check`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
With `prefer_partial_merge` modelled as `partial_merge` plus the hash
fallback, the `ANY` -> `SEMI`/`ANTI` conversion happens again under that
setting.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Sep 11, 2026
alexey-milovidov and others added 3 commits September 18, 2026 14:32
CI randomizes `query_plan_convert_any_join_to_semi_or_anti_join`, so both new
tests could pass with the conversion pass they exercise switched off. Pin it to
`1` in `05093_any_join_to_semi_anti_algorithm_check` and
`05102_storage_join_any_to_semi_algorithm_check`.

`05102_storage_join_any_to_semi_algorithm_check` also pins `join_use_nulls = 0`,
because an `ENGINE = Join` table rejects a mismatched `join_use_nulls` with an
unrelated error, the same way `03630_any_join_to_semi_storage_join_guard` does.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Commit 3e5da64 picked up the submodule pointers of another branch that
happened to be checked out in the same working tree. They have nothing to do
with this change, so put both back to what `master` has.
Comment thread src/Interpreters/JoinUtils.cpp Resolved
alexey-milovidov and others added 2 commits September 25, 2026 20:09
…run it

`tryCreateJoin` in both `PlannerJoins.cpp` and `ExpressionAnalyzer.cpp` passes
`grace_hash` over for the next algorithm of the `join_algorithm` list when there is
no spill threshold and `legacy_join_size_limits_trigger_spilling` is off. So
`canBeExecutedByEnabledAlgorithm` reporting it as able to execute every kind and
strictness let `join_algorithm = 'full_sorting_merge,grace_hash'` rewrite an `ANY LEFT`
join into `SEMI LEFT`, which then failed with `NOT_IMPLEMENTED`, and kept the
correlated-subquery fallback from replacing lists like `grace_hash,partial_merge`.

The helper now takes the whole `JoinSettings` and applies the same rule.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and adopted the grace_hash review finding (dd5ac51). The earlier CI reds were not caused by this PR: the Build profile diff infra error and the Upgrade check failure should clear now that master is merged in. The Stress test (arm_msan) GroupingAggregatedTransform pushed bucket A twice failure is the known open issue #115986. @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118315&sha=93bd5ff84f3f9620d16f6acc7718938dc4c5f403&name_0=PR&name_1=Stress%20test%20%28arm_msan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

Comment thread src/Interpreters/JoinUtils.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. This is the Cascades route of #115986, and your #119814 fixes it (merged 2026-09-25 02:50Z), so there is no new PR from me.

Attribution. The abort is query 7d1a7f61-6d77-4805-bc48-27d7f96c9dc9, log_comment = '04878_distributed_plan_shuffle_bucket_order_promise.sql-test_3': SELECT k, sum(v) FROM remote('127.0.0.{2,3}', currentDatabase(), t_shuffle_bucket_order) GROUP BY k, run with enable_cascades_optimizer = 1 and distributed_plan_force_shuffle_aggregation = 1. pushed bucket 1 twice is raised in GroupingAggregatedTransform::pushData (MergingAggregatedMemoryEfficientTransform.cpp:63), reached from tryPushTwoLevelData().

Fix presence. The job built f3dcd08e8db0, which is 93bd5ff84f3f merged into master e805acad5c00 of 2026-09-20, so #119814 was not in it (compare/f963ba3157d3...f3dcd08e8db0 is diverged). Your new head dd5ac5176cba contains the merge commit f963ba3157d3 (ahead, 0 behind), which brings both parts of the fix: the Cascades AggregationImplementation change, and SET enable_cascades_optimizer = 0 in 04878, whose Cascades plan is now pinned by 05210. The next Stress test (arm_msan) run here should not hit it.

Since the merge, the only hit on a master-based tree is #122124 at 03:18Z, and that job built on master c68449eaaf27, which is before the merge.

alexey-milovidov and others added 2 commits October 3, 2026 00:17
…lters

`05257_any_join_to_semi_grace_hash_without_spill_threshold` failed in CI with
`query_plan_optimize_join_order_randomize`: the join reordering swapped the
`ANY LEFT` join into `ANY RIGHT`, which takes a runtime filter, and the runtime
filter pass cut `join_algorithm = 'full_sorting_merge,grace_hash'` down to
`grace_hash` alone. Alone in the list, `grace_hash` without a spill threshold is
no longer passed over but refused with `BAD_ARGUMENTS`. The pass now keeps
`grace_hash` only where the join pickers would run it.

Address review: the decision is shared in `JoinSettings::canRunGraceHash`, and it
no longer counts a threshold given only by `max_bytes_ratio_before_external_join`:
each server resolves the ratio against its own memory limits, so a remote server
without them would pass `grace_hash` over after the initiator counted it.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118315&sha=dd5ac5176cba19dccd462e71156bfbd31c47ca61&name_0=PR
PR: #118315

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/JoinOperator.h Resolved
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 4, 2026
The previous commit lets `filterResultForNotMatchedRows` decide filters
that contain an `IN (subquery)` set that is not built yet. That helper is
also used by `tryConvertAnyJoinToSemiOrAntiJoin`, so an `ANY LEFT/RIGHT
JOIN ... WHERE rhs_predicate AND rhs_col IN (subquery)` started to be
rewritten to `SEMI`. `full_sorting_merge` cannot run `SEMI`, so such a
query, which runs on master, failed with `NOT_IMPLEMENTED` (the same gap
that the variant without the `IN` already has, ClickHouse#118315).

Restore the bail-out on not-built sets in the `ANY` pass, so it behaves
as on master; the outer-to-inner conversion keeps the new handling.

The test now runs that `ANY LEFT JOIN` with `join_algorithm =
'full_sorting_merge'` instead of asserting the `SEMI` plan: it returns
`2 4` on master and with this commit, and fails with code 48 without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 4, 2026 21:21
…orage

Without `tmp_path` / `tmp_policy`, the join pickers refuse `grace_hash` with
`NOT_IMPLEMENTED` instead of passing it over, so `JoinSettings::canRunGraceHash`
must not let the `ANY` to `SEMI`/`ANTI` conversion or the runtime filter
cutdown count on it there.

Also extract `Strictness: ...` from `EXPLAIN` in the new tests instead of
trimming leading spaces: with parallel replicas the plan is nested deeper and
the tree-drawing prefix differs.
https://s3.amazonaws.com/clickhouse-test-reports/PRs/118315/3865eeee725c5c2ab278d9ed36d737550b33b488/pr/result_stateless_tests_amd_llvm_coverage_parallelreplicas_s3_storage_parallel.json

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Planner/PlannerCorrelatedSubqueries.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master. The only CI red, AST fuzzer (amd_debug, targeted, old_compatibility) with Totals having transform was already added to pipeline (report), is not caused by this PR. It needs only rewrite_in_to_join = 1 and reproduces on a master binary (26.10.1.1604). The cause is that the IN→EXISTS rewrite keeps the subquery's WITH TOTALS. Fixed in #124096.

aschoube pushed a commit to aschoube/ClickHouse that referenced this pull request Oct 8, 2026
…join`

The regular `IN` set ignores the totals row of its subquery, but the `rewrite_in_to_join`
rewrite into a correlated `EXISTS` kept the `TotalsHaving` step on the right side of the
join built by the decorrelation. That leaked the totals row into the outer query and,
when the outer query had `WITH TOTALS` as well, failed with the `LOGICAL_ERROR`
`Totals having transform was already added to pipeline`.

Found by the AST fuzzer in ClickHouse#118315:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118315&sha=eaa8e0b5913bdc2bf50caccbefee4e1589987921&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is clear and neat. LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Oct 14, 2026
@alexey-milovidov alexey-milovidov removed the submodule changed At least one submodule changed in this PR. label Oct 14, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 14, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 14, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 14, 2026
Merged via the queue into master with commit 13d302e Oct 14, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the join-algorithm-capability-check-111075 branch October 14, 2026 01:42
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
Since ClickHouse#125085, `max_threads = auto` is
lowered to the fair share of CPU slots of `ConcurrencyControl` when other queries are
running. Under the concurrent load of the test runner the read in order can be planned
with a single stream, so both parts are read by one `readInOrder` call and
`EXPLAIN PIPELINE` shows `ReverseTransform × 2` instead of two separate chains.

Disable `use_concurrency_control_for_max_threads` in the test, as its output depends on
the number of streams.

Failed in the merge queue of ClickHouse#118315:
https://github.com/ClickHouse/ClickHouse/actions/runs/38491344800/job/115617405459

Co-Authored-By: Claude Opus 5.5 <[email protected]>
shankar-iyer pushed a commit to shankar-iyer/ClickHouse that referenced this pull request Oct 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... 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

3 participants