Skip to content

Parallel full sorting merge join (parallel_full_sorting_merge) - #109005

Merged
alexey-milovidov merged 49 commits into
masterfrom
parallel-full-sorting-merge-join
Aug 1, 2026
Merged

alexey-milovidov merged 49 commits into
masterfrom
parallel-full-sorting-merge-join

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 1, 2026 •

Copy link
Copy Markdown
Member

Resolves #48165

Adds a new join_algorithm value parallel_full_sorting_merge.

full_sorting_merge streams both sides and joins them with a single merge, so it keeps memory bounded but runs the merge on one thread — on many-core machines it is often slower than parallel_hash even though it uses far less memory. parallel_full_sorting_merge keeps the streaming, low-memory profile of a merge join but shards the join by the hash of the join keys into independent per-shard merge joins that run in parallel (up to max_threads).

A query-plan optimization (optimizeParallelFullSortingMergeJoin) switches each side's pre-join SortingStep to scatter the rows by the hash of the join keys into a fixed number of shards (max_threads) and sort each shard, then marks the join to run shard-by-shard, reusing the existing sharded pipeline (joinPipelinesYShapedByShards). Because the partitioning depends only on the join-key values — and FullSortingMergeJoin already requires matching key types — equal keys land in the same shard on both sides, so shards join independently. The result is unordered.

Unlike the by-primary-key-ranges sharding (query_plan_join_shard_by_pk_ranges), this works on unsorted inputs by scattering each side before sorting. Already-sorted inputs are not scattered by this rewrite; they fall back to a single merge join, while in-order MergeTree reads can still be sharded at the source by primary-key ranges. When a side reads a single stream the scatter still produces the fixed shard count on both sides, so joins between inputs with different parallelism (e.g. different part counts) stay co-partitioned.

Benchmark, 20M ⋈ 20M on UInt64 keys, max_threads = 8:

join_algorithm wall peak RSS
parallel_hash 1.27 s 3201 MB
parallel_full_sorting_merge 0.52 s 974 MB
full_sorting_merge (single merge) 0.76 s 552 MB

i.e. ~2.4× faster and ~3.3× less memory than parallel_hash, and ~1.5× faster than the single-threaded merge join.

Correctness is verified against the hash algorithm for INNER/LEFT/RIGHT/FULL joins, many-to-many keys, and join_use_nulls in 04492_parallel_full_sorting_merge_join.

Changelog category (leave one):

  • Performance Improvement

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

Added a new join_algorithm value parallel_full_sorting_merge: for hash-compatible equality joins, it shards a full sorting merge join by the hash of the join keys into independent per-shard merge joins running on all threads. It keeps the low, streaming memory usage of a merge join while parallelizing it (in a benchmark, ~2.4x faster and ~3.3x less memory than parallel_hash). ASOF joins fall back to a single full_sorting_merge; hash-incompatible key types (floating-point, JSON, Object, Dynamic) skip only the hash-scatter rewrite and can still be sharded at the source by primary-key ranges when query_plan_join_shard_by_pk_ranges is enabled. The result is not ordered.

Documentation entry for user-facing changes

  • Documentation is written (the new value is described in the join_algorithm setting).

Version info

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

alexey-milovidov and others added 4 commits June 30, 2026 23:48
Introduce a new `join_algorithm` value `parallel_full_sorting_merge`. For now it
creates the same `FullSortingMergeJoin` as `full_sorting_merge` (so it is a valid,
correct algorithm); a follow-up turns it into a hash-sharded set of independent
per-shard merge joins via a query-plan optimization.

Recognized in both the analyzer (`PlannerJoins`) and legacy (`ExpressionAnalyzer`)
join creation, and treated like `full_sorting_merge` for strict key-type matching.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Turn a `parallel_full_sorting_merge` join into a set of independent per-shard merge
joins keyed by the hash of the join keys, so the merge join runs on all threads
instead of a single one.

A new query-plan optimization `optimizeParallelFullSortingMergeJoin` finds each
`FullSortingMergeJoin` that uses the algorithm and, for a single-clause equi-join:
  - switches each side's pre-join `SortingStep` to `convertToScatteredFullSort`,
    which scatters the rows by the hash of the join keys into independent
    partitions and sorts each partition, emitting one sorted stream per shard;
  - marks the `JoinStep` with `enableJoinByLayers`, reusing the existing sharded
    pipeline (`joinPipelinesYShapedByShards`) to run one `MergeJoinTransform` per
    shard.

Because the partitioning depends only on the join-key values (and the key types
match - `FullSortingMergeJoin` requires it), equal keys land in the same shard on
both sides, so each shard joins independently. The output is unordered.

Unlike the by-primary-key-ranges sharding (`query_plan_join_shard_by_pk_ranges`),
this works on any sorted input, not only MergeTree read in order. When the input
has a single stream the scatter is skipped and it degrades to a single merge join.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The hash-sharded merge join scattered each side into `pipeline.getNumThreads()`
partitions, which differs per side when the two inputs read a different number of
streams (e.g. a table with 3 parts joined to a table with 1 part). That produced
unequal shard counts, so the sharded pipeline was not used and the plain merge
join then failed with "Join is supported only for pipelines with one output port".

Scatter both sides into a fixed number of shards (`max_threads`) regardless of how
many streams each side reads, via a new `SortingStep::scatter_partitions` used by
`convertToScatteredFullSort` and honored in `scatterByPartitionIfNeeded` (the
window-frame partitioned sort keeps using the pipeline thread count). Both sides
therefore produce the same number of co-partitioned sorted streams.

Add 04492_parallel_full_sorting_merge_join: it compares the algorithm against
`hash` for inner/left/right/full joins, `join_use_nulls`, and a row-level check,
using asymmetric part counts so the fixed-shard path is exercised.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Describe the new value in the `join_algorithm` setting (from which the settings
documentation is generated).

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

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [46b8863]

Summary: ✅


AI Review

Summary

This PR adds the parallel_full_sorting_merge join_algorithm, rewrites eligible merge joins into hash-sharded per-shard merge joins, and adds the guards/tests needed for the fallback cases where sharding would be incorrect or unsafe. On the current head, the earlier correctness gaps discussed in review are addressed, and I did not find any new remaining contract violations in the diff or current code. Residual caveat: I did not rerun a fresh local build/test matrix in this environment, so this approval relies on the current code review, the added stateless coverage, and the benchmark/test evidence already attached to the PR.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

Release-transition baseline: compared against the last 26.7 master because no 26.8 master baseline exists at or before the trusted base-commit anchor.

This PR adds a new opt-in join algorithm (parallel_full_sorting_merge) that only takes effect when explicitly listed in join_algorithm; at default settings the query-execution path is unchanged. ClickBench contains no joins and TPC-H ran with the default hash join, so none of the flagged queries exercise the changed code, and every delta sits on a thin baseline. All directional flags (both the reported improvements and regressions) have been downgraded to not_sure as run-to-run variance; the two remaining not_sure results are large but noisy and likewise unrelated to this change.

clickbench

⚠️ 13 inconclusive

Flagged queries (13 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 264 212 -19.7% <0.0001 This PR only adds the opt-in parallel_full_sorting_merge join algorithm, unused at default settings; ClickBench has no joins, so the -19.7% on Q4 is thin-baseline variance.
⚠️ 5 not_sure 374 247 -34.0% <0.0001 Off-path: the new join algorithm is opt-in and ClickBench runs no joins. The -34.0% on Q5 rests on a thin baseline and cannot be attributed to this diff.
⚠️ 9 not_sure 339 392 +15.6% <0.0001 The diff only touches an opt-in join path never exercised by this ClickBench SELECT, so the +15.6% is run-to-run variance on a thin baseline, not a regression.
⚠️ 10 not_sure 177 150 -15.3% <0.0001 Opt-in join algorithm code, unused at default settings and irrelevant to a join-free ClickBench query; the -15.3% on Q10 is thin-baseline noise.
⚠️ 11 not_sure 221 175 -20.8% <0.0001 This PR cannot touch a join-free ClickBench query at default settings, so the -20.8% on Q11 is thin-baseline variance rather than a real improvement.
⚠️ 16 not_sure 766 856 +11.7% <0.0001 The changed code is an opt-in join algorithm; ClickBench has no joins, so the +11.7% on Q16 is thin-baseline run-to-run variance, not a PR-caused regression.
⚠️ 17 not_sure 520 590 +13.3% <0.0001 Q17 is intrinsically noisy and off-path for this opt-in join change on a join-free benchmark, so the +13.3% is variance, not a regression.
⚠️ 18 not_sure 1262 1487 +17.8% <0.0001 Off-path for an opt-in join algorithm on a join-free ClickBench query; with only 31 vs 12 samples the +17.8% on Q18 is thin-baseline variance.
⚠️ 23 not_sure 169 74 ×2.3 faster <0.0001 The measurements were very noisy and the query does not exercise the opt-in join path this PR adds, so the x2.3 faster reading on Q23 is not a PR effect.
⚠️ 28 not_sure 2788 1094 ×2.5 faster <0.0001 Off-path for this opt-in join-algorithm PR on a join-free benchmark; the x2.5 faster reading is a noisy, borderline signal, not a PR effect.
⚠️ 31 not_sure 377 419 +11.1% <0.0001 The diff only adds an opt-in join algorithm unused here, so the +11.1% on Q31 is thin-baseline run-to-run variance rather than a regression.
⚠️ 33 not_sure 1448 1364 -5.8% <0.0001 A join-free ClickBench query cannot be affected by this opt-in join change, so the -5.8% on Q33 is thin-baseline noise.
⚠️ 34 not_sure 2958 1368 ×2.2 faster <0.0001 The baseline was very noisy and the query is off-path for this opt-in join algorithm, so the x2.2 faster reading on Q34 is not attributable to the PR.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 652 564 -13.6% <0.0001 This PR only adds an opt-in parallel merge join; TPC-H ran with the default hash join, so the -13.6% on Q7 is thin-baseline variance, not a PR effect.
⚠️ 20 not_sure 406 115 ×3.5 faster <0.0001 The new join algorithm is opt-in and TPC-H ran with the default hash join, so this large but noisy x3.5 faster reading on Q20 is not a PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 449556f7-9257-44b5-a5c4-9e2ba2ed3688
  • MIRAI run: 497d0907-0e1c-4c95-93e4-e5f38bcc8484
  • PR check IDs:
    • clickbench_1202249_1785556919
    • clickbench_1202256_1785556919
    • clickbench_1202266_1785556919
    • tpch_adapted_1_official_1202277_1785556919
    • tpch_adapted_1_official_1202293_1785556919
    • tpch_adapted_1_official_1202319_1785556919

`optimizeParallelFullSortingMergeJoin` sharded every `FullSortingMergeJoin`
that requested `parallel_full_sorting_merge` by the hash of the whole join-key
list, without excluding two cases the sharding cannot handle:

* `ASOF` joins: the trailing key is the inequality key, so candidate rows with
  the same equality key but different `ASOF` values hash into different shards
  and the per-shard merge join misses the closest match, returning wrong
  results. The primary-key-range sharding path (`optimizeJoinByShards`) already
  excludes `ASOF`; add the same `JoinStrictness::Asof` guard here.

* Read-in-order sorts: `applyOrder` runs before this pass and can turn a
  merge-join `SortingStep` into `FinishSorting` fed by an already in-order read
  (emitting virtual-row chunks with `read_in_order_use_virtual_row = 1`). The
  scatter path expects a full sort of unsorted input, so only convert steps that
  are still `SortingStep::Type::Full`; in-order MergeTree reads are sharded by
  the primary-key-range path instead.

Adds `04493_parallel_full_sorting_merge_join_no_shard_cases`, which verifies
both cases match the `hash` algorithm (the `ASOF` case returns wrong results
without the guard).

Addresses the AI review Block verdict on
#109005

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

Copy link
Copy Markdown
Member Author

Addressed the AI review Block verdict in 569b478.

ASOF (blocker) — confirmed real. FullSortingMergeJoin::isSupported accepts ASOF (Inner/Left), so an ASOF join with join_algorithm = 'parallel_full_sorting_merge' reached optimizeParallelFullSortingMergeJoin, which sharded by the hash of the whole key list — including the trailing inequality key — scattering candidate rows for the same equality key into different shards. Added a strictness() != JoinStrictness::Asof guard, matching the primary-key-range path (optimizeJoinByShards). The new test 04493_parallel_full_sorting_merge_join_no_shard_cases shows the ASOF join returns wrong results without the guard and matches hash with it.

Read-in-order virtual rows (major). The pass now only converts sort steps that are still SortingStep::Type::Full. applyOrder runs before this pass (optimizeTree.cpp) and can turn a merge-join SortingStep into FinishSorting fed by an in-order read (with read_in_order_use_virtual_row = 1 it emits virtual-row chunks). In-order MergeTree reads are sharded by the primary-key-range path instead. For the record: I could not reproduce an actual failure — EXPLAIN PIPELINE confirms virtual rows do flow into ScatterByPartitionTransform, but the pipeline contains a RemoveVirtualRowTransform and the query returned correct results across settings (including read_in_order_use_virtual_row_per_block = 1). The guard is still the correct division of labor between the two sharding passes; 04493 includes a read_in_order_use_virtual_row = 1 case.

Both changes verified locally (debug build): 04493 and the existing 04492_parallel_full_sorting_merge_join both pass.

Comment thread src/Interpreters/ExpressionAnalyzer.cpp Resolved
With `enable_analyzer = 0` the pre-join sorts for a merge join are built in
`InterpreterSelectQuery` without the `is_sorting_for_merge_join` mark, while
the analyzer path (`addSortingForMergeJoin` in `JoinStepLogical`) always sets
it. `optimizeParallelFullSortingMergeJoin` only rewrites sort children that are
marked `is_sorting_for_merge_join`, so with the legacy analyzer the new
`parallel_full_sorting_merge` algorithm silently degraded to a single
`FullSortingMergeJoin` instead of the promised hash-sharded parallel merge join.

Mark the legacy pre-join sorts the same way as the analyzer path. This is
semantically correct (the sort is done locally before a merge join) and makes
the two paths consistent. The only other consumers of the flag are analyzer-only
(`findQueryForParallelReplicas`) or gated behind `query_plan_join_shard_by_pk_ranges`
(off by default, `FinishSorting` type), so existing `full_sorting_merge` queries
are unaffected.

Add `04494_parallel_full_sorting_merge_join_legacy_analyzer`, which checks via
`EXPLAIN PIPELINE` (not just result equality) that with `enable_analyzer = 0` and
`max_threads > 1` the sharded pipeline (`ScatterByPartitionTransform` on both
sides) is actually chosen, that plain `full_sorting_merge` is not scattered, and
that the sharded result matches `hash`.

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

Copy link
Copy Markdown
Member Author

Addressed the AI review Changes requested verdict in 85055be.

Legacy analyzer no-op (major) — confirmed real. With enable_analyzer = 0, the pre-join sorts for a merge join are built in InterpreterSelectQuery without the is_sorting_for_merge_join mark, whereas the analyzer path (addSortingForMergeJoin in JoinStepLogical) always sets it. optimizeParallelFullSortingMergeJoin only rewrites marked sort children, so with the legacy analyzer parallel_full_sorting_merge silently ran as a single FullSortingMergeJoin. Now the legacy pre-join sorts are marked the same way as the analyzer path — semantically correct (the sort is local, before a merge join) and consistent between the two paths. The flag's only other consumers are analyzer-only (findQueryForParallelReplicas) or gated behind query_plan_join_shard_by_pk_ranges (off by default, FinishSorting type), so existing full_sorting_merge legacy queries are unaffected (02000_join_on_const, 02962_join_using_bug_57894 still pass).

Test (requested). Added 04494_parallel_full_sorting_merge_join_legacy_analyzer, which proves via EXPLAIN PIPELINE (not just result equality) that with enable_analyzer = 0, max_threads = 4 the sharded pipeline is chosen: ScatterByPartitionTransform appears on both join sides for parallel_full_sorting_merge and is absent for plain full_sorting_merge, plus a result-equality check against hash. The join is on a non-ORDER BY column so a full sort (the scatter path) is built rather than read-in-order.

`parallel_full_sorting_merge` shards a full sorting merge join by the hash of the
join keys (`ScatterByPartitionTransform` -> `IColumn::computeHashInto`), while the
merge join itself matches keys with `compareAt`. For floating-point keys these
disagree: `-0.0` and `+0.0` (and NaNs) compare equal for the merge but hash
differently, so equal keys could be scattered into different shards and the per-shard
merge join would miss the match, returning fewer rows than the `full_sorting_merge`
algorithm this one is documented to mirror.

`optimizeParallelFullSortingMergeJoin` now skips sharding whenever a join key is (or
contains, via `Nullable`/`LowCardinality`/`Array`/`Tuple`/`Map`) a floating-point
type, falling back to a single merge join. Integer and other keys whose hash is
consistent with `compareAt` still shard.

This addresses the AI review Block verdict on
#109005 .

Add `04495_parallel_full_sorting_merge_join_float_keys`, which checks that signed-zero
float keys (plain and `Nullable`) match `full_sorting_merge` and are not scattered,
while an integer key still is.

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

Copy link
Copy Markdown
Member Author

Addressed the AI review Block verdict in 6217029.

Floating-point join keys (blocker) — confirmed real. parallel_full_sorting_merge selects a shard by the hash of the key's byte representation (ScatterByPartitionTransform → IColumn::computeHashInto), but the merge join matches keys with compareAt. For floats these disagree: -0.0 and +0.0 (and NaNs) compare equal for the merge but hash differently, so equal keys were scattered into different shards and the per-shard merge join missed the match. Reproduced against the current binary: a Float64 inner join of -0.0 against +0.0 returns 1 row with full_sorting_merge (and the sharded result diverged by hundreds of millions of rows on a larger dataset) but 0 with parallel_full_sorting_merge.

Fix. optimizeParallelFullSortingMergeJoin now skips sharding whenever a join key is (or contains, through Nullable/LowCardinality/Array/Tuple/Map) a floating-point type, and runs a single merge join — exactly like full_sorting_merge. Integer and other keys whose hash agrees with compareAt still shard (verified by an EXPLAIN PIPELINE control in the test). This mirrors how the same file already excludes ASOF and read-in-order cases.

Test. 04495_parallel_full_sorting_merge_join_float_keys checks that signed-zero Float64 and Nullable(Float64) keys match full_sorting_merge and are not scattered, while an integer key still is. The reference is full_sorting_merge, not hash (which does not treat -0.0 and +0.0 as equal).

`parallel_full_sorting_merge` shards a `FullSortingMergeJoin` by the hash of
the join key (`ScatterByPartitionTransform` -> `IColumn::computeHashInto`, a
`WeakHash32`), but the merge join matches keys with `compareAt`. For
`Object('json')` / `JSON` keys the two disagree: `ColumnObject::compareAt`
compares the logical path/value map, while `ColumnObject::computeHashInto`
hashes the physical layout - whether a given path is stored as a typed/dynamic
subcolumn or serialized into `shared_data` (its own comment states it "does NOT
guarantee equal hashes for a logically equal object whose paths are split
differently"). The same logical object stored with different layouts on the two
sides therefore hashes into different shards, so the per-shard merge join misses
the match and `parallel_full_sorting_merge` returns fewer rows than
`full_sorting_merge` (which compares logically).

`JSON`/`Object` keys are reachable: `FullSortingMergeJoin` does not reject them,
and `TableJoin::inferJoinKeyCommonType` only rejects `Dynamic` keys via
`hasDynamicType`, whose `DataTypeObject::forEachChild` visits only the typed
paths.

Extend `joinKeyTypeBreaksHashSharding` to also treat `Object`/`JSON` as breaking
hash sharding (at the top level or nested inside
`Nullable`/`LowCardinality`/`Array`/`Tuple`/`Map`), so such a join runs as a
single merge join, exactly like `full_sorting_merge`.

New test `04496_parallel_full_sorting_merge_join_json_keys`: with
`max_dynamic_paths = 1` the same `{"a": v}` object is stored as a dynamic
subcolumn on one side and overflows into `shared_data` on the other; the sharded
join must still match `full_sorting_merge` (returns 0 rows instead of 2000
without the fix) and must not scatter, while an integer control key still
scatters.

#109005 .

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

Copy link
Copy Markdown
Member Author

Addressed the AI review (Changes requested) in e74fca2.

parallel_full_sorting_merge could return fewer rows than full_sorting_merge for Object('json') / JSON join keys: the shard is chosen by ColumnObject::computeHashInto (layout-dependent — same logical object hashes differently when a path is a dynamic subcolumn on one side and in shared_data on the other), while the merge join matches with the logical ColumnObject::compareAt. Reproduced on a debug build (JSON(max_dynamic_paths = 1)): the sharded join returned 0 rows versus 2000 for full_sorting_merge.

Fix: extended joinKeyTypeBreaksHashSharding to also treat Object/JSON as breaking hash sharding (top level or nested), so such joins run as a single merge join, matching the float-key exclusion. Added regression test 04496_parallel_full_sorting_merge_join_json_keys; existing 04492–04495 still pass.

`join_algorithm` is an ordered priority list: the first algorithm that supports
the join is the one that runs. Both `full_sorting_merge` and
`parallel_full_sorting_merge` build the same `FullSortingMergeJoin` object, so
the query-plan rewrite that shards the join into per-shard merge joins
(`optimizeParallelFullSortingMergeJoin`) could not tell the two apart: it gated
on `TableJoin::isEnabledAlgorithm(PARALLEL_FULL_SORTING_MERGE)`, which is true
whenever the parallel variant appears *anywhere* in the list.

As a result `join_algorithm = 'full_sorting_merge,parallel_full_sorting_merge'`
selected plain `full_sorting_merge` first (the parallel variant being only an
unreached fallback), yet was still rewritten into the sharded, unordered path -
violating the priority-list contract and silently changing behavior and
performance.

Carry the selected algorithm into the join object: `FullSortingMergeJoin` now
records whether it was created for `PARALLEL_FULL_SORTING_MERGE` (set from the
`algorithm` value in `chooseJoinAlgorithm` / `tryCreateJoin` on both the
analyzer and legacy-analyzer paths, and preserved through `clone`), exposed as
`FullSortingMergeJoin::isParallel`. The optimizer now shards only when that flag
is set instead of checking list membership.

This addresses the AI review "Changes requested" verdict on
#109005 .

Add `04497_parallel_full_sorting_merge_join_priority_order`, which checks via
`EXPLAIN PIPELINE` (on both analyzers) that `parallel_full_sorting_merge` -
alone or first in the list - is scattered, while
`full_sorting_merge,parallel_full_sorting_merge` and plain `full_sorting_merge`
are not, and that all variants return the same result.

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

Copy link
Copy Markdown
Member Author

Addressed the AI review Changes requested verdict in 03057cd.

Priority-list contract (major) — confirmed real. join_algorithm is an ordered priority list: the first algorithm that supports the join runs. Both full_sorting_merge and parallel_full_sorting_merge build the same FullSortingMergeJoin, so optimizeParallelFullSortingMergeJoin could not distinguish the two — it gated the sharded rewrite on TableJoin::isEnabledAlgorithm(PARALLEL_FULL_SORTING_MERGE), i.e. presence of the parallel variant anywhere in the list. So join_algorithm = 'full_sorting_merge,parallel_full_sorting_merge' selected plain full_sorting_merge first (the parallel variant being only an unreached fallback) yet was still rewritten into the sharded, unordered path — violating the ordering contract.

Fix. The selected algorithm is now carried into the join object. FullSortingMergeJoin records whether it was created for PARALLEL_FULL_SORTING_MERGE (set from the algorithm value in chooseJoinAlgorithm/tryCreateJoin on both the analyzer and the legacy-analyzer path, and preserved through clone), exposed as FullSortingMergeJoin::isParallel. The optimizer shards only when that flag is set, instead of on join_algorithm list membership. The require_strict_keys_match uses of isEnabledAlgorithm(...) in TableJoin are left as-is (correct for both variants).

Test. 04497_parallel_full_sorting_merge_join_priority_order proves via EXPLAIN PIPELINE — on both analyzers — that full_sorting_merge,parallel_full_sorting_merge and plain full_sorting_merge do not introduce ScatterByPartitionTransform, while parallel_full_sorting_merge alone and parallel_full_sorting_merge,full_sorting_merge (parallel first) do, plus a result-equality check across all variants. 04492–04496 still pass; a debug build compiles clean.

`parallel_full_sorting_merge` selects a shard by the hash of the join
key (`ScatterByPartitionTransform` -> `IColumn::computeHashInto`), while
`FullSortingMergeJoin` matches keys with `compareAt`. For `Dynamic` keys
the two disagree: `ColumnDynamic::compareAt` compares the logical value,
but `ColumnDynamic::computeHashInto` hashes the raw variant storage,
which is explicitly documented as not equal for logically-equal values
stored with different variant layouts (a typed variant on one side vs the
shared variant on the other). So equal `Dynamic` keys can scatter into
different shards and the per-shard merge join misses the match, returning
fewer rows than the `full_sorting_merge` algorithm this one mirrors.

A plain `Dynamic` join key is rejected earlier by
`TableJoin::inferJoinKeyCommonType`, but only when
`allow_dynamic_type_in_join_keys = 0` (the default); with that
compatibility setting enabled a `Dynamic` key (or a compound key
containing `Dynamic`) reaches the rewrite. Generalize
`joinKeyTypeBreaksHashSharding` to also reject `Dynamic`, alongside the
existing floating-point and `JSON`/`Object` exclusions, at the top level
or nested inside `Nullable`/`LowCardinality`/`Array`/`Tuple`/`Map`/
`Variant`.

Reproduced against the current binary (`clickhouse local`, MergeTree,
`Dynamic(max_types = 1)`): the same `Int64` value stored as a typed
variant on the left and overflowed into `shared_data` on the right made
`parallel_full_sorting_merge` return 24 rows instead of the 100 of
`full_sorting_merge`.

New test `04498_parallel_full_sorting_merge_join_dynamic_keys` (with
`allow_dynamic_type_in_join_keys = 1`, including nested `Array(Dynamic)`).

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

Copy link
Copy Markdown
Member Author

Addressed the AI review Changes requested verdict in aa8a945.

Dynamic join keys (blocker) — confirmed real. parallel_full_sorting_merge selects a shard by the hash of the join key (ScatterByPartitionTransform -> IColumn::computeHashInto), but the merge join matches keys with compareAt. For Dynamic keys the two disagree: ColumnDynamic::compareAt compares the logical value, while ColumnDynamic::computeHashInto hashes the raw variant storage, which is explicitly documented as not equal for logically-equal values stored with different variant layouts (a typed variant on one side vs the shared variant on the other). A plain Dynamic key is rejected earlier by TableJoin::inferJoinKeyCommonType, but only when allow_dynamic_type_in_join_keys = 0 (the default); with that compatibility setting enabled a Dynamic key (or a compound key containing Dynamic) reached the rewrite and equal keys could scatter into different shards, dropping matches.

Reproduced against the current binary (clickhouse local, MergeTree, Dynamic(max_types = 1)): the same Int64 value stored as a typed variant on the left and overflowed into shared_data on the right made parallel_full_sorting_merge return 24 rows versus 100 for full_sorting_merge.

Fix: joinKeyTypeBreaksHashSharding now also rejects Dynamic (WhichDataType::isDynamic), alongside the existing floating-point and JSON/Object exclusions, at the top level or nested through IDataType::forEachChild. New test 04498_parallel_full_sorting_merge_join_dynamic_keys (with allow_dynamic_type_in_join_keys = 1, including a nested Array(Dynamic) compound key) confirms the sharded join now matches full_sorting_merge and is no longer scattered, while an integer control key still shards. Existing tests 04492–04497 still pass.

Comment thread src/Core/Settings.cpp Resolved
Address the AI review comment on `src/Core/Settings.cpp`: the previous
`join_algorithm` description promised unconditional hash sharding, but the
implementation deliberately falls back to a single `full_sorting_merge` for
`ASOF` joins, read-in-order (`FinishSorting`) inputs, and hash-incompatible
key types (floating-point / `JSON` / `Object` / `Dynamic`). Soften the setting
text to say that only hash-compatible equality joins are sharded and that
unsupported cases transparently fall back to the single merge-join path, so
the public documentation matches the behavior we rely on for correctness.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review Changes requested verdict in 912c0a6.

Documentation over-promise (major) — confirmed. The parallel_full_sorting_merge description in src/Core/Settings.cpp documented unconditional hash sharding, but the implementation deliberately falls back to a single full_sorting_merge for ASOF joins, read-in-order (FinishSorting) inputs, and hash-incompatible key types (floating-point / JSON / Object / Dynamic), so a user could set join_algorithm = 'parallel_full_sorting_merge' and see no ScatterByPartitionTransform with no indication that the fallback is expected.

Fix: reworded the setting text to state that only hash-compatible equality joins are sharded and that unsupported cases transparently fall back to the single merge-join path, so the public docs match the behavior we rely on for correctness. Documentation-only change, no behavior change.

… plan

`optimizeParallelFullSortingMergeJoin` can convert a merge-join `SortingStep`
into a scattered full sort (`convertToScatteredFullSort`), giving it a non-empty
`partition_by_description`. Such a step is not serializable for remote execution
(`SortingStep::isSerializable`), so if it reached a distributed-plan fragment,
`QueryPlan::convertToDistributed` would reject the query with `... is not
serializable for remote execution`.

In practice the pass already cannot fire while a distributed plan is built: a
distributed plan keeps its joins logical (`convertLogicalJoinToPhysical` returns
early on `make_distributed_plan`) and this pass only matches a physical
`JoinStep`, so a `parallel_full_sorting_merge` join under `make_distributed_plan`
stays a single (serializable) merge join and is physicalized per fragment on the
worker. A multi-stage distributed plan for such a join passes
`assertFragmentSerializable` and returns the same result as `full_sorting_merge`.

Guard the pass explicitly on `!make_distributed_plan` so the invariant (no
scattered sort in a distributed fragment) is documented and preserved even if
join physicalization is ever reordered. Local single-fragment distributed plans
are re-optimized with `make_distributed_plan = false` and still get sharded, so
this does not lose parallelism there.

Also tighten the `parallel_full_sorting_merge` documentation: read-in-order
(`FinishSorting`) inputs are skipped by this hash-sharding pass but can still be
parallelized by the primary-key-range pass when
`query_plan_join_shard_by_pk_ranges` is enabled, and distributed plans are now
listed among the skipped cases.

This addresses the AI review "Request changes" verdict on the pull request.

New test `04499_parallel_full_sorting_merge_join_distributed_plan`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
alexey-milovidov and others added 2 commits July 30, 2026 16:53
…e join

- New test `04657_parallel_full_sorting_merge_join_set_on_the_fly`: with
  `max_rows_in_set_to_optimize_join > 0`, both planners insert
  `CreateSetAndFilterOnTheFlyStep` below the pre-join sorts, so the sharded
  rewrite fires on top of it. The test pins that both optimizations coexist
  in the pipeline (set/filter transforms + two scatters), that the original
  ping-pong deadlock shape (`04007`, issue #57728) terminates with a correct
  count under `parallel_full_sorting_merge`, and that filtered results match
  the `hash` algorithm, on both analyzers.
- `query_plan_join_shard_by_pk_ranges` description: list
  `parallel_full_sorting_merge` among the supported algorithms (the pass
  matches the `FullSortingMergeJoin` implementation, which both merge-join
  algorithm values build), fixing the contradiction with the
  `parallel_full_sorting_merge` paragraph.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage on 206f3dc28db (all four reds unrelated to this PR; branch updated with master and the AI-review items addressed in cfe080cbabf):

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated both. Neither needs a new PR from me; details and evidence below.

Stress test (amd_tsan), Block structure mismatch (STID 0993-3a3c) - fixing PR is open: #112205

I pulled the aborting query from that job's fatal.log rather than trusting the reported Failed query, because the STID is a hash bucket that pools several distinct query shapes. Single fault in the log, and it matches the sub-signature #112205 fixes exactly: empty LHS dump, RHS a single Const __join_result_dummy UInt8, aborting at ConstantJoin.cpp:230 via FillingRightJoinSideTransform::work, carrier 02564_analyzer_cross_to_inner.sql.

Root cause: when two count()-pruned join children both carry __join_result_dummy, buildPhysicalJoinImpl declares its name_to_nodes map inside the per-child loop, so the right child's lookup restarts and returns the left node. The dedup pass drops the repeat, the right DAG ends up with zero outputs, and the right sample block is empty while the pipeline still physically carries the dummy. #112205 hoists the map above the child loop.

One caveat worth stating: a second sub-signature shares this STID and the same three stack frames (LHS a real column at size 0, RHS the same name repeated). #112205 does not cover it and I am tracking it separately, but it is not what your job hit.

AST fuzzer (amd_debug), UNIQUE KEY encoding: ColumnSparse/ColumnReplicated unsupported (STID 0250-39d6) - already fixed on master by #109010

This one was real, and it was fixed by JingYanchao's #109010 ("Move UNIQUE KEY comparable serialization into IColumn"), merged 2026-07-29T03:32:02Z. Your run tested merge commit d4f986f8, whose master parent is e3292763 from 2026-07-29T00:00:57Z - about three and a half hours before #109010 landed. So the failure is genuine but pre-dates the fix in that build:

  • the throw string is present in UniqueKeyEncoding.cpp at e3292763 and absent on master today
  • Move UNIQUE KEY comparable serialization into IColumn #109010 deleted the whole dispatchNonNullableColumnWise type-dispatch (394 lines out of that file) and moved encoding into per-column batchSerializeAsComparable overrides
  • CIDB has exactly one occurrence of 0250-39d6 in 45 days: your run

I confirmed the behaviour change empirically on a master build whose UniqueKeyEncoding.cpp, IColumn.cpp and ColumnSparse.cpp are byte-identical to origin/master. A UNIQUE KEY column that is genuinely Sparse-serialized (verified via system.parts_columns.serialization_kind) now inserts fine, and an arrayJoin-fed insert that produces a lazily-replicated column also succeeds. Where a sparse column still reaches the encoder unmaterialized, master raises Code: 48 ... Method serializeAsComparable is not supported for Sparse(UInt64) (NOT_IMPLEMENTED) instead of aborting - a plain exception, so no longer a logical error, and LowCardinality behaves the same way. That remaining NOT_IMPLEMENTED gap is a separate follow-up and I am tracking it; it is not a regression and not blocking.

Both failures are unrelated to your PR, as you concluded.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage on cfe080cbabf — both reds are unrelated to this PR. Branch updated with master (7870e23e383) to re-roll them.

Verification on the merged head: ninja clickhouse builds clean (zero errors, zero warnings) against the 493 new master commits, and all nine parallel_full_sorting_merge tests plus 04209_top_k_through_join_read_in_order_gate match locally. 04499_..._distributed_plan cannot be checked with clickhouse local (the distributed-plan step registry is not available there — master's own 04656/04657 distributed-plan tests fail identically), so it is left to CI.

Comment thread src/Core/SettingsEnums.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov The fix is in progress and it is mine: #108855, "Fix wrong results for duplicate-ALIAS GROUP BY on a Distributed table under two-level aggregation". It is open, mergeable, and it already carries this test file. I gave the full derivation on #91358 two days ago (#91358 (comment)), so here is the short form plus what has changed since.

Root cause. The failing statement is 04357_distributed_alias_same_expression.sql:198, SELECT length(a1) AS l, length(a2) AS m, count() AS c FROM dist_longlit GROUP BY a1, a2 ORDER BY l, where a1 and a2 are both ALIAS repeat('y', 300). The shard inlines the aliases, so its ActionsDAG collapses the two GROUP BY keys into one and derives the two-level bucket number from that single key, while the initiator configures MergingAggregated with the full two-key set. A bucket is hash(keys) % 256, so once one shard has converted to two-level and another has not, equal groups arrive under different bucketing and are never merged. The one logical group then comes back once per shard with its count() split, which is exactly your 300 300 2 arriving as two 300 300 1 rows. So this is not test nondeterminism: it is a live wrong-results bug in trunk that the randomized settings expose about one run in four.

Your numbers hold, and trunk exposure has grown since my 07-29 reply. Over the last 7 days, excluding flaky-check jobs: 51 distinct pull requests, and 5 master commits rather than the 2 I could report then:

  • 07-28 47071389e917 arm_binary, 2734eda2533d amd_debug
  • 07-29 b7aeb788ba94 amd_debug
  • 07-30 4743029ec3cc arm_binary, b3391d074972 amd_debug

All three days you name are real trunk hits, on both architectures. The settings fingerprint is not coincidental either: of the 57 rows in that window, 56 (all but one memory-limit row) carry both --group_by_two_level_threshold_bytes 1 and --prefer_localhost_replica 0, and all 56 diff at the 300 300 N region. Each is drawn with probability 0.2, so 56 of 56 is the precondition rather than chance: the first forces two-level aggregation, the second forces a real remote read per shard. The mechanism is absent from trunk, shard_collapse_duplicate_keys matching 0 files on master against 13 added lines in #108855.

Two things specific to this pull request. Your merge to 7870e23e383d will not clear the red, because #108855 is unmerged. And #108855 has no human review and no requested reviewers, which is the only thing holding it.

I am not sending a separate pull request. The only test-only change available is to pin group_by_two_level_threshold_bytes or add a tag, and either deletes the coverage that finds a real wrong-results bug instead of fixing anything. You are right that there is no tracking issue; I will open one if you prefer the failure tracked separately from the pull request.

…andomization

`src/Client/BuzzHouse/Generator/SessionSettings.cpp` holds the only hardcoded
randomized `join_algorithm` list in the tree, so without this entry BuzzHouse
could never select the new algorithm and the hash-sharded merge join would stay
unfuzzed after merge. Add it to both the `settingCombinations` choice list and
the oracle values list.

#109005 (comment)

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

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 144/151 (95.36%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 1, 2026
Merged via the queue into master with commit 2601c86 Aug 1, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the parallel-full-sorting-merge-join branch August 1, 2026 15:00
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
Comment on lines +475 to +485
/// The shard is picked by the hash of the key's byte representation (`ScatterByPartitionTransform` ->
/// `IColumn::computeHashInto`), while `FullSortingMergeJoin` matches keys with `compareAt`. For some types
/// the two disagree - values that compare equal can hash differently - so hash sharding would scatter them
/// into different shards and the per-shard merge would lose the match, returning fewer rows than the
/// `full_sorting_merge` algorithm this one mirrors. Known cases:
/// - Floating-point: `-0.0` / `+0.0` (and NaNs) compare equal but have different bit patterns.
/// - `Object('json')` / `JSON` and `Dynamic`: `compareAt` compares the logical value, the hash depends on
/// the physical layout (typed/dynamic subcolumn vs `shared_data`, typed vs shared variant), and that
/// layout can differ between blocks. `Dynamic` keys are rejected earlier by
/// `TableJoin::inferJoinKeyCommonType` unless `allow_dynamic_type_in_join_keys` is enabled.
/// Detected at the top level or nested inside `Nullable`/`LowCardinality`/`Array`/`Tuple`/`Map`/`Variant`.

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.

This is wrong. computeHashInto should hash logically equal objects to the same value, because that is used in most of the scattering algorithms. Instead of fixing it, we just did a workaround here. @Avogar is fixing it for ColumnObject here

pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Aug 26, 2026
…the new join algorithm from ClickHouse#109005

- tests/clickhouse-test: randomize `allow_distinct_partitions_independently`,
  `force_distinct_partitions_independently`,
  `max_number_of_partitions_for_independent_distinct` and
  `enable_parallel_single_level_merge`. `force_*` is conditional on `allow_*`,
  because forcing is a no-op when the optimization is not allowed.
- ci/jobs/scripts/stress/stress.py: add `parallel_full_sorting_merge` to the
  `join_algorithm` rotation (skipped in Upgrade check, because the previous
  release may not know this value).
- BuzzHouse: add the four new settings next to their aggregate analogs.

Related: ClickHouse#109005
Related: ClickHouse#108326
Related: ClickHouse#110395

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The `wait_ready` deadline of 30 attempts x 2s = 60s is too tight for
debug and sanitizer builds: in a flaky-check run the amd_debug server
listened ~64 seconds after the fork, about 4 seconds past the deadline,
and the job failed with `SETUP FAILURE: clickhouse-server not ready
(wait_ready)` even though the server started fine. The loop exits early
on success and detects a dead server via `proc.poll`, so a longer
deadline only affects genuinely hung servers.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109005&sha=92b35fef52a82ba621462f1218a2e5cb43ef1980&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
PR: ClickHouse#109005

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

Labels

pr-performance Pull request with some performance 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.

Execute full sorting merge join in parallel

5 participants