Skip to content

Add merge_use_batch_sorting_queue MergeTree setting for ordinary merges - #108468

Merged
alexey-milovidov merged 55 commits into
ClickHouse:masterfrom
rorylshanks:codex/merge-batch-queue-setting
Aug 14, 2026
Merged

alexey-milovidov merged 55 commits into
ClickHouse:masterfrom
rorylshanks:codex/merge-batch-queue-setting

Conversation

@rorylshanks

@rorylshanks rorylshanks commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Related: #38022
Related: #38859

Adds merge_use_batch_sorting_queue, a Boolean MergeTree setting for ordinary MergeTree merges. It has no effect on merges that change rows, such as those performed by ReplacingMergeTree or AggregatingMergeTree.

The setting defaults to false, preserving the existing merge behavior. When set to true, it uses the batch sorting queue in the ordinary merge sorting stage.

The batch sorting queue is already used in several query sorting paths. This change makes it available for background merges as an opt-in table setting, so users can enable it for merge-heavy workloads where MergingSortedTransform is a significant part of merge time.

The PR also adds targeted stateless coverage for:

  • merge_use_batch_sorting_queue = false vs true correctness across horizontal and vertical merges with a broad set of data types;
  • vertical merges with small granules and larger merge blocks;
  • equal primary-key values spread across multiple source parts, checked by merged-part order.

Benchmark results from local runs with merge_use_batch_sorting_queue disabled and enabled:

Dataset Wall time speedup Wall time disabled Wall time enabled User CPU change Peak RSS disabled Peak RSS enabled MergeTotalMilliseconds change MergingSortedMilliseconds change
ClickBench hits 23.9% 10.270s 7.813s -28.3% 1.38 GiB 1.36 GiB -27.1% -69.2%
OnTime 2019 35.7% 6.855s 4.410s -41.4% 1.79 GiB 1.83 GiB -31.5% -91.4%
StackOverflow votes 13.0% 0.730s 0.635s -17.4% 374 MiB 372 MiB -14.4% -82.2%
HackerNews 2.8% 3.565s 3.465s -3.1% 798 MiB 803 MiB -0.9% -74.8%
NYC Taxi 2.4% 3.505s 3.420s -1.9% 998 MiB 1000 MiB -2.2% -5.2%
StackOverflow posts 2.7% 4.275s 4.160s -2.0% 1.07 GiB 1.08 GiB -2.3% -32.8%

The benefit is workload dependent. It is largest when sorted merging is a significant fraction of the total merge time, and smaller when writing, compression, or other merge work dominates.

This PR was developed with AI assistance from Codex and Claude.

Changelog category (leave one):

  • Performance Improvement

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

Add the merge_use_batch_sorting_queue MergeTree setting to optionally use the batch sorting queue for ordinary MergeTree merges, reducing CPU and wall-clock time for merge workloads where sorted merging is a significant cost.

Version info

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

@alexey-milovidov

Copy link
Copy Markdown
Member

Why closing?

@alexey-milovidov alexey-milovidov added the pr-performance Pull request with some performance improvements label Jul 20, 2026
@rorylshanks

rorylshanks commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Hey I didn't see any activity from CH on this PR and figured that it might not be relevant or I was missing context, so I closed it as part of a cleanup of some of my PRs. Happy to work on it if it is of interest!

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 20, 2026
@clickhouse-gh clickhouse-gh Bot closed this Jul 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Jul 20, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

We review 100% of PRs.

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b5a3923]

Summary: ✅


AI Review

Summary

This PR adds the opt-in merge_use_batch_sorting_queue MergeTree setting for row-preserving ordinary merges and wires the batch queue through MergeTask / MergingSortedAlgorithm. On the current head, the guard keeps the feature off for row-changing merges and projection sub-merges, and the updated unit/stateless coverage now exercises the previously risky surfaces: adaptive block-boundary flushing, _block_number / _block_offset, _parent_part_offset projection remapping, text-index remapping, and non-additive byte-size column types such as LowCardinality, dynamic columns, and AggregateFunction states. I did not find an unresolved correctness, compatibility, or metadata issue in the current code.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.20% +0.10%

Changed lines: Changed C/C++ lines covered: 275/279 (98.57%) · Uncovered code

Full report · Diff report

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 3 query(s) improved out of 35 analysed

This PR adds a new default-off MergeTree setting (merge_use_batch_sorting_queue) that reduces per-row overhead during background merges; it does not touch the SELECT execution path, so it cannot plausibly change ClickBench or TPC-H query latencies. ClickBench Q17's -12.1% is downgraded to not-sure as variance. The larger improvements (ClickBench Q23 ×2.3 faster, TPC-H Q7 ×8.2 faster, Q8 ×2.2 faster) are deterministically locked by their large, consistent magnitude, but since the diff can't explain SELECT speedups these most likely reflect a baseline/era shift (small source sample of 6 runs) rather than the PR itself. Q32 is borderline (+5.3%) with mixed signals and is also off the changed path.

clickbench

🟢 1 improved · ⚠️ 2 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 23 improvement 167 72 ×2.3 faster <0.0001 Delta is locked by its large, consistent magnitude (×2.3 faster), but the PR only touches background merges behind a default-off setting and this query is intrinsically noisy, so attribution to the PR is doubtful.
⚠️ 17 not_sure 556 489 -12.1% <0.0001 The PR only adds a default-off background-merge setting (batch sorting queue); nothing in the SELECT execution path changed, so this -12.1% reads as run-to-run variance rather than a PR effect.
⚠️ 32 not_sure 1320 1390 +5.3% 0.0035 Marginal +5.3% with mixed signals from the two tests; the PR's merge-only change does not touch this query's execution path.

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 improved

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 7 improvement 574 70 ×8.2 faster <0.0001 Locked by the large, consistent delta (×8.2 faster), but the PR changes only background merge batching behind a default-off setting, so this most likely reflects a baseline shift rather than the PR.
🟢 8 improvement 175 81 ×2.2 faster <0.0001 Locked by the large, consistent delta (×2.2 faster), but the changed code path is background merges gated by a default-off setting, which cannot speed up this SELECT.

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: 2f02b8ba-fc77-4c6d-a77e-2a884a7f1d3a
  • MIRAI run: 9c6b6251-4e2e-4a86-b9ad-1cde7eeded42
  • PR check IDs:
    • clickbench_1200661_1786706791
    • clickbench_1200667_1786706791
    • clickbench_1200678_1786706791
    • tpch_adapted_1_official_1200689_1786706791
    • tpch_adapted_1_official_1200703_1786706791
    • tpch_adapted_1_official_1200732_1786706791

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@alexey-milovidov alexey-milovidov self-assigned this Aug 12, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Add this MergeTree setting to randomization in CI.

Add the new `MergeTree` setting to `MergeTreeSettingsRandomizer` in
`tests/clickhouse-test`, so stateless tests exercise both the default and
the batch sorting queue merge paths.

The randomized value is injected into `CREATE ... MergeTree` queries only
when the table does not already specify the setting (see
`ClientBase::addMergeTreeSettings`), so the tests added by this pull
request, which pin the setting explicitly to compare both paths, keep
their own values.
Add the setting to `hot_table_settings` in `ci/jobs/buzzhouse_job.py`, so
the fuzzer picks it for `MergeTree` tables more often and exercises the
batch sorting queue merge path against randomly generated schemas.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 12, 2026
@rorylshanks

Copy link
Copy Markdown
Contributor Author

The previous Stress test (arm_asan_ubsan) failure in https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108468&sha=9fdbc3b971dd72906d9d86e1bec33a6f961bc89c&name_0=PR&name_1=Stress%20test%20(arm_asan_ubsan) is unrelated to this change: it is the convertFieldToType signed-overflow failure. A fix is already open at #114546.

@rorylshanks

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov it looks like this run requires manual approval. Can you approve it?

`MergingSortedBatchLimits.MaxBlockSizeBytesWithAggregateFunctionState` failed:
the batch queue returned a 1-row block while the default queue returned 6 rows,
and the expected row count was hardcoded.

The two inputs were shaped so that the second one was consumable as a whole
chunk, which makes the batch queue take the fast-forward path in
`MergingSortedAlgorithm::mergeBatchImpl` - it flushes the rows accumulated so
far and then inserts the source chunk directly. The default queue does not
fast-forward there, because `SortCursorHelper::totallyLessOrEquals` compares
against the first row of the other cursor, so the two queues legitimately
disagree about block boundaries in that case.

Interleave the two inputs instead, so neither of them is consumed as a whole
chunk and the comparison actually exercises the byte limit predictor. Also
replace the hardcoded row count with a non-vacuity check: the exact number of
rows depends on `sizeOfData` of the aggregate state, which differs between
build types.
`merge_use_batch_sorting_queue` was registered between
`merge_max_block_size_bytes` and `merge_max_bytes_to_prewarm_cache`;
move it to its alphabetical place in the list.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Approved the workflow run and pushed an update to this branch:

  • Merged current master. That pulls in the fixes for both failures you reported as unrelated: Fix wrapped Time64 values from an overflowing scale conversion in convertFieldToType #114546 (the convertFieldToType signed overflow in Stress test (arm_asan_ubsan)) and Fix crash reading a Nested member subcolumn from an unrewritten part #113925, so those reds should clear now.
  • Fixed MergingSortedBatchLimits.MaxBlockSizeBytesWithAggregateFunctionState, which failed locally in a RelWithDebInfo build: the batch queue returned a 1-row block while the default queue returned 6, and the expected row count was hardcoded. The two inputs were shaped so the second one was consumable as a whole chunk, which makes MergingSortedAlgorithm::mergeBatchImpl take the fast-forward path — it flushes the accumulated rows and then inserts the source chunk directly. The default queue does not fast-forward there, because SortCursorHelper::totallyLessOrEquals compares against the first row of the other cursor, so the two queues legitimately disagree about block boundaries in that case. The inputs now interleave, so neither is consumed as a whole chunk and the byte-limit predictor is really exercised; the hardcoded count is replaced by a non-vacuity check (0 < rows < total), since the exact number depends on sizeOfData of the aggregate state and thus on the build type.
  • Moved merge_use_batch_sorting_queue to its alphabetical place in the BuzzHouse MergeTree setting list.

The AI review verdict on the previous head is stale: both of its minimum required actions (treating AggregateFunction columns as non-additive in rowsToInsertBeforeFlush, plus focused coverage) are implemented — the coverage now actually compares the two queues instead of asserting a build-dependent row count.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 14, 2026
Merged via the queue into ClickHouse:master with commit 936bd86 Aug 14, 2026
181 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
cwurm added a commit to cwurm/ClickHouse that referenced this pull request Oct 26, 2026
`merge_use_batch_sorting_queue` inserts runs of consecutive rows from the
same source part with a single `insertRangeFrom`. But
`MergedData::rowsToInsertBeforeFlush` returned 1 when any merged column had a
non-additive `IColumn::byteSizeAt` (`LowCardinality`, `AggregateFunction`,
dynamic columns), so with `merge_max_block_size_bytes` set (10 MiB by
default) such merges fell back to single-row batches, which cost more than
the default queue: enabling the setting made such merges slower.

Remove that special case and let the existing per-row byte prediction cover
these columns as an estimate. For `LowCardinality` the estimate is
pessimistic (a repeated value adds only an index entry), so batches are cut
no later than needed, and any remaining error is bounded by one batch because
`hasEnoughRows` measures the actual size before the next one. Wide values
still cut the batch where the row-by-row path does, including values inside
columns like `Map(LowCardinality(String), String)`, so a run of huge values
does not end up in a single granule.

The special case was added during review only to reproduce the default
queue's flush boundaries exactly
(ClickHouse#108468 (comment)),
which is not a correctness property: the two queues already disagree on
boundaries through the whole-chunk fast path.

With the setting enabled, a horizontal merge of a table with a
`Map(LowCardinality(String), LowCardinality(String))` column (18M rows) is
21% faster than with the setting disabled (18% slower before this change),
and on the ClickStack `otel_logs` schema horizontal merges are 12% faster and
vertical merges no longer 11% slower.

Related: ClickHouse#108468

Co-Authored-By: Claude Opus 5.5 <[email protected]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 18, 2026
The `!global_ctx->projection` guard in `createMergedStream` kept every child
`MergeTask` that merges projection parts (the projection-part merges of a parent
merge and the temporary-part merges of `MergeProjectionPartsTask`) on the default
sorting queue, even with `merge_use_batch_sorting_queue = 1`. It was added in
ClickHouse#108468 for missing coverage, not for a defect. Normal projection merges are
`Ordinary` and row-preserving; aggregate projections and children of
DEDUPLICATE/CLEANUP parents still have `merge_may_reduce_rows` and keep the
default queue. `_parent_part_offset` is remapped when the projection parts are
read, not by the sorting algorithm.

The new test compares the merged projection parts (rows and positions) between
the two queues for a normal projection with another sorting key, a
`_parent_part_offset` projection and a commit-order projection, in horizontal and
vertical merges, asserts via part_log that the projections were merged rather
than rebuilt, and covers the temporary parts that `MATERIALIZE PROJECTION`
writes for a part larger than `min_insert_block_size_rows`.

Related: ClickHouse#127826
Related: ClickHouse#108468

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

Labels

can be tested Allows running workflows for external contributors manual approve Manual approve required to run CI 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.

3 participants