Skip to content

Extract ConstantJoin from HashJoin - #108289

Merged
antaljanosbenjamin merged 33 commits into
masterfrom
separate-cross-join
Jul 24, 2026
Merged

antaljanosbenjamin merged 33 commits into
masterfrom
separate-cross-join

Conversation

@antaljanosbenjamin

@antaljanosbenjamin antaljanosbenjamin commented Jun 23, 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):

Added ConstantJoin for cartesian joins and analyzer-planned constant-predicate joins, so these queries no longer fail because of an incompatible join_algorithm setting when the analyzer is used.

Version info

  • Merged into: 26.8.1.93 (included in 26.8 and later)

@antaljanosbenjamin antaljanosbenjamin changed the title First attempt to extract CrossJoin from HashJoin Extract CrossJoin from HashJoin Jun 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [69a2538]

Summary: ✅


AI Review

Summary

This PR extracts cartesian and constant-predicate joins into ConstantJoin and wires that path through the analyzer/planner. The current head is close, but I still see one new FirstRowOnly performance regression and one remaining ordered-read correctness issue that was dismissed in discussion but is still present in the code.

Findings

⚠️ Majors

  • [src/Interpreters/ConstantJoin.cpp:885] In the FirstRowOnly modes (ANY INNER ... ON 1, RIGHT ANY ... ON 1, RIGHT SEMI ... ON 1), the result is fully determined by the first matching left row, but after this CAS succeeds nothing tells JoiningTransform to stop reading the rest of the probe side. Queries like SELECT count() FROM huge_l ANY INNER JOIN (SELECT 1 AS r) AS rt ON 1 SETTINGS enable_analyzer = 1 will still scan all of huge_l even though every later block can only return ConstantJoinEmptyResult.
    Suggested fix: add a post-first-match cancellation path (for example a dedicated IJoin/JoiningTransform hook) and cover it with a focused read_rows regression.

  • [src/Interpreters/ConstantJoin.cpp:885] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/108289#discussion_r3615435000] ConstantJoin still inherits preservesLeftBlockOrder() == true, but FirstRowOnly picks the first stream that wins the CAS, not the first row in global left-side order. optimizeReadInOrder can therefore keep ordered probe streams for ANY INNER ... ON 1 and return a later key for ORDER BY ... LIMIT 1.
    Suggested fix: either report preservesLeftBlockOrder() == false for FirstRowOnly plans or force a single probe stream when keepLeftPipelineInOrder() is requested.

Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 23, 2026
Comment thread src/Interpreters/CrossJoin.cpp Resolved
Just changing HashJoin -> CrossJoin and enforcing usage of HashJoin when sanity check is necessary for joined_block_split_single_row
Comment thread src/Interpreters/HashJoin/HashJoin.h Resolved
Comment thread src/Interpreters/ConstantJoin.cpp Resolved
Comment thread src/Interpreters/ConstantJoin.cpp Resolved
Comment thread src/Interpreters/ConstantJoin.cpp Resolved
@antaljanosbenjamin antaljanosbenjamin changed the title Extract CrossJoin from HashJoin Extract ConstantJoin from HashJoin Jun 29, 2026
03786_outer_to_semi_or_anti:  ConstantJoin handled matched LEFT SEMI as “emit left row + default right columns”. That broke optimizer-converted ANY LEFT JOIN -> LEFT SEMI when a removed post-join filter still
  needed the matched right column value internally. HashJoin semantics for SEMI are “emit a matching row from the other side”, not defaults.
  03788_hash_join_with_empty_right_side_skip_left_side: missing implementation of alwaysReturnsEmptySet
Goals:
- make it behave as HashJoin with any joins
- simplify logic
Comment thread src/Core/Settings.cpp Resolved
INSERT INTO constant_join_algorithm_t1 VALUES (1), (2);
INSERT INTO constant_join_algorithm_t2 VALUES (2), (3);

-- Constant joins use ConstantJoin independently of join_algorithm.

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 a behavioral change: previosly we returned NOT_IMPLEMENTED is the hash join algorithm wasn't enabled.

Comment on lines +203 to +205
any_left_true_take_last
1 20
2 20

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.

Previously this returned 1 10 and 2 10, beause join_any_take_last_row wasn't considered for constant joins. In another PR I fixed the usage of join_any_take_last_row and there and it should return the same.

Comment thread src/Interpreters/ConstantJoin.cpp Resolved
@antaljanosbenjamin
antaljanosbenjamin marked this pull request as ready for review July 2, 2026 15:42
Comment thread src/Interpreters/ConstantJoin.cpp Resolved
@vdimir vdimir self-assigned this Jul 2, 2026
@antaljanosbenjamin

Copy link
Copy Markdown
Member Author

Because there was a merge conflict in sync PR, I have to merge latest master.

{
/// Probe streams race here: exactly one matching block keeps its first row, the losers emit nothing.
bool expected = false;
if (has_seen_matching_rows.compare_exchange_strong(expected, true))

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.

Once FirstRowOnly wins this CAS, the result is already fully determined, but nothing tells JoiningTransform to stop reading the remaining probe side. Queries like SELECT count() FROM huge_l ANY INNER JOIN (SELECT 1 AS r) rt ON 1 SETTINGS enable_analyzer = 1 will still scan all of huge_l even though every later probe block can only return ConstantJoinEmptyResult; the same wasted scan happens for RIGHT ANY / RIGHT SEMI with a non-empty right side.

Please add a post-first-match short-circuit (for example via a dedicated IJoin/JoiningTransform hook that cancels the left side once this flag is set) and cover it with a focused read_rows regression.

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 687/734 (93.60%) · Uncovered code

Full report · Diff report

@antaljanosbenjamin
antaljanosbenjamin added this pull request to the merge queue Jul 24, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jul 24, 2026
@antaljanosbenjamin
antaljanosbenjamin added this pull request to the merge queue Jul 24, 2026
Merged via the queue into master with commit 622b852 Jul 24, 2026
179 of 180 checks passed
@antaljanosbenjamin
antaljanosbenjamin deleted the separate-cross-join branch July 24, 2026 14:55
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 24, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 24, 2026
…ouse#108289 design

Detect the constant-false ON condition and empty inputs on the logical join step
(where they are still visible, before splitFilter lowers them), but keep the
JoinStep in place and only replace the input sides that cannot contribute a row
with an empty ReadNothing source. This preserves join validation (an invalid
constant join over a Join-engine table still throws instead of being silently
short-circuited, fixing the 02498_storage_join_key_positions regression the
previous whole-join-replacement approach introduced) while still avoiding the
read of the non-contributing side.

The runtime ConstantJoin from ClickHouse#108289 only cancels the probe side after the
build side is filled, so the build side of a LEFT/LEFT ANTI join over a large
right table was fully read; this optimization removes it from the plan
(read_rows 20000010 -> 10 for such queries).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Jul 25, 2026
Master extracted cross joins out of `HashJoin` into `ConstantJoin` (#108289);
the reasoning in `getMinRequiredVersion` is unchanged, only the class name in
the comment was stale.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 26, 2026
…ws-assert

Resolve the conflict in src/Interpreters/HashJoin/HashJoin.cpp in favour of
master. PR ClickHouse#108289 extracted the cross join into src/Interpreters/ConstantJoin.cpp
and the code this PR changed no longer exists in HashJoin::addBlockToJoin: the
spill branch became ConstantJoin::trySpillRightBlock, which already bails out on
block_to_save.columns() == 0, and the two chassert(rows == block.rows()) guards
are gone. Both fixes of this PR are therefore already upstream, so only the
regression test remains.
@PedroTadim

Copy link
Copy Markdown
Member

@antaljanosbenjamin a setting for this optimization could help on testing?

@antaljanosbenjamin

Copy link
Copy Markdown
Member Author

a setting for this optimization could help on testing?

There is no setting here. If you write join conditions that are constant (eg.: 1, TRUE, 0, FALSE, NULL, 1 < 3, 5 > 3, etc) ConstantJoin will be used.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 29, 2026
The hoisted structure guard in optimizeUseNormalProjections was verified against
one more carrier of the same defect, found by the AST fuzzer on an unrelated pull
request (STID 0993-3a3c, AST fuzzer (amd_tsan) on ClickHouse#92472; also seen in
Stress test (arm_debug) on ClickHouse#108289).

Same root cause as the case already covered: ActionsDAG::updateHeader appends
every input the rebuilt query.dag does not consume, so unconsumed columns of
required_columns survive as pass-throughs and widen the projection-rewritten
stream past the header of the subplan it replaces. What differs is the consumer.
Here the leaked columns are real (not virtual), and the parent is the right side
of the inner correlated-decorrelation join, whose contract is a single column
(payload and id belong to the outer stream). So instead of the output port check
in JoiningTransform::prepare, the widened block trips the right-side structure
assert in ConstantJoin::addBlockToJoin. Which of the two fires depends only on
the settings: correlated_subqueries_use_in_memory_buffer = 0 gives the
ConstantJoin one, additionally setting correlated_subqueries_default_join_kind to
'left' gives the output port one.

Reproduced on unmodified master for both asserts, byte-identical to the CI
report (message, column dump including the sparse id column, and the whole frame
chain). It only surfaces when query_plan_remove_unused_columns is off, because
that optimization re-narrows the stream; CI reached it through
compatibility = '25.3'.

No source change was needed: removing only the hoisted blocksHaveEqualStructure
block from the fixed build makes both asserts fire again with the original
messages, and restoring it rebuilds bit-identically, which is what proves the
existing guard is what covers this carrier. The check was deliberately made on
the branch merged with current master rather than by comparing prebuilt binaries
of different vintages, since ConstantJoin.cpp does not exist at this branch's
original merge base.

The test pins query_plan_remove_unused_columns = 0 (otherwise the check is
vacuous), keeps id sparse-serialized and asserts that it is, and compares
projection-on against projection-off results so the skip path is shown to lose no
rows. No randomization tags are needed: 100 randomized runs pass.

While verifying this I confirmed that issue ClickHouse#112128 (correlated EXISTS under OR
with full_sorting_merge) is a different producer of the same symptom, since it is
unaffected by optimize_use_projections = 0. It is tracked separately.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ouse#108289 design

Detect the constant-false ON condition and empty inputs on the logical join step
(where they are still visible, before splitFilter lowers them), but keep the
JoinStep in place and only replace the input sides that cannot contribute a row
with an empty ReadNothing source. This preserves join validation (an invalid
constant join over a Join-engine table still throws instead of being silently
short-circuited, fixing the 02498_storage_join_key_positions regression the
previous whole-join-replacement approach introduced) while still avoiding the
read of the non-contributing side.

The runtime ConstantJoin from ClickHouse#108289 only cancels the probe side after the
build side is filled, so the build side of a LEFT/LEFT ANTI join over a large
right table was fully read; this optimization removes it from the plan
(read_rows 20000010 -> 10 for such queries).

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

Labels

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