Repository navigation
Restore selected right join key from left under join_use_nulls - #119001
Conversation
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]>
|
Workflow [PR], commit [efc86d7] Summary: ✅
AI ReviewSummaryThis PR changes Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Minimum required actions:
LLVM Coverage ReportMeasured on commit efc86d7.
Changed lines: Changed C/C++ lines covered: 50/52 (96.15%) · Uncovered code |
| if (planning_context.is_storage_join || planning_context.is_prebuilt_hash_join) | ||
| return; | ||
|
|
||
| const auto * input = right_node.getNode(); |
There was a problem hiding this comment.
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.
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; }); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Don't we omit nullmask and use nested column for Nullable key?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Shouldn't we choose the hashtable type based on the peeled type that is actually used?
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 23 s compile time in total, 7 of them have a recent master baseline. |
`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'; |
There was a problem hiding this comment.
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?
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.
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
Cherry pick #119001 to 26.6: Restore selected right join key from left under join_use_nulls
Cherry pick #119001 to 26.7: Restore selected right join key from left under join_use_nulls
Cherry pick #119001 to 26.8: Restore selected right join key from left under join_use_nulls
|
@vdimir @fm4v — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Backport #119001 to 26.8: Restore selected right join key from left under join_use_nulls
Backport #119001 to 26.7: Restore selected right join key from left under join_use_nulls
Backport #119001 to 26.6: Restore selected right join key from left under join_use_nulls
…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
… 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]>
Closes: #118738
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
LEFTandFULL JOINwithjoin_use_nulls = 1use 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
26.9.1.1579(included in26.9and later)26.8.7.4,26.7.11.4,26.6.9.9