Skip to content

K-way merge optimizations: batch lookahead, sorted array of cursors, batch queue for special merges - #115869

Merged
alexey-milovidov merged 18 commits into
masterfrom
kway-merge-queue-optimizations
Sep 7, 2026
Merged

alexey-milovidov merged 18 commits into
masterfrom
kway-merge-queue-optimizations

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Three k-way merge optimizations motivated by the analysis in https://maksimkita.com/blog/k-way-merge.html, plus a follow-up refinement:

  1. O(1) whole-cursor batch detection (SortingQueueImpl::updateBatchSize). When the batch exceeds the linear detection limit, one comparison against the last row of the front cursor takes the entire remainder as a single batch. Merging cursors with non-intersecting key ranges (e.g. parts sorted by the primary key that do not overlap) now costs O(1) comparisons per batch instead of a linear detection followed by a binary search over the remainder.

  2. Sorted array of cursors as an alternative queue container. Reinserting the advanced front cursor costs one comparison when it is still the minimum, and otherwise ceil(log2(K - 1)) further comparisons (a binary search among the other cursors; none at all with two cursors) plus a shift of plain pointers, versus up to 2 * log2(K) comparisons for the heap. It is selected only for cursors with expensive comparators: the generic multi-column SortCursor and SortCursorWithCollation. Above 256 cursors it falls back to the heap behavior (a sorted array is a valid heap layout, so the switch is free). Measured on 64-way in-order merges of parts with fully overlapping ranges: 7-8% faster for two- and four-column sorting keys, no change for the specialized single-column cursors (which stay on the heap: e.g. strings measured 18% slower with the array, since their comparisons usually resolve within the first bytes).

  3. Batch sorting queue for the special merge algorithms (Replacing/Summing/Aggregating/Collapsing/VersionedCollapsing/Graphite). They advanced the queue one row at a time; now the queue is restructured once per batch. ReplacingSortedAlgorithm additionally fast-forwards to the last row of a run of equal keys within a batch when processing a row has no effects besides replacing the selected row (no version and no is_deleted columns, no row sources, no vertical FINAL, not reading in reverse order) — the run end is found with getEqualRangeEndAssumeSorted instead of per-row comparisons. The batch detection itself is enabled only where it can pay off: for expensive (multi-column or collated) comparators, and for ReplacingMergeTree when a level-zero source starts with runs of equal keys dense enough for skipping them to be cheaper than merging them row by row (the probe for the end of a run costs about a fifth of a merge iteration and also runs on the rows outside runs, so a quarter of the sampled rows have to be strictly inside one; the sample is the first rows of the source, at most 8192 and at most an eighth of the chunk). The run skipping follows that same switch rather than the batch size, because a queue with one cursor left reports its whole remainder as one batch no matter what - which is every INSERT into a ReplacingMergeTree with optimize_on_insert (on by default), where MergeTreeDataWriter::mergeBlock merges one already sorted block. Otherwise the queue behaves exactly like the heap on master. Measured in CPU time of a single-threaded SELECT ... FINAL over fully overlapping parts: 42% less with runs of ~10 duplicates per key inside 8 parts of ReplacingMergeTree, 1-3% less with a two-column key, within 1% of master for SummingMergeTree and CollapsingMergeTree with a single-column key where every part holds each key once, and about 3% more (1.7 ns per row, the remaining cost of the batch interface in the leanest merge loop) for ReplacingMergeTree in that last shape.

  4. Galloping detection of the batch end: after the linear detection caps out, the end of the batch is bracketed with exponentially growing steps, so the search costs O(log(batch size)) comparisons on rows near the current position instead of O(log(rows left)) comparisons on far rows that miss caches. The common cases of the detection (a single cursor, a batch of one row) are inlined into the merge loops; only the search for the end of a longer batch is out of line.

Measured in the time of MergeTreeDataWriter::mergeBlock itself (MergeTreeDataWriterMergingBlocksMicroseconds, minimum of 9 runs) for an INSERT of 20 M rows into a ReplacingMergeTree with a single UInt64 key, against a build of master with the same flags:

already sorted block branch / master
unique keys 1.00
unique keys with one duplicate every 4096 rows 1.00
runs of ten equal keys 0.30

and, for INSERTs squashed into 8192-row blocks instead, 1.02 with unique keys and 0.36 with runs of ten.

Verification: a 25-case differential harness (multi-column/string/nullable/collation/LowCardinality ORDER BY checksums incl. row order, external sort, >256-cursor merges, FINAL for all six engines, vertical merges, enable_vertical_final, is_deleted, insert-time merging with a permutation) produces identical results against master; ~560 stateless tests around merges, sorting and FINAL give identical results for this branch and master; 04506_read_in_reverse_order_final covers the reverse reading order added on master in the meantime. A new performance test kway_merge_expensive_comparator covers the array-container cases, the insert-time merge with and without runs of duplicates, and guards the heap cases.

Changelog category (leave one):

  • Performance Improvement

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

Speed up k-way merges: merging sorted streams with multi-column or collated sorting keys uses a sorted array of cursors instead of a heap (7-8% faster), merges of non-intersecting parts detect the whole cursor as one batch in O(1) comparisons, and runs of duplicate keys inside a part are skipped, which makes SELECT ... FINAL from ReplacingMergeTree use up to 40% less CPU and the insert-time deduplication of optimize_on_insert about three times faster when there are many duplicates.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.9.1.923 (included in 26.9 and later)

robot-clickhouse and others added 4 commits August 21, 2026 19:19
…(1) check

When the batch grows beyond the first row, compare the last row of the
front cursor with the next cursor before any further detection: if even
the last row is less, the whole remainder of the cursor forms one batch.
This makes merging cursors with non-intersecting key ranges (e.g. parts
sorted by the primary key that do not overlap) cost O(1) comparisons per
batch instead of a linear detection followed by a binary search over the
remainder. When the check does not hit, it costs one comparison and
excludes the last row from the binary search range.

Motivated by https://maksimkita.com/blog/k-way-merge.html

Co-Authored-By: Claude Fable 5 <[email protected]>
Add a sorted array container to `SortingQueueImpl` as an alternative to
the binary heap. Reinserting the advanced front cursor costs exactly
ceil(log2(K)) comparisons (a binary search) plus a shift of plain
pointers, versus up to 2 * log2(K) comparisons for the heap, and one
comparison when the front cursor is still the minimum (the common case
for clustered data) in both containers. Above 256 cursors the queue
falls back to the heap behavior; a sorted array is a valid heap layout,
so the switch is free.

The array container is selected via `SortQueueVariants` only for the
cursors whose comparator is expensive: the generic multi-column
`SortCursor` (a loop with a virtual call per column) and
`SortCursorWithCollation`. Measured on 64-way in-order merges of parts
with fully overlapping key ranges: 7-8% faster for two- and four-column
sorting keys, with no change for the specialized single-column cursors
(including strings, whose comparisons usually resolve within the first
bytes and stay on the heap - measured 18% slower with the array).

Motivated by https://maksimkita.com/blog/k-way-merge.html

Co-Authored-By: Claude Fable 5 <[email protected]>
…ionedCollapsing/Graphite merges

The special merge algorithms advanced the queue one row at a time, which
restructured the heap (up to 2 * log2(K) comparisons) on every row. Switch
`IMergingAlgorithmWithSharedChunks` and `IMergingAlgorithmWithDelayedChunk`
to the batch sorting queue: within a batch, `next(1)` only advances the
cursor position, and the queue is restructured once per batch. The per-row
logic of the algorithms is unchanged.

In `ReplacingSortedAlgorithm`, additionally fast-forward to the last row of
a run of equal keys within a batch when processing a row has no effects
besides replacing `selected_row` (no version and no `is_deleted` columns, no
row sources for a vertical merge, no vertical FINAL): the intermediate rows
of the run would each merely replace `selected_row` with the next one. The
run end is found with `getEqualRangeEndAssumeSorted` instead of per-row
comparisons. Sources with a non-zero part level keep the per-row path to
preserve the exact behavior of `rowsHaveDifferentSortColumns`, which treats
rows of such sources as always distinct without comparing.

Measured on FINAL over 8 parts of ReplacingMergeTree with runs of ~10
duplicates per key inside each part: 33% faster single-threaded, 27% faster
with 8 threads. FINAL over non-intersecting parts is unchanged.

Motivated by https://maksimkita.com/blog/k-way-merge.html

Co-Authored-By: Claude Fable 5 <[email protected]>
After the linear detection caps out, bracket the end of the batch with
exponentially growing steps before the binary search. Compared to an
immediate binary search over the whole remainder, this costs
O(log(batch size)) comparisons on rows near the current position instead
of O(log(rows left)) comparisons on far rows that miss caches - which
matters when the batch is much smaller than the block.

Also move the whole-remainder check after the linear detection: this way
small batches (the common case for interleaved keys) cost exactly as many
comparisons as before, and the check is only paid when the batch is
already known to exceed the linear detection limit.

Measured together with the previous commits on FINAL over 8 parts of
SummingMergeTree with runs of 4 duplicates per key: 6% faster when the
parts do not intersect, 5% slower in the worst case of fully interleaved
hash-distributed keys (a follow-up that skips per-row key comparisons
using the run information can win both shapes).

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

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c0d7e0f]

Summary: ✅


AI Review

Summary

This PR reworks the hot k-way merge path by adding the sorted-array queue for expensive comparators, batch-aware queue reuse in the special merge algorithms, and run skipping for ReplacingMergeTree. I re-checked the current code against the earlier review threads and did not find a remaining correctness, safety, or semantics regression: the one-column special merges stay on the heap again, and the single-input optimize_on_insert path now gates run skipping on batch_detection_enabled instead of current_batch_size.

Missing context / blind spots
  • ⚠️ The full Praktika run for head c0d7e0fe804ff2642e2687bdee4782a2abb31970 is still in progress, so I could not validate the final commit set against the latest complete CI/performance artifacts. That gap closes once the current PR report finishes.
Final Verdict

✅ No actionable code-review findings on the current diff.

LLVM Coverage Report

Measured on commit c0d7e0f.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 178/185 (96.22%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 21, 2026
Comment thread src/Core/SortCursor.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c0d7e0fe8 with master e568d262d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

29 object files changed (+1.92 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp.o 3.05 MiB 3.74 MiB +709.80 KiB (+22.73%)
src/CMakeFiles/dbms.dir/Processors/Transforms/SortingTransform.cpp.o 1.55 MiB 2.01 MiB +472.75 KiB (+29.80%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/MergeTreeFinalMerge.cpp.o 771.80 KiB 818.61 KiB +46.81 KiB (+6.06%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTask.cpp.o 1.78 MiB 1.82 MiB +46.64 KiB (+2.56%)
src/CMakeFiles/dbms.dir/Processors/Transforms/MergeSortingTransform.cpp.o 582.92 KiB 629.45 KiB +46.52 KiB (+7.98%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/LimitStep.cpp.o 484.10 KiB 530.59 KiB +46.49 KiB (+9.60%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/SortingStep.cpp.o 641.61 KiB 688.08 KiB +46.48 KiB (+7.24%)
src/CMakeFiles/dbms.dir/QueryPipeline/QueryPipelineBuilder.cpp.o 734.23 KiB 780.70 KiB +46.48 KiB (+6.33%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromMergeTree.cpp.o 2.22 MiB 2.27 MiB +46.47 KiB (+2.04%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/GatherSendStep.cpp.o 446.52 KiB 492.99 KiB +46.47 KiB (+10.41%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/GatherReceiveStep.cpp.o 442.61 KiB 489.08 KiB +46.47 KiB (+10.50%)
src/CMakeFiles/dbms.dir/Interpreters/SortedBlocksWriter.cpp.o 510.78 KiB 557.24 KiB +46.46 KiB (+9.10%)
src/CMakeFiles/dbms.dir/Processors/Merges/MergingSortedTransform.cpp.o 417.19 KiB 463.63 KiB +46.45 KiB (+11.13%)
src/CMakeFiles/dbms.dir/Core/SortCursor.cpp.o 378.43 KiB 423.88 KiB +45.45 KiB (+12.01%)
src/CMakeFiles/dbms.dir/Processors/Transforms/FinishSortingTransform.cpp.o 414.80 KiB 455.03 KiB +40.23 KiB (+9.70%)
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/ReplacingSortedAlgorithm.cpp.o 124.59 KiB 158.21 KiB +33.62 KiB (+26.99%)
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/IMergingAlgorithmWithSharedChunks.cpp.o 84.23 KiB 113.29 KiB +29.07 KiB (+34.51%)
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/IMergingAlgorithmWithDelayedChunk.cpp.o 70.50 KiB 98.33 KiB +27.82 KiB (+39.46%)
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/SummingSortedAlgorithm.cpp.o 329.46 KiB 346.44 KiB +16.98 KiB (+5.15%)
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/CollapsingSortedAlgorithm.cpp.o 106.87 KiB 123.83 KiB +16.96 KiB (+15.87%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Translation unit Master PR Δ vs median
src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp 23.9 s 32.7 s +9.1 s (+39%)

Slowest changed entities of src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp:

  • InstantiateFunction std::__variant_detail::__move_assignment<std::__variant_detail::__traits<DB::SortingQueueImpl<DB::S…: +0.7 s
  • InstantiateFunction std::__variant_detail::__assignment<std::__variant_detail::__traits<DB::SortingQueueImpl<DB::Specia…: +0.7 s
  • InstantiateFunction std::__variant_detail::__visitation::__base::__visit_alt_at<(lambda at /ClickHouse/contrib/llvm-pro…: +0.7 s
  • InstantiateFunction std::__variant_detail::__visitation::__base::__make_fdiagonal<(lambda at /ClickHouse/contrib/llvm-p…: +0.7 s
  • InstantiateFunction std::__variant_detail::__visitation::__base::__make_fdiagonal_impl<(lambda at /ClickHouse/contrib/l…: +0.7 s
  • InstantiateFunction std::__variant_detail::__move_assignment<std::__variant_detail::__traits<DB::SortingQueueImpl<DB::S…: -0.7 s (-100%)
  • InstantiateFunction std::__variant_detail::__assignment<std::__variant_detail::__traits<DB::SortingQueueImpl<DB::Specia…: -0.7 s (-100%)
  • InstantiateFunction std::__variant_detail::__visitation::__base::__visit_alt_at<(lambda at /ClickHouse/contrib/llvm-pro…: -0.7 s (-100%)

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 38 analysed

1 improved query(s). K_source=6 K_base=30 flagged=1/65

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 31 improvement 305 268 -12.1% <0.0001

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

🟢 No significant changes

Debug info
  • StressHouse run: 3bfdd6c9-4853-4ed6-aca7-a8e52ffc3c50
  • MIRAI run: 566229b2-008d-4ab5-a5e8-2e8edad5c74c
  • PR check IDs:
    • clickbench_1472966_1788756235
    • clickbench_1472972_1788756235
    • clickbench_1472981_1788756235
    • tpch_adapted_1_official_1472989_1788756235
    • tpch_adapted_1_official_1473001_1788756235
    • tpch_adapted_1_official_1473037_1788756235

alexey-milovidov and others added 3 commits August 24, 2026 17:14
…ainer

`IMergingAlgorithmWithSharedChunks` and `IMergingAlgorithmWithDelayedChunk` always
merge through the generic `SortCursor`, so marking that cursor expensive also switched
one-column `Replacing`/`Summing`/`Aggregating`/`Collapsing`/`Graphite` merges to the
sorted array container, contrary to the intent that cheap comparators stay on the heap.
Add a runtime `enable_array_container` knob to `SortingQueueImpl` (the Array container
already downgrades itself at runtime above 256 cursors) and gate it in those bases on
`sortDescriptionCompareIsExpensive`, which mirrors the cursor selection in
`SortQueueVariants`: only multi-column or collated descriptions count as expensive.
Extend the `kway_merge_expensive_comparator` performance test with `FINAL` over fully
overlapping parts of `ReplacingMergeTree` for both a single-column key (guards the heap)
and a two-column key (covers the array).

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

Copy link
Copy Markdown
Member Author

🕵 The only red check on the previous head e70abc7a was Stress test (arm_debug): logical error Equal values are not contiguous within the range assumed to be sorted via LimitBySortedStreamTransform → ColumnVector<char8_t>::getEqualRangeEndAssumeSorted. This PR does not touch LimitByTransform or findEqualRangeEndAssumeSorted.h, and the same logical error fails stress tests on master and dozens of unrelated PRs daily (tracked in #115455). Merged master to get a fresh CI run.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115869&sha=e70abc7a62dafc747f1775717cb17dd6183c7d42&name_0=PR&name_1=Stress%20test%20%28arm_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress: #113242. This is the same defect as the buckets in #115455, with a third fuzzed target type.

From fatal.log the aborting query is

SELECT count() FROM (SELECT s FROM merge_distinct__fuzz_3 ORDER BY s ASC NULLS FIRST LIMIT 1 BY s LIMIT 100)
SETTINGS max_threads = 1, distributed_aggregation_memory_efficient = 0

with log_comment 04870_distinct_merge_over_distributed.sql. There merge_distinct is a Merge over a Distributed whose child column is s String, and the fuzzer's clone declares s UInt8, which is why the leaf frame is ColumnVector<char8_t>. StorageMerge::getQueryProcessingStage returns a stage above FetchColumns, so the children are read sorted and merged as sorted streams, while convertAndFilterSourceStream casts each child's String to the declared UInt8 underneath that claim. The cast does not preserve order ('10' < '2' as strings, 10 > 2 as numbers), so the merge combines runs that are not sorted by s, equal keys stop being adjacent, and LimitBySortedStreamTransform asserts. The earlier buckets are the same query with Nullable(Float32) (STID 2508-3319) and Decimal32 (STID 2508-3775). #113242 refuses the pushdown for any child conversion that is not order preserving, so one gate covers all three.

I verified both directions on two debug builds of today's master (708305557ad) differing only by that PR's StorageMerge.cpp hunk, two shard test_cluster_two_shards_localhost:

merge_distinct, types match the query above, s retyped to UInt8 Merge sorted streams in plan: retyped / match
master, build id 76144d95 21 abort, LimitBySortedStreamTransform::transform -> ColumnVector<char8_t>::getEqualRangeEndAssumeSorted at ColumnVector.cpp:459, server dies 1 / 1
+ #113242, build id a192cabf 21 21, server alive 0 / 1

The local leaf frames are the ones in your report, down to ColumnVector.cpp:459 and the ColumnVector<char8_t> instantiation. The matching-types column is the control: it is 21 on both arms, so the retype is what triggers it, and the last column shows the gate removes the sortedness claim only for the retyped carrier.

What holds #113242 up is one red, Fast test / 00717_merge_and_distributed. That is the pre-existing _table prefilter defect, reachable on master without this PR and without any cast; #113735 fixes it and is still open with changes requested. Making #113242 green ahead of it would mean accepting UInt64 -> Int64 as order preserving, which is the case the gate exists to refuse.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check on 207d7fd4 was Stress test (amd_debug): Logical error: 'Inconsistent AST formatting: the query: (STID: 1941-26fa). This is a master-wide fuzzer flake, not related to this PR: on 2026-08-27 alone it failed on master (pull_request_number = 0) and on ~130 unrelated pull requests, and it is tracked by #116732 (closed on 2026-08-28; the hourly failure rate on master dropped from ~14/hour to ~1/day right after). This PR touches only SortCursor.h and the merge algorithms under src/Processors/Merges/Algorithms, nothing in AST formatting.

The AI review verdict on 207d7fd4 is ✅ (no actionable findings) and there are no unresolved review threads. Merged master (no conflicts, and no master commit touched any file of this PR since the previous merge) to get a fresh CI run that also picks up the mitigation of the flake above.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Two queries slowed down. One is a query with FINAL. Looks not acceptable.

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
…timizations

# Conflicts:
#	src/Processors/Merges/Algorithms/ReplacingSortedAlgorithm.h
…ard the run skip against reverse reads

The performance test `merge_tree_reorder_columns_merge` (`SELECT count() FROM ... FINAL`
over two fully interleaved parts of a `ReplacingMergeTree` with a five-column sorting key
of `LowCardinality(String)` columns) was 70-90% slower in every CI run of this branch:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115869&sha=9f73523881d6029537e5ebe38d5fc65681c7cd9d&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%206%2F6%29

With two cursors and interleaved keys every batch has one row. The heap queue on
master reinserts the advanced cursor with a single comparison. The sorted array container
performed two: the batch detection had already established that the next row of the front
cursor is not less than the second cursor's row, and then `arrayUpperBound` compared the
two again as the first probe of the binary search. The same redundant probe followed a
failed in-order check in the `Default` strategy. Start the binary search at the third
cursor instead: reinsertion now costs `ceil(log2(K - 1))` comparisons, and none at all with
two cursors, which restores parity with the heap in the interleaved case.

`ReplacingSortedAlgorithm` also learned `read_in_reverse` on master (#58035): in that mode
the first row of a run within a source wins instead of the last one, so the fast-forward to
the last row of a run must stay disabled there. Covered by `04506_read_in_reverse_order_final`.
Profiling `SELECT * FROM replacing_cheap_key FINAL` (four fully overlapping parts, a
single `UInt64` key, one thread) showed `SortingQueueImpl::updateBatchSize` as a separate
hot function next to `ReplacingSortedAlgorithm::merge`, while on master the whole heap
maintenance is inlined into `merge`. With interleaved keys every batch has one row, so the
call, its prologue and the register pressure of the galloping and binary search were paid
on every row. Split the function: the common cases (a single cursor, and a batch of one row
that costs exactly one comparison, the same the heap spends on its in-order check) are
inlined, the search for the end of a longer batch stays out of line.

The sorted array container also swaps the two front cursors directly when the advanced
cursor lands right behind the second one instead of calling `memmove` for one element.
The special merge algorithms consume rows one by one, so a detected batch pays off only
by saving comparisons (through the sorted array of an expensive comparator) or by letting
`ReplacingSortedAlgorithm` skip runs of equal keys. With a cheap single-column key and
interleaved keys between the parts the detection was pure overhead: measured on four fully
overlapping parts, `SELECT * FROM t FINAL` cost 4-5% more CPU than on master for
`ReplacingMergeTree` with a version column and for `CollapsingMergeTree`, while the same
shape with runs of ten duplicates per key in a `ReplacingMergeTree` without a version column
costs 44% less thanks to the run skipping.

Add a runtime switch to the batch queue: without the detection it reports batches of one
row (or the whole remainder of the last cursor) and restructures itself after every row with
the in-order check, exactly like the default heap strategy. The algorithms enable the
detection for expensive comparators, and `ReplacingSortedAlgorithm` also when it can skip
runs.
`ReplacingSortedAlgorithm` kept the batch detection on whenever it could skip runs of equal
keys, which costs about 5% CPU on the common shape where every part holds each key once
(e.g. periodic snapshots inserted as separate parts) and pays off only when a part contains
adjacent duplicates. Check the first rows of every level-zero source for adjacent equal sort
keys at initialization and enable the detection only when some source has them; otherwise
the queue works exactly like the heap on master. Sources with a non-zero part level are
assumed to have no duplicates, and rows sorted through a permutation are not adjacent.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The FINAL slowdown was real and I found and fixed its cause; the second query is noise.

merge_tree_reorder_columns_merge #0 (SELECT count() FROM test_reorder_columns_in_merge FINAL: two fully interleaved parts of a ReplacingMergeTree, five-column LowCardinality(String) key). It had been 0.53-0.59x in every CI run of this branch since the first commit, on both architectures (perf_test_perf_changes_v1), and the master series is one of the most stable ones (spread 0.003 s, flagged in 4 of 6554 ARM runs in 30 days), so it was never flakiness. Cause: with two cursors and interleaved keys every batch has one row, and the sorted-array container reinserted the advanced cursor with arrayUpperBound(top, 1), i.e. it compared it with the second cursor again although the batch detection had just established that it is not less than it. Two comparisons per row instead of the heap's one, each over four 36-byte strings. Fixed in 3d464dd: the binary search starts at the third cursor (ceil(log2(K - 1)) comparisons, none at all for two cursors). Locally (perf.py, 11 runs, three servers): pre-fix 1.50x of master, fixed 1.035x, and after the two follow-up commits below the CPU time of this query is within 1% of master.

set_index #1 is unrelated (a Set lookup, no sorting or merging in the query) and is flagged as changed in 4168 of 9258 ARM runs of the last 30 days, i.e. on ~45% of all PRs.

While at it I looked at the PR's own performance test, kway_merge_expensive_comparator, whose FINAL queries over four fully overlapping parts had also been 8-14% slower in every CI run. Measured in CPU time per query (OSCPUVirtualTimeMicroseconds from query_log, max_threads = 1, 15-21 rounds, load-independent) on master vs the branch:

  • the same redundant comparison for the two-column key (fixed by 3d464dd);
  • updateBatchSize was a separate non-inlined hot function next to merge, paid on every row for a batch of one row; a645089 inlines the common cases (single cursor, batch of one row) and keeps only the search for the end of a longer batch out of line;
  • for a cheap single-column key the batch detection is pure overhead when the parts hold each key once, since the special algorithms consume rows one by one: 11d7500 adds a runtime switch so that the detection is enabled only for expensive comparators or when ReplacingSortedAlgorithm can skip runs, and 609fa89 enables the latter only when a level-zero part actually starts with adjacent equal keys (checked once on the first 8192 rows at initialization). Otherwise the queue does exactly what the heap does on master.

Final CPU-time numbers (branch / master, single thread, four or eight fully overlapping parts):

shape branch / master
ReplacingMergeTree, single UInt64 key, runs of 10 duplicates inside 8 parts 0.58
ReplacingMergeTree, two-column key, each key once per part 0.97-0.99
two interleaved parts, five LowCardinality(String) columns (the CI query) 1.00
SummingMergeTree / CollapsingMergeTree, single key, each key once per part 0.99-1.01
ReplacingMergeTree, single UInt64 key, each key once per part 1.03 (1.7 ns per row: the remaining cost of the batch interface in the leanest loop)

Also merged master, which brought the reverse reading order for FINAL (#58035) into ReplacingSortedAlgorithm: in that mode the first row of a run wins, so the run skipping is disabled there (covered by 04506_read_in_reverse_order_final). ~560 stateless tests around merges, sorting and FINAL give identical results for the branch and master. The PR description is updated accordingly.

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

@alexey-milovidov alexey-milovidov self-assigned this Sep 6, 2026
alexey-milovidov and others added 2 commits September 7, 2026 00:17
`ReplacingSortedAlgorithm::merge` decided to look for the end of a run of
equal keys from the batch size alone. That is not the same as "the batch
detection found a profitable run": a queue with one cursor left reports its
whole remainder as one batch no matter what, because there is nothing to
compare it against.

So the last commits, which disable the detection when it cannot pay off, did
not reach the single-input merge - and that is the most common one of all:
`MergeTreeDataWriter::mergeBlock` builds a `ReplacingSortedAlgorithm` with
`num_inputs == 1` for every `INSERT` into a `ReplacingMergeTree`, and
`optimize_on_insert` is on by default. An already sorted block of unique keys
therefore still paid `getEqualRangeEndAssumeSorted` on every row, only to find
a run of one row every time.

Record in `IMergingAlgorithmWithSharedChunks` whether the queue detects
batches at all, and let the run skipping depend on that instead of on the
batch size. An insert of unique keys now takes exactly the same path as it
does without the batch queue, while an insert whose block does contain runs
of duplicates - where the detection stays on - still skips them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits September 7, 2026 00:23
The test measured `FINAL` over several parts, but the single-input merge that
`optimize_on_insert` runs on every `INSERT` into a `ReplacingMergeTree` is the
default path and the one where a batch is always the whole remaining block.
Add the two shapes that matter there: a block of unique keys, where the batch
interface must cost nothing over the plain heap, and a block with runs of ten
duplicates per key, where skipping to the end of a run is what pays off.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…uplicate

`anySourceHasRunsOfEqualKeys` turned the batch detection on as soon as it saw
one pair of adjacent equal keys among the first rows of a source. That is not
what the switch has to answer: skipping a run replaces the merge iterations of
the rows strictly inside it by one probe for the end of the run, and that probe
also runs on the rows that turn out not to be inside one. Measured on a single
`UInt64` key, a merge iteration costs about 31 ns and a probe about 6 ns, so
runs of two rows never pay for themselves and longer ones have to cover about a
fifth of the rows.

Count the skippable rows in the sample instead and require a quarter of it,
which is above that break-even for every run length. A block of unique keys
holding one duplicate every 4096 rows - detection on, nothing to skip - cost
1.18x of master in the insert-time merge and now costs 1.00x, while a block
with runs of ten keeps costing 0.30x.

Also cap the sample at an eighth of the chunk. It was a fixed 8192 rows, which
is a whole extra comparison pass over a chunk of that size: inserts of 8192-row
blocks with unique keys cost 1.06x of master in the insert-time merge and now
cost 1.02x, with runs of ten still at 0.36x.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
With fewer than eight rows in a chunk the sample was empty, and the comparison
of the skippable rows against its size then held trivially (`0 >= 0`), so one
tiny source turned the detection on for the whole merge.

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

Copy link
Copy Markdown
Member Author

🕵 The only red check on 609fa89b was Stress test (arm_tsan), and it failed at Cannot start clickhouse-server: the restarted server could not load metadata because test_1.test_s3_base_nc referenced a named collection that no longer existed.

Code: 669. DB::Exception: There is no named collection `nc_04626_s3_base_setting_test_1`:
Cannot attach table `test_1`.`test_s3_base_nc` ... ENGINE = S3(nc_04626_s3_base_setting_test_1, ...)

That is 04626_s3_base_setting, not this pull request: the stress test can kill the server mid-test, and the block that created a table from a SQL-created named collection could leave the table behind while the collection was dropped against the restarted server. It has already been removed from that test on master by #117234, which was merged on 2026-09-06 at 13:56 UTC - after this branch's last CI run. Merging master (cc2a386) picks it up. The signature is new and confined: three occurrences in the last 30 days in checks, on three pull requests, none on master.

Also addressed the AI review's "Request changes" on the single-input optimize_on_insert path - see the reply in the review thread for the fix and the measurements.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 7, 2026
Merged via the queue into master with commit c220c3f Sep 7, 2026
175 checks passed
@alexey-milovidov
alexey-milovidov deleted the kway-merge-queue-optimizations branch September 7, 2026 19:44
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
@nihalzp nihalzp added the post-approved Approved, but after the PR is merged. label Sep 21, 2026
@nihalzp nihalzp self-assigned this Sep 21, 2026
BorisTyshkevich pushed a commit to BorisTyshkevich/ClickHouse that referenced this pull request Nov 15, 2026
The collation sort (#2, 5M rows) and the single-column string sort (ClickHouse#3,
20M rows) take 1.2-1.9 s on MasterCI on both arches. They get
disabled="1" (text and number unchanged) and are appended as ClickHouse#9 and ClickHouse#10
on a quarter of the rows with max_block_size = 16384, a quarter of the
default 65409. `numbers_mt` hands out blocks of exactly max_block_size
rows, so each copy has as many blocks as its original (77 and 306): the
same number of cursors in every per-stream merge and the same 16-stream
final merge, with a quarter of the rows per block. EXPLAIN PIPELINE of
each original and its copy is identical (16 streams).

Measured on official MasterCI release builds, two servers pinned to 24
cores of one NUMA node, perf.py, 25 runs: copy / original time 0.248
(#2) and 0.252 (ClickHouse#3), projected CI medians 380 / 487 ms amd, 298 / 483 ms
arm. On the builds before/after ClickHouse#115869 (sorted array of cursors) #2 is
1.161x faster and its copy 1.159x; on those before/after ClickHouse#126829
(cheaper collation) 2.179x and 2.111x; ClickHouse#3 and its copy show no change
on either pair (1.005 / 1.008, 1.004 / 1.001), as the heap guard should.

#0 and #1 stay as they are: on this rig the ClickHouse#115869 change did not show
on them beyond the A/A resolution, so there was no measured guarantee
that copies would keep their sensitivity.

About 32 s (amd) and 29 s (arm) of query time less per master
performance job; 9 queries stay enabled, so all of them still run.

Related: ClickHouse#129258

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

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. post-approved Approved, but after the PR is merged. 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.

5 participants