Skip to content

Restore selected right join key from left under join_use_nulls - #119001

Merged
fm4v merged 10 commits into
masterfrom
vdimir/join-use-nulls-restore-right-key
Sep 16, 2026
Merged

fm4v merged 10 commits into
masterfrom
vdimir/join-use-nulls-restore-right-key

Conversation

@vdimir

@vdimir vdimir commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Closes: #118738

Changelog category (leave one):

  • Performance Improvement

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

  • LEFT and FULL JOIN with join_use_nulls = 1 use less memory when the right join key is selected in the query: the key is no longer stored twice on the build side.

Close #118738


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

Version info

  • Merged into: 26.9.1.1579 (included in 26.9 and later)
  • Backported to: 26.8.7.4, 26.7.11.4, 26.6.9.9

vdimir and others added 4 commits September 8, 2026 18:55
With `join_use_nulls = 1`, a right join key selected from a LEFT or FULL JOIN
was wrapped as `toNullable(key)` in the right pre-join actions, so `HashJoin`
stored a full `Nullable` copy of the key next to the key itself. The hash join
already knows how to emit a required right key from the matched left key with
NULL for unmatched rows, so `JoinStepLogical` now hands the join the plain key
and asks for a `Nullable` result via `TableJoin::nullable_right_keys`.

The optimization applies to single-clause equi-joins resolved within the hash
family; merge joins emit the stored key as is and keep the previous plan.

Closes: #118738

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`MergeJoin` takes the types of the required right keys from
`TableJoin::getRequiredRightKeys`, so a key asked for as `Nullable` is filled
from the stored plain column by `copyRightRange` and gets NULL for an unmatched
left row. `JoinStepLogical` therefore restores the selected right key for
`partial_merge` and `auto` too, which is the configuration in the issue; only
`full_sorting_merge` keeps the previous plan.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The legacy join step cast the right key to `Nullable` before the join and
joined on that single column, which was both the key and the output. Do the
same in `JoinStepLogical`: when a right key input has a `toNullable` output
node, that node becomes the key (`preferNullableRightKey`), and an input that
only feeds a used expression is no longer passed to the join as a column of its
own. The right side then carries one column, restored from the left key by the
join as before, for every join algorithm.

This replaces the `TableJoin::nullable_right_keys` approach of the previous
commits, so the `TableJoin`, `MergeJoin` and `joinTotals` changes are reverted.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Where the hash join keeps keys only in its arena the Nullable wrapper is a
whole extra payload column; where it saves key columns too, the wrapper shares
the data and only the byte count toward the spill threshold doubles.

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

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [efc86d7]

Summary: ✅


AI Review

Summary

This PR changes join_use_nulls planning so a selected right join key is joined on as toNullable(...) and the plain input is dropped from the right pre-join header. The functional cases look covered, but the current implementation still regresses hash-family joins on the very surface it claims to optimize: HashJoin now sees a Nullable build key and falls off its specialized map types, so I cannot approve it as a Performance Improvement.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/JoinStepLogical.cpp:866-895] preferNullableRightKey rewrites the build key itself to toNullable(x). HashJoin chooses its map type from the raw right_table_keys block before extractNestedColumnsAndNullMap peels Nullable, and the single-LowCardinality fast path inspects that wrapped column too (src/Interpreters/HashJoin/HashJoin.cpp:256-264, 288-326, 395-531; src/DataTypes/NullableUtils.cpp:65-110). As a result, selected right keys under join_use_nulls = 1 fall back from the specialized single-key key* / key_string / key_fixed_string / low_cardinality_key_* maps to generic hashed / two_level_hashed, and fixed-hash-table conversion plus shared fixed-hash-table runtime filters stop applying. That is a hot-path performance regression, not the promised optimization.
    Suggested fix: keep the original non-nullable build key for HashJoin method selection/storage and use the Nullable expression only for the output column, or move the method-selection logic in HashJoin to the peeled key consistently before relying on this rewrite.
Tests
  • ⚠️ [tests/queries/0_stateless/05137_join_use_nulls_right_key_restored.sql:19-85] The new stateless test only checks output types and plan headers, so it still passes when HashJoin has already fallen back to the generic map. For a Performance Improvement PR, please add focused proof that the optimized cases keep their specialized hash path, or attach before/after measurements showing that selecting the right key under join_use_nulls does not regress.
Final Verdict

Status: ❌ Block

Minimum required actions:

  1. Avoid forcing hash-family joins to choose their map from a Nullable build key, or change HashJoin so method selection happens from the peeled key with equivalent behavior for LowCardinality, fixed-hash conversion, and shared runtime filters.
  2. Add focused proof for the claimed improvement: either a test that distinguishes specialized vs generic hash paths, or a benchmark showing there is no regression for selected right keys under join_use_nulls.

LLVM Coverage Report

Measured on commit efc86d7.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 80.50% 80.50% +0.00%

Changed lines: Changed C/C++ lines covered: 50/52 (96.15%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 9, 2026
if (planning_context.is_storage_join || planning_context.is_prebuilt_hash_join)
return;

const auto * input = right_node.getNode();

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.

Rewriting the build key itself to toNullable(x) regresses the single-LowCardinality(String) / LowCardinality(FixedString) hash path. HashJoin only enables the dictionary-aware low_cardinality_key_* map for non-nullable LowCardinality keys (tryGetLowCardinalityMethod returns {} as soon as the dictionary's nested column is nullable), so this change turns a query that previously built on the plain LC key into one that falls back to the generic materialized path.

That means the exact surface this PR is trying to optimize can get slower for selected LC string keys under join_use_nulls = 1. I think preferNullableRightKey needs to skip that case, or preserve the original non-nullable LC key for map selection/storage and use the nullable expression only for the output column.

@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 9, 2026
A 1-byte external join limit made the grace join rehash without bound under
some randomized settings; the spilling wrapper is exercised by any non-zero
limit. Pin query_plan_join_swap_table on the EXPLAIN checks.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
/// The build-side key name is the rendezvous with the shared runtime filter descriptors, as in
/// `predicateOperandsToCommonType`.
String name_before = right_node.getColumnName();
right_node = JoinActionRef::transform({right_node}, [to_nullable](auto &, auto &&) { return to_nullable; });

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.

Rewriting the build key itself to toNullable(x) regresses more than the existing LowCardinality case. HashJoin::chooseMethod only keeps the specialized single-key key*, key_string, and key_fixed_string paths for plain build columns, and the separate low_cardinality_key_* fast path also bails once the dictionary becomes nullable (src/Interpreters/HashJoin/HashJoin.cpp:256-263, 395-531). So a query that previously built on plain UInt*, String, FixedString, or LowCardinality(String) now falls back to hashed / two_level_hashed just because the key is selected under join_use_nulls.

That also disables fixed-hash-table conversion and the shared fixed-hash-table runtime filter path, and on multi-disjunct joins there is no compensating memory win because required right keys are still kept as payload (HashJoin.cpp:247-253). I think preferNullableRightKey needs to preserve the original non-nullable build key for method selection/storage, or at least skip this rewrite for the specialized single-key hash cases.

@vdimir vdimir Sep 9, 2026 •

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.

Don't we omit nullmask and use nested column for Nullable key?

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.

The null map is stripped, but only later, inside build/probe. HashJoin chooses data->type from the raw right_table_keys column first (src/Interpreters/HashJoin/HashJoin.cpp:256-264, 319-325, 395-531), and only after that does extractNestedColumnsAndNullMap peel Nullable for insertion/lookup (src/Interpreters/HashJoin/HashJoin.cpp:1046-1048; src/DataTypes/NullableUtils.cpp:65-119).

So when preferNullableRightKey rewrites the RHS key to toNullable(x), chooseMethod still sees ColumnNullable (or LowCardinality(Nullable(...))): the plain isNumeric / ColumnString / ColumnFixedString fast paths no longer match, and tryGetLowCardinalityMethod explicitly returns {} once the dictionary nested column is nullable (src/Interpreters/HashJoin/HashJoin.cpp:516-517). That is why the hash-family method still falls back even though the null map is omitted later.

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.

Shouldn't we choose the hashtable type based on the peeled type that is actually used?

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.

Yes, conceptually that is the direction, but it needs to be implemented inside HashJoin itself rather than assumed by JoinStepLogical. Today the map choice still happens from the raw right_table_keys column before extractNestedColumnsAndNullMap strips Nullable, and the single-LowCardinality fast path also probes the wrapped column first (src/Interpreters/HashJoin/HashJoin.cpp:256-264, 288-320, 1046-1048). So until HashJoin makes all of those decisions from the peeled key consistently, rewriting the build key to toNullable(x) still changes behavior.

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing efc86d7f6 with master ea45f5612 (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, 23 s compile time in total, 7 of them have a recent master baseline.

Job report

vdimir and others added 3 commits September 9, 2026 15:45
`LEFT ANY JOIN` with `partial_merge` picks one of the two duplicate `c`
rows on the right, and which one depends on the order of equal keys
after sorting the right blocks. On debug builds libc++ randomizes that
order, so the test returned `30` or `31` at random. The query only needs
to show that `r.k` is restored, so it no longer selects `r.w`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119001&sha=9d66cefd4318ef79b43c3df3ff4a80baaf2a13e9&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
#119001

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Parallel replicas add Union, MergingAggregated and ReadFromRemoteParallelReplicas
steps to the plan, and each prints a `Header: __table2.k` line that the EXPLAIN
filter in the test picks up.

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

Co-Authored-By: Claude Fable 5.1 <[email protected]>
SELECT l.k, r.k, r.w FROM l LEFT JOIN r ON l.k = r.k ORDER BY ALL SETTINGS join_algorithm = 'full_sorting_merge';
SELECT '-- LowCardinality key';
SELECT l.k, r.k FROM l LEFT JOIN (SELECT toLowCardinality(k) AS k FROM r) AS r ON l.k = r.k ORDER BY ALL SETTINGS join_algorithm = 'hash';
SELECT toTypeName(r.k) FROM l LEFT JOIN (SELECT toLowCardinality(k) AS k FROM r) AS r ON l.k = r.k LIMIT 1 SETTINGS join_algorithm = 'hash';

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 only proves the output type, not the performance contract the PR claims. preferNullableRightKey rewrites the hash build key itself to toNullable(k), and buildPhysicalJoinImpl then drops the original input from the pre-join header, so HashJoin::chooseMethod now sees ColumnNullable / LowCardinality(Nullable(...)) and falls back from the specialized single-key key* / key_string / key_fixed_string / low_cardinality_key_* maps to generic hashed / two_level_hashed (src/Processors/QueryPlan/JoinStepLogical.cpp:848-878, 1758-1802; src/Interpreters/HashJoin/HashJoin.cpp:256-264, 319-325, 395-531). This test still passes in that regressed state. Can we add a focused check that pins the single-key hash path, or otherwise demonstrate that selecting the right key does not force the generic map?

alexey-milovidov and others added 2 commits September 10, 2026 18:36
The merge of master brought the descriptor struct that replaced std::vector<std::pair<String, String>> for shared runtime filter descriptors, and preferNullableRightKey still used the old shape, failing Build (arm_tidy) and Fast test.
@vdimir
vdimir marked this pull request as ready for review September 15, 2026 16:59
@fm4v
fm4v enabled auto-merge September 15, 2026 18:34
@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 8e920a71-b500-4b4a-b6f9-07aa50981310
  • MIRAI run: 39fe4004-1dbd-4352-8751-1d9a3ad1a1a1
  • PR check IDs:
    • clickbench_335227_1789498950
    • clickbench_335233_1789498950
    • clickbench_335239_1789498950
    • tpch_adapted_1_official_335250_1789498950
    • tpch_adapted_1_official_335283_1789498950
    • tpch_adapted_1_official_335297_1789498951

@fm4v
fm4v added this pull request to the merge queue Sep 16, 2026
Merged via the queue into master with commit 5ae6776 Sep 16, 2026
345 of 348 checks passed
@fm4v
fm4v deleted the vdimir/join-use-nulls-restore-right-key branch September 16, 2026 11:34
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 16, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 16, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Sep 16, 2026
Cherry pick #119001 to 26.6: Restore selected right join key from left under join_use_nulls
robot-clickhouse added a commit that referenced this pull request Sep 16, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Sep 16, 2026
Cherry pick #119001 to 26.7: Restore selected right join key from left under join_use_nulls
robot-clickhouse added a commit that referenced this pull request Sep 16, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Sep 16, 2026
Cherry pick #119001 to 26.8: Restore selected right join key from left under join_use_nulls
robot-clickhouse added a commit that referenced this pull request Sep 16, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 16, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@vdimir @fm4v — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

fm4v added a commit that referenced this pull request Sep 16, 2026
Backport #119001 to 26.8: Restore selected right join key from left under join_use_nulls
fm4v added a commit that referenced this pull request Sep 16, 2026
Backport #119001 to 26.7: Restore selected right join key from left under join_use_nulls
vdimir added a commit that referenced this pull request Sep 17, 2026
Backport #119001 to 26.6: Restore selected right join key from left under join_use_nulls
thevar1able pushed a commit to actueleai/ClickHouse that referenced this pull request Sep 21, 2026
…erge

With join_use_nulls = 1, a right join key that is also selected is joined on
as toNullable(key). toNullable returns makeNullableOrLowCardinalityNullable,
so for a LowCardinality(T) key the wrapper order is LowCardinality(Nullable(T))
rather than Nullable(LowCardinality(T)). preferNullableRightKey rebinds the
build key to that node, and predicateOperandsToCommonType has already returned
early on equal key types, so the only surviving asymmetry is
LowCardinality(Nullable(T)) against LowCardinality(T).

FullSortingMergeJoin::checkTypesOfKeys compared the key types after
removeNullable, which strips a top-level Nullable only, so it tolerated the
plain-String form of that rewrite and rejected the LowCardinality form with
TYPE_MISMATCH. This affected LEFT (depending on the join swap), FULL (either
swap) and ASOF LEFT, under both full_sorting_merge and
parallel_full_sorting_merge.

Widen the non-USING branch to the tolerance JoinCommon::checkTypesOfKeys
already has. FullMergeJoinCursor::setChunk calls
convertToFullColumnIfLowCardinality and then splits ColumnNullable into a
separate null map, unconditionally and identically for both sides, so a pair
differing only in those wrappers reduces to the bare column plus optional null
map that nullableCompareAt already compares correctly, and non-matched rows
still fill through the data type. The USING branch stays strict because
TableJoin::leftToRightKeyRemap makes allJoin insert right key values into a
column cloned from the left key, where ColumnUnique::uniqueInsertFrom would
turn a NULL into the empty-string placeholder.

The composition order matters: removeNullable(recursiveRemoveLowCardinality(t))
is required, because on LowCardinality(Nullable(T)) an inner removeNullable is
a no-op and leaves Nullable(T) after the LowCardinality strip.

Closes: ClickHouse#120424
Related: ClickHouse#119001
alexey-milovidov added a commit that referenced this pull request Sep 24, 2026
… matcher

Since #119001 the right key of a `LEFT` / `FULL` join under `join_use_nulls` is
`toNullable(x)` when the query also selects `x`. `findCommonPrimaryKeyPrefixByJoinKey`
then saw a monotonic wrapper and refused the pair, so `parallel_sorted_merge` lost its
primary-key-range sharding for `FULL JOIN ... USING` (`04760_sorted_merge_join_use_nulls`
failed in Fast test). `toNullable` keeps every value and a sharded primary key column is
never `Nullable` (`isSafePrimaryDataKeyType`), so match the argument instead.

Related: #119001

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AUTO JOIN regression after #104017: returned RHS String key retains duplicate Nullable payload and causes external writes

6 participants