Skip to content

fix ANY INNER JOIN with partial_merge - #104621

Closed
4ertus2 wants to merge 7 commits into
ClickHouse:masterfrom
4ertus2:fix-pmj-any-inner-join
Closed

4ertus2 wants to merge 7 commits into
ClickHouse:masterfrom
4ertus2:fix-pmj-any-inner-join

Conversation

@4ertus2

@4ertus2 4ertus2 commented May 11, 2026

Copy link
Copy Markdown
Contributor

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 ANY INNER JOIN result used with partial_merge algo

@scanhex12 scanhex12 added the can be tested Allows running workflows for external contributors label May 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bfa5eed]

Summary: ✅


AI Review

Summary

This PR changes MergeJoin::semiLeftJoin so ANY INNER JOIN with partial_merge emits only the first row from each equal-key range while advancing past the full range, plus adds coverage for right block splits. The right-block-split case is addressed, but the PR still does not enforce the ANY INNER JOIN contract across multiple left input blocks, so it can still return incorrect, block-size-dependent duplicates.

Findings
  • ❌ Blockers
    • [src/Interpreters/MergeJoin.cpp:1112] ANY INNER JOIN with default any_join_distinct_right_table_keys = 0 must return one row per matched key from both sides, but MergeJoin::joinBlock sorts and joins each incoming left block independently and semiLeftJoin only skips duplicate left keys within the current block. If duplicate left keys arrive in separate left blocks, each block emits one row for the same key; HashJoin avoids this with used flags, but MergeJoin has no cross-left-block emitted-key state. This keeps partial_merge results dependent on left block boundaries, e.g. max_block_size = 1.
      Suggested fix: keep emitted-key state for ANY INNER JOIN across left blocks, or make partial_merge reject this strictness until it can preserve the contract.
Tests
  • ⚠️ tests/queries/0_stateless/04340_any_inner_join_partial_merge_block_split.sql varies partial_merge_join_rows_in_right_blocks, but all duplicate left keys are still in one left input block. Add a focused regression that splits the same left key across left blocks, for example by probing from a source constrained with max_block_size = 1, and compare partial_merge against hash.
Final Verdict

Status: ❌ Block

Minimum required actions: fix cross-left-block duplicate suppression for ANY INNER JOIN under partial_merge, or explicitly reject that combination, and add the left-block-split regression.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 11, 2026
Comment thread src/Interpreters/MergeJoin.cpp Resolved
Comment thread src/Interpreters/MergeJoin.cpp Resolved
@4ertus2

4ertus2 commented May 11, 2026 •

Copy link
Copy Markdown
Contributor Author

It's probably not a full fix. If there could be blocks' splits with same key on a split border there could be duplicates too.

@vdimir vdimir self-assigned this May 13, 2026

@vdimir vdimir 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.

Since, as you mentioned, the change does not cover the case with block split, I'm not sure it's worth going with a partial fix and having non-deterministic results based on block size. We can think about forbidding ANY INNER for partial merge (as we do for ANY RIGHT, probably for the same reason that we cannot deduplicate the left side?). But that would be backward-incompatible and would require a setting, so I'm also not sure if it's worth doing.

@4ertus2

4ertus2 commented May 13, 2026 •

Copy link
Copy Markdown
Contributor Author

the change does not cover the case with block split

Even worse. As soon as left table is not fully sorted there would be duplicates between left table portions we are joining.

we cannot deduplicate the left side

We could. But only if we make key-visit map of the right table (or maybe for each right table block separately). Like it was in HashJoin (I'm not sure about its current state).

In fact currently partial_merge works only for LEFT ANY from this link. The PR is about to shrink 'left table rows' area from the link. I think it's interesting if it's faster. But it's probably better to disable partial_merge for ANY INNER JOIN at all.
I've made this PR cause I found unexpected result in tests in #100945.

@vdimir

vdimir commented May 13, 2026

Copy link
Copy Markdown
Member

But it's probably better to disable partial_merge for ANY INNER JOIN at all.

To keep queries compatible with older behavior, we probably will need to introduce a compatibility setting something along the lines of partial_merge_any_join_allow_left_duplicates. Which is a bit awkward, but it could preserve the old behavior when enabled via the compatibility setting.

@4ertus2

4ertus2 commented May 14, 2026

Copy link
Copy Markdown
Contributor Author

To keep queries compatible with older behavior, we probably will need to introduce a compatibility setting

I'm not sure I fully understand which behaviour we should to keep. Both variants are works not in sync with other ANY INNER JOIN algorithms.

Would it better if I mark the PR as DRAFT and you continue it with your vision?

@4ertus2
4ertus2 marked this pull request as draft May 14, 2026 12:16
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

# Conflicts:
#	src/Interpreters/MergeJoin.cpp
Comment thread src/Interpreters/MergeJoin.cpp Resolved
alexey-milovidov and others added 2 commits June 13, 2026 11:12
# Conflicts:
#	tests/queries/0_stateless/01881_join_on_conditions_hash.sql.j2
The previous fix set range.left_length = 1 for ANY INNER, which also
limited how far the left cursor advanced. As a result, when the right
rows of a single key were split across several right blocks (e.g. with
partial_merge_join_rows_in_right_blocks = 1), the same left key could be
emitted once per right block, producing block-size-dependent duplicates.

Now semiLeftJoin still emits only the first left row of the equal range
for ANY INNER, but advances the left cursor past the whole range. Because
left keys are contiguous and sorted, a matched key is never reconsidered
in later right blocks, so the result is one row per matched left key
regardless of the right block size, matching the hash join.

Add test 05017_any_inner_join_partial_merge_block_split.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

@vdimir I addressed the block-split concern in 46a57db instead of going with a partial fix.

The issue was that range.left_length = 1 also capped how far the left cursor advanced, so a key whose right rows span multiple right blocks could be emitted once per block (block-size-dependent duplicates). The new version still emits only the first left row of the equal range for ANY INNER, but advances the left cursor past the whole range. Because left keys are contiguous and sorted, once a key is matched it is never reconsidered in a later right block — so the result is one row per matched left key regardless of partial_merge_join_rows_in_right_blocks, and no cross-block emitted-key state is needed. This keeps the feature working and avoids a backward-incompatible change.

New test 05017_any_inner_join_partial_merge_block_split forces key splitting (partial_merge_join_rows_in_right_blocks = 1 and = 2) and checks the result is stable across block sizes and equal to hash. Also merged master (the branch was ~4 weeks behind). PTAL.


right_cursor.nextN(range.right_length);
left_cursor.nextN(range.left_length);
left_cursor.nextN(left_length);

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.

ANY INNER with the default any_join_distinct_right_table_keys = 0 promises one row per key from both sides, but this only skips duplicates within the current left block. joinBlock sorts each incoming left block independently and partial_merge_join_left_table_buffer_bytes is disabled, so if the same left key arrives in two left blocks this code emits it once per block. For example, left block 1 contains id = 1, left block 2 also contains id = 1, and the right side contains id = 1: hash can suppress the second row via its used flags, but this path has no cross-left-block state and returns two rows. Please either keep emitted-key state for ANY INNER across left blocks, or make partial_merge fall back/reject this strictness, and add a regression that splits duplicate left keys across blocks (for example with max_block_size = 1).

The new test was numbered 05017, far above the current maximum stateless
test number (04336), which `check_gaps_in_tests_numbers` flags as
`Gap (4336, 5017) > 100`. Renumber it to 04340 to close the gap.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104621&sha=46a57dba53f66101699abd40746a9e8133cc5247&name_0=PR&name_1=Style%20check

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

clickhouse-gh Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.10% 85.10% +0.00%
Functions 92.30% 92.40% +0.10%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 9/9 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@vdimir

vdimir commented Jun 15, 2026 •

Copy link
Copy Markdown
Member

@vdimir I addressed the block-split concern in 46a57db instead of going with a partial fix.

I believe issue with inter-block keys remains, tested with script:

#!/usr/bin/env -S ${HOME}/clickhouse client --queries-file


DROP TABLE IF EXISTS t1;
CREATE TABLE IF NOT EXISTS t1 ( `id` UInt64, `name` String, ) ENGINE = MergeTree ORDER BY id;

DROP TABLE IF EXISTS t2;
CREATE TABLE IF NOT EXISTS t2 ( `id` UInt64, `name` String, ) ENGINE = MergeTree ORDER BY id;

SYSTEM STOP MERGES t1;
SYSTEM STOP MERGES t2;

INSERT INTO t1 VALUES (1, 'A'), (2, 'B'), (3, 'C');
INSERT INTO t1 VALUES (1, 'D'), (2, 'E'), (4, 'F');

INSERT INTO t2 VALUES (1, 'a'), (2, 'b'), (3, 'c');
INSERT INTO t2 VALUES (1, 'd'), (2, 'e'), (4, 'f');

SELECT * FROM t1
ANY INNER JOIN t2 USING id
SETTINGS join_algorithm = 'partial_merge';

SYSTEM START MERGES t1;
SYSTEM START MERGES t2;
OPTIMIZE TABLE t1 FINAL;
OPTIMIZE TABLE t2 FINAL;

SELECT '--';

SELECT * FROM t1
ANY INNER JOIN t2 USING id
SETTINGS join_algorithm = 'partial_merge';


SELECT * FROM system.build_options
WHERE name = 'GIT_COMMIT_SUBJECT'
FORMAT PrettyCompact;
1       D       d
2       E       e
4       F       f
1       A       d
2       B       e
3       C       c
--
1       A       a
2       B       b
3       C       c
4       F       f
   ┌─name───────────────┬─value────────────────────────────────────────────────────────────────────────────────────────┐
1. │ GIT_COMMIT_SUBJECT │ Merge bfa5eed061fddfe76268362324b86870c3226e48 into eec0d05047dd1c5d9c457bddd7abed463096ae19 │
   └────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────┘

@vdimir

vdimir commented Jun 15, 2026

Copy link
Copy Markdown
Member

Proper implementation would require some kind of tracking keys, e.g. storing them in hash table, with will add signification overhead, and in that case it's better to use hash join

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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants