Repository navigation
K-way merge optimizations: batch lookahead, sorted array of cursors, batch queue for special merges - #115869
Conversation
…(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]>
|
Workflow [PR], commit [c0d7e0f] Summary: ✅
AI ReviewSummaryThis 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 Missing context / blind spots
Final Verdict✅ No actionable code-review findings on the current diff. LLVM Coverage ReportMeasured on commit c0d7e0f.
Changed lines: Changed C/C++ lines covered: 178/185 (96.22%) · Uncovered code |
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| 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%)
|
📊 Cloud Performance Report 🟢 AI verdict: 1 improved query(s). K_source=6 K_base=30 flagged=1/65 clickbench🟢 1 improved Flagged queries (1 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_official🟢 No significant changes Debug info
|
…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]>
|
🕵 The only red check on the previous head @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. |
|
The fix is in progress: #113242. This is the same defect as the buckets in #115455, with a third fuzzed target type. From 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 = 0with I verified both directions on two debug builds of today's master (
The local leaf frames are the ones in your report, down to What holds #113242 up is one red, |
|
🕵 The only red check on The AI review verdict on |
|
Two queries slowed down. One is a query with FINAL. Looks not acceptable. |
…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.
|
🕵 The FINAL slowdown was real and I found and fixed its cause; the second query is noise.
While at it I looked at the PR's own performance test,
Final CPU-time numbers (branch / master, single thread, four or eight fully overlapping parts):
Also merged |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The code LGTM.
`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]>
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]>
|
🕵 The only red check on That is Also addressed the AI review's "Request changes" on the single-input |
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]>
Three k-way merge optimizations motivated by the analysis in https://maksimkita.com/blog/k-way-merge.html, plus a follow-up refinement:
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.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 to2 * log2(K)comparisons for the heap. It is selected only for cursors with expensive comparators: the generic multi-columnSortCursorandSortCursorWithCollation. 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).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.ReplacingSortedAlgorithmadditionally 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 nois_deletedcolumns, no row sources, no vertical FINAL, not reading in reverse order) — the run end is found withgetEqualRangeEndAssumeSortedinstead of per-row comparisons. The batch detection itself is enabled only where it can pay off: for expensive (multi-column or collated) comparators, and forReplacingMergeTreewhen 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 everyINSERTinto aReplacingMergeTreewithoptimize_on_insert(on by default), whereMergeTreeDataWriter::mergeBlockmerges one already sorted block. Otherwise the queue behaves exactly like the heap on master. Measured in CPU time of a single-threadedSELECT ... FINALover fully overlapping parts: 42% less with runs of ~10 duplicates per key inside 8 parts ofReplacingMergeTree, 1-3% less with a two-column key, within 1% of master forSummingMergeTreeandCollapsingMergeTreewith 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) forReplacingMergeTreein that last shape.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::mergeBlockitself (MergeTreeDataWriterMergingBlocksMicroseconds, minimum of 9 runs) for anINSERTof 20 M rows into aReplacingMergeTreewith a singleUInt64key, against a build ofmasterwith the same flags: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 BYchecksums 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_finalcovers the reverse reading order added on master in the meantime. A new performance testkway_merge_expensive_comparatorcovers the array-container cases, the insert-time merge with and without runs of duplicates, and guards the heap cases.Changelog category (leave one):
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 ... FINALfromReplacingMergeTreeuse up to 40% less CPU and the insert-time deduplication ofoptimize_on_insertabout three times faster when there are many duplicates.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/115869]
Version info
26.9.1.923(included in26.9and later)