Repository navigation
Parallel full sorting merge join (parallel_full_sorting_merge) - #109005
Conversation
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]>
|
Workflow [PR], commit [46b8863] Summary: ✅
AI ReviewSummaryThis PR adds the Final Verdict
|
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (13 of 43)
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_officialFlagged queries (2 of 22)
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
|
`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]>
|
Addressed the AI review Block verdict in 569b478. ASOF (blocker) — confirmed real. Read-in-order virtual rows (major). The pass now only converts sort steps that are still Both changes verified locally (debug build): |
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]>
|
Addressed the AI review Changes requested verdict in 85055be. Legacy analyzer no-op (major) — confirmed real. With Test (requested). Added |
`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]>
|
Addressed the AI review Block verdict in 6217029. Floating-point join keys (blocker) — confirmed real. Fix. Test. |
`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]>
|
Addressed the AI review (Changes requested) in e74fca2.
Fix: extended |
`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]>
|
Addressed the AI review Changes requested verdict in 03057cd. Priority-list contract (major) — confirmed real. Fix. The selected algorithm is now carried into the join object. Test. |
`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]>
|
Addressed the AI review Changes requested verdict in aa8a945.
Reproduced against the current binary ( Fix: |
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.
|
Addressed the AI review Changes requested verdict in 912c0a6. Documentation over-promise (major) — confirmed. The 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]>
…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]>
|
CI triage on
|
|
Investigated both. Neither needs a new PR from me; details and evidence below. Stress test (amd_tsan), I pulled the aborting query from that job's Root cause: when two 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), 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
I confirmed the behaviour change empirically on a master build whose Both failures are unrelated to your PR, as you concluded. |
|
CI triage on
Verification on the merged head: |
|
@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 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:
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 Two things specific to this pull request. Your merge to I am not sending a separate pull request. The only test-only change available is to pin |
…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]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 144/151 (95.36%) · Uncovered code |
| /// 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`. |
…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]>
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]>
Resolves #48165
Adds a new
join_algorithmvalueparallel_full_sorting_merge.full_sorting_mergestreams 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 thanparallel_hasheven though it uses far less memory.parallel_full_sorting_mergekeeps 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 tomax_threads).A query-plan optimization (
optimizeParallelFullSortingMergeJoin) switches each side's pre-joinSortingStepto 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 — andFullSortingMergeJoinalready 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 ⋈ 20MonUInt64keys,max_threads = 8:join_algorithmparallel_hashparallel_full_sorting_mergefull_sorting_merge(single merge)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
hashalgorithm forINNER/LEFT/RIGHT/FULLjoins, many-to-many keys, andjoin_use_nullsin04492_parallel_full_sorting_merge_join.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a new
join_algorithmvalueparallel_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 thanparallel_hash).ASOFjoins fall back to a singlefull_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 whenquery_plan_join_shard_by_pk_rangesis enabled. The result is not ordered.Documentation entry for user-facing changes
join_algorithmsetting).Version info
26.8.1.592(included in26.8and later)