Skip to content

Remove CrossJoinNode: convert comma joins to INNER in the query plan - #119259

Open
vdimir wants to merge 16 commits into
masterfrom
vdimir/remove-cross-join-node
Open

vdimir wants to merge 16 commits into
masterfrom
vdimir/remove-cross-join-node

Conversation

@vdimir

@vdimir vdimir commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Comma joins and CROSS JOIN are converted to INNER JOIN by the query plan optimizer instead of the query analyzer. cross_to_inner_join_rewrite = 2 still rejects a comma join without an equi-join condition. GLOBAL CROSS JOIN now keeps its locality.


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

The n-ary CrossJoinNode existed only so that CrossToInnerJoinPass could
build a join graph from WHERE equalities and re-emit a reordered chain of
INNER JoinNodes. The query plan now does this itself: mergeFilterIntoJoinCondition
turns a Cross/Comma JoinStepLogical with WHERE equalities into an INNER join
and the join order optimizer handles the ordering. Comma and CROSS joins are
plain binary JoinNodes again, the pass and the node are deleted.

Plan-level changes needed to cover what the pass did:
- mergeFilterIntoJoinCondition runs before pushDownFilter, so a predicate on a
  key column is copied to both join inputs instead of sinking into one; the
  rebuilt filter keeps its conjuncts visible to the pushdown and the emptied
  filter step keeps its description.
- Equalities whose sides mix both inputs become join conditions (hyperedges for
  the join order optimizer) when hash join is available.
- Server constants are refused as join keys, as the pass did.
- cross_to_inner_join_rewrite = 2 is checked in the plan (normalizeCommaJoins):
  a comma join without join keys after the optimizations is INCORRECT_QUERY,
  and force mode implies the optimization.
- A cross product costs slightly more than a join of the same inputs, so the
  join order optimizers do not pick one on a cost tie without statistics.
- Cross/Comma JoinStepLogical gets strictness All so it stays reorderable.

GLOBAL locality of an unrewritten cross join was dropped by the n-ary path and
is now preserved. Parallel replicas stay disabled for cross joins, so a comma
join with WHERE keys is no longer eligible for them (to be handled separately).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0591c3d]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
Build ClickHouse FAIL
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 10, 2026
vdimir and others added 2 commits September 10, 2026 15:44
…-join-node

# Conflicts:
#	src/Analyzer/Resolve/QueryAnalyzer.cpp
The rebuilt filter must keep a predicate column that is also a regular
output (`WHERE flag AND a = b` selecting `flag`). The emptied filter step is
left nameless again, as the pushdown does, to keep the plan labels of master.
The correlated-subquery test pins the merge off only from the guarded float
case on, since its comma joins now get their keys from that optimization.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
merge_filter_into_join_condition = from[Setting::query_plan_enable_optimizations] && from[Setting::query_plan_merge_filter_into_join_condition];
force_comma_join_rewrite = from[Setting::cross_to_inner_join_rewrite] >= 2;
/// Forcing the rewrite of comma joins makes no sense without the optimization that performs it.
merge_filter_into_join_condition = from[Setting::query_plan_enable_optimizations]

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.

cross_to_inner_join_rewrite = 2 is supposed to imply the plan rewrite, but this still gates merge_filter_into_join_condition on query_plan_enable_optimizations.

With SETTINGS cross_to_inner_join_rewrite = 2, query_plan_enable_optimizations = 0, optimizeTreeFirstPass skips mergeFilterIntoJoinCondition entirely, then normalizeCommaJoins in the second pass still sees a Comma join and throws INCORRECT_QUERY even for a valid query like SELECT count() FROM t1, t2 WHERE t1.a = t2.a.

I think force mode needs to bypass the global optimization gate for this one rewrite, or the first pass needs a special case so tryMergeFilterIntoJoinCondition still runs when force_comma_join_rewrite is set. A focused stateless test for that setting combination would pin it.

@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 10, 2026
…e merge setting

Comma joins are converted to INNER joins whenever `cross_to_inner_join_rewrite`
is non-zero, independently of `query_plan_merge_filter_into_join_condition`,
which keeps governing INNER and CROSS joins (the planner emits CROSS for
decorrelated subqueries, and 05023 relies on that setting to keep a float
equality out of a hash join). `cross_to_inner_join_rewrite = 0` now keeps the
cross join with the analyzer too, so the tests that set it only to bypass the
old query-tree pass drop it, and the pins added for the randomized merge
setting are not needed anymore.

A filter emptied by the merge whose actions are the identity is dropped
instead of leaving a nameless expression step.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 9fb7b707b90df7e97fae3979c5692031ab2ac151 with master failed: RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes W….

See the job log for details.

@vdimir
vdimir force-pushed the vdimir/remove-cross-join-node branch from 216161d to 25769f1 Compare September 14, 2026 09:48
vdimir and others added 8 commits September 14, 2026 10:00
…utological pushdown copies, comma joins for parallel replicas

- The `cross_to_inner_join_rewrite = 2` check moves from `normalizeCommaJoins`
  into the join order optimizer: the two sides of a comma join must be connected
  by the equalities of the flattened graph, possibly through other relations
  (the SSB query joins `date` and `customer` only through `lineorder`). A comma
  join the optimizer leaves in place is an error in force mode and `Cross`
  otherwise. `normalizeCommaJoins` is deleted.
- The filter pushdown copies a `WHERE` equality over two keys equivalent to the
  same key of the other side as `k = k`; the statistics priced that as a real
  predicate (05045 estimated `e[0]`). The copy is dropped when the conjunct
  stays unsubstituted on the other side; 05045 is back to the master reference.
- Comma joins pass the parallel replicas gates like `INNER ALL`: the planner
  used to see them already rewritten (04651).
- Tests: 02564 SSB restored on the plan-level rewrite, 04673 nondeterministic
  restored, 02564_analyzer_cross_to_inner folded into 05175, join order without
  statistics pinned, new 05212 (parallel replicas over a comma join with a
  leftover cross product) and 05213 (tautological pushdown copy, null-safe keys).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…eyless joins via ConstantJoin, simpler force-mode check and pushdown rule

- Parallel replicas: `CROSS JOIN` and comma joins are treated alike, as
  `INNER ALL`, in all planner gates; the n-way cross join exclusion of
  PR #96848 is dropped, the leftmost table is coordinated instead
  (issue #74337 case added to 05212).
- A keyless `INNER` join becomes a cross product with a filter whichever
  `join_algorithm` is set, since `ConstantJoin` executes it; the hash-only
  gate on hyperedges in `mergeFilterIntoJoinCondition` is gone (05214).
- `cross_to_inner_join_rewrite = 2`: a cross product emitted by the join
  order optimizer for a graph containing a comma join is the error; the
  union-find connectivity check is replaced by that.
- The pushdown copy of a one-sided conjunct that turns into `k = k` on the
  other side is not made; the conjunct itself always stays on its own side.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…cal equivalence copies

The filter pushdown copies `t1.k = t2.k` to the other side of a join on
`t1.k = t3.k AND t2.k = t3.k` as `t3.k = t3.k`; the estimator prices that
copy as a real predicate. This is not new to the branch and only arises
when `WHERE` lists redundant pairwise equalities over one key set, so the
fix attempted in the previous commits is reverted with its test, and 05045
records the estimates the branch produces for such a `WHERE`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…s false

`ConditionSelectivityEstimator` handled a comparison only against a constant
or a set; `x = x` fell through as an unknown condition with selectivity 0.33.
The filter pushdown produces such atoms when it copies `t1.k = t2.k` to the
other side of a join on `t1.k = t3.k AND t2.k = t3.k` as `t3.k = t3.k`, and
several copies multiplied the estimate of `t3` down to nothing (05045: `e[0]`).
The reference of 05045 is back to the one on master.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
CI (01881_join_on_conditions_merge): `JOIN ... ON a OR b` under
`partial_merge` and `full_sorting_merge` must keep failing with
NOT_IMPLEMENTED / INVALID_JOIN_ON_EXPRESSION; the gate in
`can_convert_to_cross` is what enforces it, so it comes back together
with `allow_hyperedges` in `mergeFilterIntoJoinCondition`.

05175: the join-order check pins `use_hash_table_stats_for_join_reordering = 0`,
a same-shaped join of another test in the run fed it `l3[cache~200000]`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
/// A comma join with equalities in `WHERE` is an `INNER` join written differently; its rewrite is governed by
/// `cross_to_inner_join_rewrite`. `Cross` also comes from the planner itself (e.g. decorrelated subqueries),
/// so it follows the optimization setting like `Inner`.
if (kind == JoinKind::Comma ? !settings.cross_to_inner_join_rewrite : !settings.merge_filter_into_join_condition)

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.

cross_to_inner_join_rewrite = 0 used to suppress both comma and explicit CROSS JOIN rewrites in the analyzer pass (CrossToInnerJoinPass::isEnabled looked only at that setting). After this split, the explicit CROSS JOIN path now follows query_plan_merge_filter_into_join_condition instead, so a query like:

SELECT count()
FROM t1 CROSS JOIN t2
WHERE t1.a = t2.a
SETTINGS cross_to_inner_join_rewrite = 0

is still rewritten to INNER JOIN as long as plan optimizations stay on. That is a user-visible compatibility break for an existing setting, and the new tests only cover the comma form.

I think JoinKind::Cross still needs to honor cross_to_inner_join_rewrite, or this has to be treated as a backward-incompatible change with a compatibility path.

if (!is_in_operator && !func.getArgumentAt(0).isConstant()
&& func.getArgumentAt(0).getColumnName() == func.getArgumentAt(1).getColumnName())
{
if (func_name == "equals" || func_name == "lessOrEquals" || func_name == "greaterOrEquals")

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.

This shortcut is only sound when a self-comparison is actually a tautology. Nullable columns are not: x = x, x <= x, and x >= x return NULL for NULL rows, so inside a filter they behave like isNotNull(x), not ALWAYS_TRUE. Floating columns can also contain NaN, and ClickHouse's comparison execution treats comparisons with NaN as false as well.

With this branch, a pushed-down predicate like t.x = t.x now estimates 100% selectivity on Nullable or floating columns even when some rows are filtered out, which can keep obviously worse join orders. This needs a null/NaN guard (or an isNotNull model for nullable columns) plus focused coverage for self-comparisons on those types.

vdimir and others added 2 commits September 15, 2026 12:27
`getConjunctsList` walked the `and` chain with a stack and returned the conjuncts in reverse order,
so the join predicates a comma join got from `WHERE` came out reversed relative to the query text.
The runtime filter conditions inherited that order, and the PREWHERE optimizer then either kept it
(compact parts, no statistics) or sorted the two conditions by column size or selectivity, which made
`03580_join_runtime_filter` depend on the randomized part format and `use_statistics`. The conjuncts
now come in the order of the query text; the references of 03580 and 03835 are identical to master
again.

Under parallel replicas the materialized side of a `GLOBAL` join is prepared on the initiator, and a
comma join reaching that path was refused with `Unexpected global join kind: COMMA`
(`04516_join_reorder_duplicate_names_merge_expression`). A comma cannot carry `GLOBAL` in the query
text sent to the replicas, so the join becomes a `CROSS JOIN` there. Test 05218 covers it.

`04671_make_distributed_plan_join_to_in_disabled` pins `query_plan_remove_unused_columns`: the right
column the `WHERE` used stays in the join output until that pass drops it, and the conversion to `IN`
needs a right side without output columns.

`05176_distributed_plan_exchange_layout` records the nameless expression step left after the filter
moved into the join.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119259&sha=6c7de32f51ad6acc312a84ff5525b768c5d0712e&name_0=PR
PR: #119259

Co-Authored-By: Claude Fable 5.1 <[email protected]>
if (!allow_global_join_for_right_table || join_kind == JoinKind::Left || join_kind == JoinKind::Inner)
/// A comma cannot carry `GLOBAL` in the query text; the join is a cross join with the same meaning.
if (join_kind == JoinKind::Comma)
join_node->setKind(JoinKind::Cross);

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.

cross_to_inner_join_rewrite = 2 is supposed to reject a comma join that still has no equi-condition after planning, regardless of whether the join is executed locally or shipped to shards/replicas. This converts every shipped comma join to CROSS before the remote analyzer runs, so the remote path loses that distinction and never reaches the force-mode check.

The call chain is rewriteJoinToGlobalJoin -> buildQueryTreeForShard -> InterpreterSelectQueryAnalyzer::getSampleBlockAndPlannerContext(...) on the parallel-replicas path, and StorageDistributed::getQueryInfoForShard uses the same helper. A query like SELECT count() FROM t1, (SELECT k FROM t2) AS r WHERE t1.k > r.k SETTINGS cross_to_inner_join_rewrite = 2 can therefore fail locally but run as a slow GLOBAL CROSS JOIN once it goes through a shipped-query path.

I think the shipped tree needs to preserve "this originated as a comma join" until the remote plan enforces cross_to_inner_join_rewrite, or this helper needs to raise the same INCORRECT_QUERY before changing the kind.

This branch has not been deployed

No deployments
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-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants