Skip to content

Enable query_plan_join_shard_by_pk_ranges by default - #117856

Merged
alexey-milovidov merged 11 commits into
masterfrom
join-shard-by-pk-ranges-default
Oct 12, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
join-shard-by-pk-ranges-default

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

Related: #112664
Related: #117786
Related: #118918
Related: #112402
Related: #112031
Related: #117873
Related: #111897

Prerequisites (all settled as of 2026-09-11). #112664 (the NOT_FOUND_COLUMN_IN_BLOCK when a PREWHERE consumes a sorting-key column that is not in the join output, issues #112402 and #112031) and #118918 (rows silently dropped when a Float primary key holds a NaN, issue #117873) are merged and in this branch, with their regression tests 05099_join_shard_by_pk_prewhere_sorting_key and 05159_join_shard_by_pk_ranges_float_nan. The query condition cache poisoning of issue #111897 no longer reproduces on this branch (verified 3/3, with EXPLAIN confirming the read is still sharded); 04065_join_shard_by_pk_with_qcc covers it. #117786 is not a prerequisite after all: the PartitionedFinishSorting above a chained merge join, which its pending_sorting_steps / JoinPipelineType::YShaped guard fixes, only comes into existence because #117786 itself makes a FullSortingMergeJoin advertise the order of its output — chains of merge joins with the sharding on give identical results here and never hit Join is supported only for pipelines with one output port, which has no CIDB occurrence in the fleet since 2026-09-04.

Why it was off

query_plan_join_shard_by_pk_ranges was added in 25.4 (#74733) as an opt-in with the description "usually does not speed up queries but may lower memory consumption". That assessment was made for the hash join, and it still holds for it. But since then two default-on features made the optimization a no-op for hash joins on a stock server:

  • join runtime filters (enable_join_runtime_filters) put a BuildRuntimeFilter step between the build-side read and the join, which optimizeJoinByShards does not look through;
  • since 26.5 (max_bytes_ratio_before_external_join = 0.5) the default hash join is SpillingHashJoin, whose hasDelayedBlocks() is always true, and the pass excludes joins with delayed blocks.

A hash join is sharded only when both are switched off. So on a default configuration the setting affects exactly full_sorting_merge and parallel_full_sorting_merge, and there it is the difference between a single-threaded merge join and one streaming merge join per primary-key range on every thread. (parallel_full_sorting_merge deliberately does not hash-shard already sorted inputs such as a read in order, so it, too, runs single-threaded on such joins without this setting.)

Measurements

Two 50M-row tables and a 1M-row table, all ORDER BY id, 16 threads, min of three interleaved runs of on/off on a loaded box (system.query_log):

query full_sorting_merge off → on parallel_hash (spilling and runtime filters off) off → on
a JOIN b USING id (50M × 50M) 1436 → 222 ms, 583 → 69 MiB 357 → 368 ms, 2.9 → 5.4 GiB
a JOIN dim USING id (50M × 1M) 561 → 76 ms, 289 → 69 MiB 128 → 116 ms
… WHERE a.v < 5M (matches the first 10% of the key range) 186 → 123 ms, 338 → 37 MiB 153 → 283 ms
… WHERE b.s = '5' 605 → 143 ms, 283 → 68 MiB 167 → 157 ms
a LEFT JOIN dim USING id 700 → 121 ms, 315 → 68 MiB 157 → 148 ms

parallel_full_sorting_merge gives the same numbers as full_sorting_merge (the hash sharding is skipped for sorted inputs). Single-threaded hash goes 2465 → 387 ms on the first query. The skewed filter is the known weak point of static range assignment: threads whose ranges have no matches finish early. That trade-off is now spelled out in the setting description, together with when the setting applies to hash joins at all.

Testing

The setting is already randomized in the functional tests (30% on), so the suite has been exercising the sharded path for a long time; the randomization now leans towards the new default (70% on). Running all 1068 *join* stateless tests and the 45 no-random-settings tests containing a JOIN with the setting forced on and off gives identical results, except 04105_limit_by_into_sort_explain, a no-random-settings EXPLAIN PIPELINE test whose full_sorting_merge join now pins the setting off (the test is about LIMIT BY, and #117786 rewrites that reference block anyway).

The default change is recorded in SettingsChangesHistory.cpp for compatibility.

Changelog category (leave one):

  • Performance Improvement

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

query_plan_join_shard_by_pk_ranges is enabled by default. A full_sorting_merge or parallel_full_sorting_merge JOIN of two MergeTree tables whose join keys contain a prefix of the primary key of both tables now runs as independent streaming merge joins over primary-key ranges on all threads instead of a single-threaded merge join: several times faster and with several times less memory in our tests. Hash joins are affected only when both join runtime filters and spilling to disk are disabled. Set query_plan_join_shard_by_pk_ranges = 0 to restore the previous behavior.


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

Version info

  • Merged into: 26.10.1.2166-master (included in 26.10 and later)

The setting was introduced in 25.4 (#74733) as an opt-in with the note
that it "usually does not speed up queries but may lower memory
consumption". That is true for the hash join it was written against,
but two later default-on features made it a no-op there anyway on a
stock server: join runtime filters put a `BuildRuntimeFilter` step on
the build side, which the pass does not look through, and since 26.5
the default hash join is `SpillingHashJoin` (`max_bytes_ratio_before_external_join = 0.5`),
whose `hasDelayedBlocks()` excludes it from sharding. Hash joins are
sharded only when both are switched off.

Where the setting does apply, `full_sorting_merge` and
`parallel_full_sorting_merge` on a join key that is a primary-key prefix
of both tables, it turns a single-threaded merge join into one streaming
merge join per primary-key range, on all threads. Two 50M-row tables
`ORDER BY id`, 16 threads, min of three interleaved runs:

    50M x 50M inner join              1436 ms -> 222 ms, 583 MiB -> 69 MiB
    50M x 1M dimension                 561 ms ->  76 ms, 289 MiB -> 69 MiB
    ... with a filter matching 10%     186 ms -> 123 ms, 338 MiB -> 37 MiB
    ... with a filter on the right     605 ms -> 143 ms, 283 MiB -> 68 MiB
    50M LEFT JOIN 1M                   700 ms -> 121 ms, 315 MiB -> 68 MiB

`parallel_full_sorting_merge` deliberately skips hash-sharding of
already-sorted inputs (a read in order), so without this setting it also
runs such joins single-threaded.

For `hash`/`parallel_hash` with runtime filters and spilling disabled,
the effect is neutral for `parallel_hash` (357 -> 368 ms on the first
query, higher peak memory), a large win for single-threaded `hash`
(2465 -> 387 ms), and 2x slower on the skewed filter, since the ranges
are assigned to threads statically. The setting description now says so
instead of the old blanket statement.

The setting is randomized in the functional tests, so the suite already
runs with it on 30% of the time; the randomization now favors the new
default. `04105_limit_by_into_sort_explain` is a `no-random-settings`
test that inspects the pipeline shape around a `full_sorting_merge`
join, so it pins the setting off.

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

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [575440e]

Summary: ✅


AI Review

Summary

This PR flips query_plan_join_shard_by_pk_ranges to default-on, updates the setting’s source-of-truth description and compatibility history, and tightens optimizeJoinByShards so a final DISTINCT no longer carries primary-key-range sharding through a join. I did not find any remaining correctness, safety, or contract issues in the current code: the earlier blockers called out on this PR are addressed in the merged tree, the DISTINCT plan-shape regression is covered by the updated stateless test, and the latest CI for 575440e9 is green.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 575440e.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 3, 2026
Comment thread src/Core/Settings.cpp Resolved
@zlareb1

This comment was marked as low quality.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 575440e92 with master 740fe426e (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

8 translation units recompiled, 29 s compile time in total, 8 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there.

This PR turns on query_plan_join_shard_by_pk_ranges by default and stops sharding past a final DISTINCT. That changes merge-join plans, and hash-join plans only when join runtime filters and spilling are both off. All 8 flagged improvements were downgraded to not_sure. Five of them (ClickBench Q18, Q32, Q33, Q34 and TPC-H Q1) have no JOIN. TPC-H Q7, Q9 and Q17 use hash joins with runtime filters on, which is enabled by default, so the new sharding path should not apply to them either. Since the speedups also show up on single-table aggregations, they most likely come from drift between the 26.9 master base and the 26.10 source build. Rerunning against a baseline built from the exact base commit should confirm this, and this run shows no performance change that can be attributed to the PR.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1064 868 -18.4% <0.0001 aggregation: ClickBench Q18 is a single-table GROUP BY with no JOIN, so making primary-key-range JOIN sharding the default cannot reach it. The -18.4% is more likely master drift between the 26.9 base and 26.10 source on a query that is already noisy.
⚠️ 32 not_sure 1342 843 -37.2% <0.0001 aggregation: Q32 is a single-table GROUP BY WatchID, ClientIP with no JOIN, so this PR's JOIN sharding change does not run here. The -37.2% and the CPU drop probably come from other changes between the 26.9 base and the source build.
⚠️ 33 not_sure 1236 1051 -15.0% <0.0001 aggregation: Q33 is a single-table aggregation with no JOIN, so the PR's JOIN sharding change cannot reach it. The -15.0% fits base-version drift on a noisy query.
⚠️ 34 not_sure 1244 1142 -8.2% <0.0001 aggregation: Q34 is a single-table GROUP BY URL with no JOIN, so the changed code path is not executed. The -8.2% is not attributable to this 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

⚠️ 4 inconclusive

Flagged queries (4 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 66 53 -19.7% <0.0001 aggregation: TPC-H Q1 scans and aggregates lineitem only, with no JOIN, so primary-key-range JOIN sharding cannot affect it. The -19.7% points to base-version drift.
⚠️ 7 not_sure 82 62 -24.4% <0.0001 join_operator: Q7 uses the default hash joins. The new default only shards hash joins when join runtime filters are off, and those are on by default, so this plan should not change. The -24.4% is more likely base drift.
⚠️ 9 not_sure 104 87 -15.9% <0.0001 join_operator: Q9 runs default hash joins with join runtime filters enabled, which turns off the hash-join sharding path this PR makes the default. The -15.9% is not clearly caused by this PR.
⚠️ 17 not_sure 100 62 -38.0% <0.0001 join_operator: Q17 joins part and lineitem with hash joins and join runtime filters on, so the sharding path should not apply. The base runs were very noisy, and the -38.0% likely reflects base drift, not this setting flip.

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: 6d8cfe4c-4a47-4af1-a219-3c5f02b8fe47
  • MIRAI run: d98aea46-ca7d-4a70-bd7e-585a2645da93
  • PR check IDs:
    • clickbench_946157_1791759720
    • clickbench_946256_1791759723
    • clickbench_946403_1791759734
    • tpch_adapted_1_official_946499_1791759748
    • tpch_adapted_1_official_946613_1791759779
    • tpch_adapted_1_official_946720_1791759787

@alexey-milovidov
alexey-milovidov marked this pull request as draft September 3, 2026 16:10
@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 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks — both are now sequenced out, and the branch is merged with master (51f627ccdbae), so both fixes are in it.

  1. PK-range join sharding silently drops rows when a Float primary key contains NaN (query_plan_join_shard_by_pk_ranges) #117873 was fixed by Stop PK-range join sharding at a key column that can hold a NaN #118918 ("Stop PK-range join sharding at a key column that can hold a NaN"), merged 2026-09-10, with the regression test 05159_join_shard_by_pk_ranges_float_nan. That test passes on this branch.

  2. Query condition cache poisoned by a query_plan_join_shard_by_pk_ranges + full_sorting_merge multi-threaded join read — later default-settings queries silently lose rows #111897 no longer reproduces. I re-ran the exact reproducer from the issue on this branch (server build of 51f627ccdbae, index_granularity = 64, max_threads = 4, max_block_size = 100, join_algorithm = 'full_sorting_merge'), 3/3 runs: the poisoner returns 41, 249, 267, 423, the victim at plain default settings returns the same four rows, and system.query_condition_cache holds only the correct 10011010000000000 entries — the 11111101111111110 entry from the issue is gone. EXPLAIN actions = 1 still shows Sharding: [(id = id)] for the poisoner, so the check is not vacuous, and the FULL JOIN ... USING shape behaves the same. The tree also carries 04065_join_shard_by_pk_with_qcc for this. I did not track down which change fixed it; the issue looks stale rather than open, but I left it open for whoever owns it to confirm.

I have added both to the Related list in the description.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI status of the previous head de4b57e0, for the record:

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117856&sha=de4b57e08b87d3cc512f0c0fc20fcffb03393f2c&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29 (GroupingAggregatedTransform pushed bucket A twice, issue #115986) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated de4b57e0. This is the shard-side shuffle aggregation, and the fix is already in progress: #116446.

From the job's own server.log, initiator query 85ce943d-31fc-4e0f-88b4-9cadb7f4160c (SELECT toInt8OrDefault(-2), 65536, _part_offset FROM remote('127.0.0.{4,5}', currentDatabase(), toFixedString('jd_l__fuzz_12', 13)) GROUP BY ALL LIMIT 10, abort at 17:29:37.760473 on bucket 1):

  • The initiator is on the classic two-stage path (Planner: Query from stage WithMergeableState to stage Complete) and merges memory-efficiently, so GroupingAggregatedTransform needs each bucket exactly once, in order.
  • Both shard legs (ef1b7702..., 9874ae19...) are at WithMergeableState, and the distributed planner rewrites each of them into
====================== Executing stage 'stage_1' =========================
GatherSend
  Aggregating
  Keys: __table1._part_offset
    ShuffleReceive
TASKS: 3

Three full Aggregating instances above a shuffle, gathered. Each numbers its own two-level buckets (Aggregation method: key64_void_two_level, three Aggregator: Merging aggregated data per shard, zero Merging partially aggregated blocks), and the gather cannot restore a global order because the bucket number is chunk metadata, not a column. So bucket 1 reaches the initiator twice and MergingAggregatedMemoryEfficientTransform.cpp:63 throws (stack frames 12 to 15; the in-order arm at :137).

04649_pr_plan_based_join_distributed.sql, where the fuzzed query comes from, sets no distributed-plan settings. They are session leftovers from an earlier corpus file: SET make_distributed_plan = 1, enable_parallel_replicas = 0, distributed_plan_execute_locally = 1, distributed_plan_default_shuffle_join_bucket_count = 3, distributed_plan_default_reader_bucket_count = 3 at 17:12:23 on the same client connection, which is also where TASKS: 3 comes from. The span has no Cascades lines, so the rewrite is tryMakeDistributedAggregation.

That is the function #116446 guards: when the AggregatingStep carries the bucket-order promise, which Planner.cpp sets at WithMergeableState whenever distributed_aggregation_memory_efficient or enable_memory_bound_merging_of_aggregation_results is on (both default to true), the strategy is demoted from Shuffle to partial aggregation plus merge, which keeps the promise. Regression test 04878_distributed_plan_shuffle_bucket_order_promise. I reached the same conclusion for the carrier you pointed at on 2026-09-09: #114883 (comment).

So no separate PR is needed for this failure, but #116446 is waiting on a design call rather than on code: merge the guard as a stopgap, or implement bucket-aware shuffle support. I set out what each option costs on 2026-09-02 (#116446 (comment)). I will implement the proper support if that is preferred.

alexey-milovidov and others added 3 commits September 18, 2026 11:28
The `Style check` job failed on `settings_changes_history`: the
`query_plan_join_shard_by_pk_ranges` record sat in the `26.9` block,
while the version in `cmake/autogenerated_versions.txt` has moved on to
`26.10`. A default change made now has to be recorded under the current
version block, otherwise `compatibility` attributes the flip to a
release that shipped the old default.

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

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai — #116446 merged on 2026-09-13 and is now in this branch (master merged in as 5b450963), so that GroupingAggregatedTransform pushed bucket A twice red should not come back.

Also fixed the Style check / settings_changes_history failure on 3703b659: the query_plan_join_shard_by_pk_ranges record was still in the 26.9 block while cmake/autogenerated_versions.txt has moved to 26.10, so it was moved to the current version block. No other change.

Comment thread src/Core/Settings.cpp Resolved
…nges-default

# Conflicts:
#	src/Core/SettingsChangesHistory.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117856&sha=5b450963619f82cb16e3177cd2d592857951370d&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 (Logical error: GroupingAggregatedTransform pushed bucket A twice, STID 3994-4c1d, tracked in #115986) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. This is the Cascades route of #115986, and the fix is already in progress in your own PR #119814 ("Keep the bucket-order promise of a shard aggregation in the Cascades optimizer"), still open.

Attribution on this run. The abort is query 95db025e-0310-47cc-8171-7439b3a187f2, log_comment = '04878_distributed_plan_shuffle_bucket_order_promise.sql-test_5'. Its logged settings carry enable_cascades_optimizer = 1 together with distributed_plan_force_shuffle_aggregation = 1, distributed_aggregation_memory_efficient = 1 and enable_memory_bound_merging_of_aggregation_results = 1. pushed bucket 7 twice is raised at MergingAggregatedMemoryEfficientTransform.cpp:63, reached from GroupingAggregatedTransform::tryPushTwoLevelData(). That is the path #119814 describes, and #119814 also carries the explicit enable_cascades_optimizer = 0 line for exactly this test.

Fix absence in the tested build. #119814 is unmerged, and compare/bc3814d143540baada9d377d08fe758444804274...5b450963619f82cb16e3177cd2d592857951370d reports diverged (4063 commits missing), so none of it was in this build.

Not caused by this PR. query_plan_join_shard_by_pk_ranges is read in one place, optimizeTree.cpp:849, where it gates optimizeJoinByShards(root); that pass matches a physical JoinStep with two children whose join keys contain a prefix of both primary keys. The aborting query is SELECT k, sum(v) FROM remote('127.0.0.{2,3}', ..., t_shuffle_bucket_order) GROUP BY k, which has no join at all, and t_shuffle_bucket_order is ORDER BY tuple(). So whichever value the setting took on that query, it cannot reach GroupingAggregatedTransform. Independently, the signature fires on plain master: 22 distinct master commits in the last 21 days (201 rows, 153 PRs, 20 check flavours, arm and amd, every sanitizer plus release, s3 and azure).

No new PR from me then; #119814 owns it.

alexey-milovidov and others added 2 commits September 26, 2026 23:23
…nges-default

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master (f2fe75c7); Settings.cpp merged cleanly and compiles.

The only red on 21905c75 was Performance Comparison (amd_release, master_head, 2/6), which flagged json_key_formatting #3 at +15.8%: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117856&sha=21905c75cd264dbcccd59cb09585fbd7cbf76e36&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%202%2F6%29
That query runs formatRow over a Memory table with no JOIN, so query_plan_join_shard_by_pk_ranges cannot affect it. The same job also reported "under-utilized CPU" and "disk-almost-full". The intended full_sorting_merge_join / parallel_full_sorting_merge_join speedups (up to 3.3x) all showed up.

@groeneai, investigate the failure: the link above, and provide a fix in a separate PR if json_key_formatting #3 is unstable. If the fix is already in progress, link it here.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

The red at 21905c75 came from the dashboard tier, not from the in-tree comparison: the shard summary is 1 too long, 2 faster; 1 confirmed regression(s) on the performance dashboard, and CIDB has all four json_key_formatting queries as success in that job. The dashboard had 7 old samples at 0.269-0.272 s and 7 new ones at 0.312-0.320 s, so the two servers differed by a steady 16% for the whole run.

#3 is noisy on amd in exactly this way: in the last 30 days it moved by more than 15% in 71 of 2046 amd runs (37 of 865 master runs), against 10 of 6888 arm runs. The in-tree comparison marked it slower once and never unstable.

That class no longer blocks. Since #122782 (merged 2026-09-29), a master_head shard restarts both servers and reruns its dashboard regressions before failing. On 2026-10-02 the dashboard gave this same query a +15.7% confirmed_regression on amd, and the rerun cleared it (0/1 dashboard regression(s) remain blocking after confirmation, shard green): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115014&sha=0e252e3606286558406659c06631e2b1345a788c&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%206%2F6%29
Since that merge, no amd shard has stayed red on json_key_formatting. Your master merge f2fe75c7 includes #122782, so I am not sending a PR for this test.

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

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

Both have fixes in progress:

…ough a final `DISTINCT`

`optimizeJoinByShards` treated every `DistinctStep` as transparent. A final
`DISTINCT` (unless it skips stream merging, which happens only for
per-partition reads that this optimization already rejects) merges its input
into a single stream, so that side of the join ends up with one stream while
the other side is still split into primary-key ranges. `JoinStep` then
disables the sharded path on the stream-count mismatch, and for a `YShaped`
join (`full_sorting_merge`) the unsharded fallback requires one port per side.

Now only a preliminary `DISTINCT` is transparent. For hash joins this changes
nothing at runtime (the sharding was already dropped on the mismatch), so the
`04655` test now expects no `Sharding` marker for a final `DISTINCT`, and shows
sharding on the same tables without `DISTINCT` instead.

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

Copy link
Copy Markdown
Member Author

🕵 Pushed 4cca8714, which addresses the clickhouse-gh review: optimizeJoinByShards no longer carries the PK-range sharding through a final DISTINCT, and 04655 is updated to match.

On 16570d86, the only red is Performance Comparison (amd_release, master_head, 4/6), where float_formatting #1 is +36.3% and still +37.7% after the server restart: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117856&sha=16570d8635e219a86c7e788897e0c122d9301171&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%204%2F6%29
That test formats floats from numbers and has no JOIN, so query_plan_join_shard_by_pk_ranges cannot affect it.

@groeneai, investigate the failure: the link above, and provide a fix in a separate PR. If a fix is already in progress, link it here.

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

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

float_formatting #1 on 16570d86: 118 of the 154 extra CPU samples are in the AVX-512 IFMA kernel that formats the integer value (avx512ifma::toChars, 133 -> 251). #0, #4 and #5 use the same kernel and are 1.32x-1.34x slower too. Float32 (#13) and non-integer values (#8, #11) are flat.

The slowdown is a property of the candidate binary, which is why it survives the restart. The machine code of toChars and itoa is the same, instruction for instruction, in the PR binary and in the reference (b62bc5c3). Only the code's offset in its 4 KiB page differs (0x7c0 vs 0x240); the constants it loads are at the same addresses. On my Xeon 6975P-C (has IFMA; the CI runners are m7i, Sapphire Rapids), the same two CI binaries run #1 at the same speed (1.01x). Master binaries hit the same state: cdc0f1ab45 was 1.2x slower as the new side (report) and was still slow as the old side of the next run (0.78x, report).

No fix is in progress for this, and I don't have one. The only difference I can find is where the code lands, and it does not reproduce on my machine, so I can't narrow it down without a Sapphire Rapids host. These flips were more common before the kernel: #1 moved by 20% or more in 76 of 901 amd runs in the 7 weeks before 2026-08-17, and in 9 of 1397 since then. So the options I posted for the separate 11-21% step on #1-#5 (#81944 (comment)) would not fix this. Going back to the scalar code for short values could make the flips more frequent.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (575440e9). The PR diff is unchanged, and Settings.cpp and optimizeJoinByShards.cpp compile.

Thanks @groeneai for the float_formatting #1 analysis: the code has the same instructions and only a different page offset, so it is not related to this PR.

The only red on 4cca8714 is Upgrade check (amd_release), Cannot run the mutation entries left behind by the killed mutations: SYSTEM SYNC REPLICA ... PULL on test_3.mutation_pruning_without_validation got TABLE_IS_READ_ONLY (report). That step was added by #123376. #123069, a proxy-only PR, failed it the same way (Code: 242 on test_5.t_lwu_merges), and #123841 (open) is tracking it. Mutations are unrelated to query_plan_join_shard_by_pk_ranges.

@groeneai, check whether #123841 also covers this occurrence, a replica in read-only mode during the drain. If it does not, provide a fix in a separate PR.

The clickhouse-gh thread about the settings docs is answered: those pages are autogenerated from Settings.cpp.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

#123841 covers it. The read-only replica is a side effect of the same lock wait, not a ZooKeeper problem: SYSTEM RESTART REPLICA test_3.mutation_pruning_without_validation shut the replica down, then timed out on the exclusive lock (Code: 473 ... DEADLOCK_AVOIDED, owner c7260cc7), so the replica stayed read-only and SYNC REPLICA ... PULL failed.

This time the lock owner is BACKUP DATABASE test_3 ON CLUSTER test_shard_localhost from 02907_backup_mv_with_no_source_table.sh, started 7 minutes before the drain. Its host part was stuck in prepareReplicatedTables::repl_part_names retries under the stress phase's backup_restore_keeper_fault_injection_probability=0.05 (around retry 93/1000 at the restart, one every 5 s), holding the shared locks of the test_3 tables. Those retries check for cancellation, so KILL QUERY stops it.

I reproduced it on the official 26.9.11.2 server with the same chain (a killed mutation on a replicated table, plus that ON CLUSTER backup stuck in fault-injection retries over 80 replicated tables):

In 2 of the 3 passing runs the KILL itself hit its timeout 2m, because the backup initiator waits for the host after an error before cleaning up. That costs 2 minutes but not the result, since the lock holder is already gone. So I do not plan a separate PR for this one.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai — agreed, the Upgrade check red on 4cca8714 is covered by #123841 (a BACKUP ... ON CLUSTER stuck in fault-injection retries holding the table locks), so no separate PR is needed. The current head 575440e9 is green on all CI jobs; only CH Inc sync is still pending. There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

All prerequisites are solved.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The results for full_sorting_merge_join are good.

@alexey-milovidov alexey-milovidov left a comment

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.

The code is trivial. LGTM.

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

4 participants