Skip to content

Batch LowCardinality columns in merges with merge_use_batch_sorting_queue - #127826

Merged
Algunenano merged 2 commits into
ClickHouse:masterfrom
cwurm:batch-sorting-queue-lowcardinality
Nov 13, 2026
Merged

Algunenano merged 2 commits into
ClickHouse:masterfrom
cwurm:batch-sorting-queue-lowcardinality

Conversation

@cwurm

@cwurm cwurm commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

merge_use_batch_sorting_queue inserts runs of consecutive rows from the same source part with a single insertRangeFrom instead of row by row. But MergedData::rowsToInsertBeforeFlush returns 1 for any batch with a LowCardinality column (including inside Map/Array/Tuple) whenever merge_max_block_size_bytes is set (default 10 MiB), so such merges fall back to single-row batches, which cost more than the default queue. Enabling the setting makes these merges slower, even though dictionary-encoded columns are the ones that benefit most from batching.

This PR removes LowCardinality from that special case, so the existing per-row byte prediction covers it. For a LowCardinality column, the sum of byteSizeAt over the source rows is a close, mostly pessimistic estimate of its growth: a repeated value adds only an index entry. Wide values still cut the batch exactly where the row-by-row path does, including values inside Map(LowCardinality(String), String). Aggregate states and dynamic columns stay in the special case, because for them the source estimate can arbitrarily underestimate the growth of the destination (state data is copied into the destination arena, missing dynamic paths are filled with defaults). The PR also skips the byte prediction for single-row batches, where it can only return 1.

The LowCardinality special case was added during the review of #108468 (#108468 (comment)) only to make the batch queue reproduce the default queue's flush boundaries exactly. That is not a correctness property: the two queues already disagree on boundaries through the whole-chunk fast path. Merge results are unchanged, and query-time sorts are unaffected because they pass a byte limit of 0.

Benchmarks (medians of several runs, setting on vs. off on the same binary):

  • Metrics table with a Map(LowCardinality(String), LowCardinality(String)) column, 6-part horizontal merge of 18M rows: 6.07 s → 4.78 s (−21%). On master, enabling the setting makes this merge 18% slower.
  • ClickStack otel_logs (including its text indexes), 10-part merge of 3M rows: horizontal merge 9.54 s → 8.43 s (−12%). The vertical merge stays the same (8.39 s → 8.43 s), because only the sorting-key columns go through its sorted stage; on master, enabling the setting makes it 11% slower.

Merge results and peak memory are identical in all runs. A run of ten 50 MB values still gets one granule per value, as with the setting off.

Related: #108468

Changelog category (leave one):

  • Performance Improvement

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

Merges with merge_use_batch_sorting_queue enabled no longer fall back to row-by-row insertion for tables with LowCardinality columns, which made them slower than with the setting disabled. With the setting enabled, merged parts can be split into blocks differently than on previous versions. The data is the same, but in a ReplicatedMergeTree cluster with replicas on different versions this can show up as a harmless "not byte-identical" checksum mismatch, after which the replica downloads the merged part from another replica.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2218-master (included in 26.11 and later)

`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 only reproduced the default queue's flush boundaries
exactly, 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.

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

clickhouse-gh Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2f28fce]

Summary: ✅


AI Review

Summary

The PR enables batched merge insertion for LowCardinality columns using estimated byte growth, while retaining incremental measurement for aggregate states and dynamic columns. Commit 2f28fceab9411b8b923e4d917a60f2274f2cc52f addresses both previous findings: potentially unbounded destination growth and unnecessary sizing of single-row batches. Both threads are resolved. No new actionable findings remain.

Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 26, 2026
For aggregate states and dynamic columns, the source `byteSizeAt` can
arbitrarily underestimate the growth of the destination: aggregate state data
is copied into the destination arena, and the destination adds defaults for
dynamic paths missing in the source. A single batch could then exceed
`merge_max_block_size_bytes` by far before `hasEnoughRows` could intervene.
Keep measuring them row by row, and only drop `LowCardinality` from the
special case, for which the estimate is close and mostly pessimistic.

Also skip the byte prediction for single-row batches, where it can only
return 1 but still visited every nested element.

Make the stateless test 10 times smaller, because it ran too long in debug
builds with a randomized `merge_max_block_size = 2`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cwurm cwurm changed the title Estimate non-additive columns in batch merge byte limits Batch LowCardinality columns in merges with merge_use_batch_sorting_queue Oct 26, 2026
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Oct 26, 2026
@cwurm
cwurm marked this pull request as ready for review October 26, 2026 22:09
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-26T23:09:58.909064Z
We couldn’t complete this review. Comment @codex review to try again.
2f28fce Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@snelheidai

Copy link
Copy Markdown

Independent measurement of this PR's MergedData.cpp change (at 2f28fce, applied to master 7a987ba): AWS Graviton3, server pinned to 4 cores, OPTIMIZE TABLE ... FINAL, query_duration_ms, 10 paired rounds; ratio = geometric mean with bootstrap 95% CI.

Merge master this PR ratio
batch queue: 1 merged part + 10 small parts, LowCardinality(String) + String 1482 ms 888 ms 0.598 [0.595, 0.601]
batch queue: 50 interleaved parts, 9 columns incl. LowCardinality(String) 4057 ms 2152 ms 0.532 [0.528, 0.536]
batch queue: 50 interleaved parts, no LowCardinality 886 ms 883 ms 1.001 [0.991, 1.013]
default queue: first table 1202 ms 1202 ms 1.001 [0.995, 1.010]

On the first table the batch queue is 23% slower than the default queue on master, and 26% faster with this PR.

Flush boundaries: the merged parts (hash_of_all_files) were identical to master in 14 of 15 batch-queue merges (merge_max_block_size_bytes of 16 KiB, 128 KiB and 10 MiB; Nullable, 300-value, 70,000-value, key-column and per-granule-dictionary LowCardinality). The exception was the per-granule dictionaries (low_cardinality_max_dictionary_size = 64 at insert) with the 16 KiB limit: same rows, different block boundaries.

Exact boundaries are possible, at some cost. Counting an upper bound of the LowCardinality growth instead of the estimate (patch below) kept all 15 merges byte-identical to master, but measured 0.631 [0.627, 0.634] instead of 0.598 on the first table, 0.531 on the second and 1.006 [1.000, 1.012] on the table without LowCardinality. The estimate in this PR looks like the better trade-off; the bound is below in case exact boundaries are required.

This PR also helps the SummingMergeTree batch copy proposed in #131261, which goes through rowsToInsertBeforeFlush too and so copies LowCardinality rows one at a time on master: merging the first table as a SummingMergeTree took 2788 ms on master, 2699 ms with that copy and 1124 ms with this PR added (0.416 [0.413, 0.418] against the copy alone).

Tables and procedure

Background merges blocked with max_bytes_to_merge_at_max_space_in_pool = 1, max_bytes_to_merge_at_min_space_in_pool = 1; inserts single-threaded with large insert blocks. Each timed run attaches the parts to a fresh copy of the table with merge_use_batch_sorting_queue = 1 (or 0 for the default queue) via ALTER TABLE ... ATTACH PARTITION tuple() FROM and runs OPTIMIZE TABLE ... FINAL. Rounds rotate the order of the servers; the first round is discarded.

-- first table: one merged part of 6M rows + 10 parts of 20k rows (SummingMergeTree variant: same with ENGINE = SummingMergeTree)
CREATE TABLE mlc (sid UInt32, d Date, region LowCardinality(String), page String, hits UInt64, cost Float64)
ENGINE = MergeTree ORDER BY (sid, d) SETTINGS auto_statistics_types = '';
INSERT INTO mlc SELECT number % 200000, toDate('2026-10-01') + intDiv(number, 200000), concat('region-', toString(number % 23)),
    concat('/page/', toString(number % 200000)), number % 97 + 1, number / 13 FROM numbers(6000000);
OPTIMIZE TABLE mlc FINAL;
-- then, for k = 1..10:
INSERT INTO mlc SELECT cityHash64(number, k) % 200000 AS s, toDate('2026-10-30') + (number % 2), concat('region-', toString(s % 23)),
    concat('/page/', toString(s)), 1, 0.25 FROM numbers(20000);

-- second table: 50 parts, part k (0..49) holds a time slice of 10000 series
CREATE TABLE wide50 (sid UInt64, ts DateTime64(3), v1 Float64, v2 Float64, v3 Int32, v4 Int32, v5 UInt8, v6 Float32, host LowCardinality(String))
ENGINE = MergeTree ORDER BY (sid, ts);
INSERT INTO wide50 SELECT number % 10000, toDateTime64('2026-01-01 00:00:00', 3) + toIntervalMillisecond(intDiv(number, 10000) * 15000 + sipHash64(number) % 1000),
    (number % 997) / 7.0, (number % 991) / 3.0, toInt32(number % 1000), toInt32(sipHash64(number) % 100000), toUInt8(number % 7),
    toFloat32(number % 113), concat('host-', toString(number % 10000 % 50)) FROM numbers(k * 200000, 200000);

-- control without LowCardinality: same parts with columns (sid UInt64, ts DateTime64(3), value Float64), value = (number % 997) / 7.0
Exact-boundary bound (measured alternative to this PR's change)

It counts every index as UInt64, plus byteSizeAt of the inserted values, plus the whole destination dictionary. A range from another dictionary is limited to 64 rows when the destination dictionary is shared or could reach exactly 256 or 65,536 values: there uniqueInsertRangeFrom picks a wider index type than row-by-row insertion. It pairs destination and source columns by position, which holds for MergingSortedAlgorithm; a caller with a different column order (such as the SummingMergeTree copy above) would need order-independent accounting.

diff --git a/src/Processors/Merges/Algorithms/MergedData.cpp b/src/Processors/Merges/Algorithms/MergedData.cpp
index ad69f2da959e..3d9261f3c0e9 100644
--- a/src/Processors/Merges/Algorithms/MergedData.cpp
+++ b/src/Processors/Merges/Algorithms/MergedData.cpp
@@ -2,6 +2,7 @@
 #include <Columns/IColumn.h>
 #include <Core/Block.h>
 #include <Processors/Merges/Algorithms/MergedData.h>
+#include <Columns/ColumnLowCardinality.h>
 #include <Columns/ColumnReplicated.h>
 #include <Columns/ColumnSparse.h>
 #include <Common/logger_useful.h>
@@ -17,6 +18,13 @@ extern const int LOGICAL_ERROR;
 namespace
 {
 
+/// `ColumnLowCardinality::insertRangeFrom` translates up to this many rows of another dictionary one by one, with
+/// the same result as inserting them one at a time. A longer range is translated by `uniqueInsertRangeFrom`, which
+/// picks the index type for the dictionary size instead of the largest inserted index, so the indexes become wider
+/// than after inserting the rows one at a time when the dictionary has exactly 256 or 65536 values. Keep in sync with
+/// `max_rows_to_translate_individually` in ColumnLowCardinality.cpp.
+constexpr size_t max_low_cardinality_rows_to_translate_individually = 64;
+
 bool hasNonAdditiveByteSizeAt(const IColumn & column)
 {
     if (column.getDataType() == TypeIndex::LowCardinality
@@ -307,21 +315,50 @@ size_t MergedData::rowsToInsertBeforeFlush(
 
     chassert(columns.size() == raw_columns.size());
 
-    /// `byteSizeAt` is not additive for dictionary/index-backed columns, so let
+    /// `byteSizeAt` is not additive for dictionary/index-backed columns. For `LowCardinality` an upper bound of the
+    /// growth is counted instead: while the bound stays below the limit, `hasEnoughRows` cannot become true before
+    /// the last of the rows, exactly as when inserting them one at a time. For the other such columns let
     /// `hasEnoughRows` measure the actual size after inserting one row.
+    size_t merged_bytes = 0;
+    size_t low_cardinality_bytes_per_row = 0;
     for (size_t i = 0; i < columns.size(); ++i)
     {
+        const auto * low_cardinality = typeid_cast<const ColumnLowCardinality *>(columns[i].get());
+        const auto * low_cardinality_source = typeid_cast<const ColumnLowCardinality *>(raw_columns[i]);
+        if (low_cardinality && low_cardinality_source)
+        {
+            /// Inserting rows grows `byteSize` of a `LowCardinality` column by at most:
+            /// - the indexes: each index, old or new, can become `UInt64`;
+            /// - the dictionary: the size of each inserted value, which is `byteSizeAt` of the source row (counted
+            ///   below; repeated values add nothing). A shared dictionary is not counted in `byteSize`, but rows of
+            ///   another dictionary replace it with a subset of it, so its whole size is counted here.
+            merged_bytes += low_cardinality->size() * sizeof(UInt64) + low_cardinality->getDictionary().byteSize();
+            low_cardinality_bytes_per_row += sizeof(UInt64);
+
+            /// Keep the column the same as after inserting the rows one at a time (see the constant). A shared
+            /// dictionary is first replaced by a subset of it of unknown size.
+            if (&low_cardinality->getDictionary() != &low_cardinality_source->getDictionary())
+            {
+                const size_t dictionary_size = low_cardinality->getDictionary().size();
+                const size_t max_dictionary_size
+                    = dictionary_size + std::min(rows_to_insert, low_cardinality_source->getDictionary().size());
+                const auto can_reach = [&](size_t size) { return dictionary_size <= size && size <= max_dictionary_size; };
+                if (low_cardinality->isSharedDictionary() || can_reach(256) || can_reach(65536))
+                    rows_to_insert = std::min(rows_to_insert, max_low_cardinality_rows_to_translate_individually);
+            }
+            continue;
+        }
+
         if (hasNonAdditiveByteSizeAt(*columns[i]) || hasNonAdditiveByteSizeAt(*raw_columns[i]))
             return 1;
-    }
 
-    size_t merged_bytes = 0;
-    for (const auto & column : columns)
-        merged_bytes += column->byteSize();
+        merged_bytes += columns[i]->byteSize();
+    }
 
     for (size_t length = 1; length <= rows_to_insert; ++length)
     {
         const size_t row = start_index + length - 1;
+        merged_bytes += low_cardinality_bytes_per_row;
         for (const auto * column : raw_columns)
             merged_bytes += column->byteSizeAt(row);
 

@Algunenano Algunenano self-assigned this Nov 13, 2026

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great.

2 things:

  • We should mention this can cause benign checksum errors during updates on replicated tables: different versions will produce different parts, but the second replica will fetch it. I'll add it to the changelog
  • I think we could probably find ways to overestimate growth for the remaining cases so we can insert in batches, specially for JSON / Dynamic:
JSON / Dynamic: an upper bound is possible, and this is the one worth doing.
When a row is copied, the output grows by at most:
- the source row's own size, which byteSizeAt already gives;
- plus, for every path the output has but the source row lacks, one default value per row. For a dynamic path that is about 9 bytes (a 1-byte discriminator and an 8-byte offset); for a typed path, the default size of its type;
- plus, for every source path the output doesn't have yet, a one-time cost of merged_rows × default size to fill in that path for the rows already in the block;
- plus a little extra for values that end up in shared_data (path name and type name).

That needs a small helper that knows the internals of ColumnObject and ColumnDynamic, nothing more. The bound is loose but usable: with 1,000 output paths it is about 9 KB per row, so the 10 MiB limit allows about 1,100 rows per batch instead of 1. It also covers the bot's 1,000-path JSON example, which is the case that blew up merge memory. The default-value sizes above come from reading the ColumnVariant layout, not from a measurement. A gtest would have to confirm them before relying on the bound.

@groeneai Could you please give it try? Do some measurements around merge speed, find a safe upper bound for the byte growth for dynamic columns, and if all works create a PR and ping me on it.

@Algunenano
Algunenano added this pull request to the merge queue Nov 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm measuring merge speed and working on a safe upper bound for the byte growth of Dynamic/JSON columns in rowsToInsertBeforeFlush; I'll follow up here with a PR (or my findings) shortly.

@snelheidai

Copy link
Copy Markdown

@groeneai, for the JSON/Dynamic follow-up: the bound above underestimates the growth when a merge moves a value between a dynamic path (or variant) and shared data (or the shared variant), and for objects inside arrays. Measured with byteSize() (the row's byteSizeAt) on master 7a987ba: bytes per row of the first of two parts before and after OPTIMIZE TABLE ... FINAL, and the bound computed as before + 9 bytes per missing path + names of values moved to shared data.

Column: first part → merged part before bound after
JSON(max_dynamic_paths = 2): path x, an array of 1,000 elements with 999 NULLs, moves from shared data to a dynamic path 1,072 ~1,100 9,069
Dynamic(max_types = 1): the same array moves from the shared variant to a variant 1,030 1,030 9,017
JSON: path arr holds 100 objects with path a; the objects of the second part have 100 other paths 2,525 2,525 92,525
JSON(max_dynamic_paths = 4): path arr, 100 objects with a 60-character path, moves from a dynamic path to shared data 2,525 ~2,600 7,172

With the default limits of 8,192 rows and 10 MiB, a block sized by the bound would reach about 70 MiB in the first two cases, 370 MiB in the third and 28 MiB in the fourth.

  • chooseDynamicStructureForMerge promotes the most frequent paths and types, including those in the sources' shared data and shared variants, and moves the rest to shared data. Moving changes the size: a NULL array element takes 1 byte serialized and 9 bytes in memory, and serialized objects repeat their path names in every element.
  • Objects in arrays (Array(JSON) is inferred for arrays of objects) get a 9-byte default for each missing nested path in every element: 100 × 100 × 9 = 90,000 bytes per row in the third case, while the top-level paths do not change.

The bound is safe for a source column whose values stay where they are. For JSON: every dynamic path of the source is a dynamic path of the merged column, and the source has no shared data or has all dynamic paths of the merged column. For Dynamic, the same with variants and the shared variant. Nested objects need the same check, with missing paths counted per element. Rows of the second part meet these conditions and grew by exactly 9 bytes per missing path, which confirms the default size. Other sources could keep inserting one row at a time.

Two terms are not needed in merges: typed paths are always the same in the source and the merged column, and the paths and types chosen by chooseDynamicStructureForMerge stay fixed for the whole merge (max_dynamic_paths = dynamic_paths.size(), kept by cloneEmpty), so no path is added during it.

Reproduction (clickhouse local)
-- Case 1. For the other cases, change the type of v and the two INSERTs.
CREATE TABLE t (id UInt64, v JSON(max_dynamic_paths = 2)) ENGINE = MergeTree ORDER BY id
SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
SYSTEM STOP MERGES t;
INSERT INTO t SELECT number, concat('{"p1":1,"p2":2,"x":[1', repeat(',null', 999), ']}') FROM numbers(1000);
INSERT INTO t SELECT 1000 + number, concat('{"x":[1', repeat(',null', 999), ']}') FROM numbers(1000);
SELECT id < 1000 AS first_part, avg(byteSize(v)) FROM t GROUP BY ALL ORDER BY ALL;
SYSTEM START MERGES t;
OPTIMIZE TABLE t FINAL;
SELECT id < 1000 AS first_part, avg(byteSize(v)) FROM t GROUP BY ALL ORDER BY ALL;

-- Case 2: v Dynamic(max_types = 1); add dynamicType(v) to both SELECTs (the Int64 rows push the arrays into the shared variant).
INSERT INTO t SELECT number, if(number < 600, number::Int64::Dynamic,
    arrayMap(i -> if(i = 0, 1, NULL), range(1000))::Array(Nullable(Int64))::Dynamic) FROM numbers(1000);
INSERT INTO t SELECT 1000 + number, arrayMap(i -> if(i = 0, 1, NULL), range(1000))::Array(Nullable(Int64))::Dynamic FROM numbers(2000);

-- Case 3: v JSON
INSERT INTO t SELECT number, concat('{"arr":[', arrayStringConcat(arrayMap(i -> concat('{"a":', toString(i), '}'), range(100)), ','), ']}') FROM numbers(1000);
INSERT INTO t SELECT 1000 + number, concat('{"arr":[{', arrayStringConcat(arrayMap(i -> concat('"b', toString(i), '":1'), range(100)), ','), '}]}') FROM numbers(1000);

-- Case 4: v JSON(max_dynamic_paths = 4)
INSERT INTO t SELECT number, concat('{"arr":[', arrayStringConcat(arrayMap(i -> concat('{"', repeat('n', 60), '":', toString(i), '}'), range(100)), ','), ']}') FROM numbers(1000);
INSERT INTO t SELECT 1000 + number, '{"q1":1,"q2":2,"q3":3,"q4":4}' FROM numbers(2000);

Merged via the queue into ClickHouse:master with commit 3cfc81f Nov 13, 2026
179 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
@cwurm
cwurm deleted the batch-sorting-queue-lowcardinality branch November 13, 2026 22:21
@groeneai

Copy link
Copy Markdown
Collaborator

I opened #131486.

The bound turned out to be exact, not just an upper bound: a merge fixes the merged column's dynamic structure, so when every path and variant of a source chunk is in the merged column, the block grows by byteSizeAt plus 9 bytes (discriminator and offset) per dynamic path the source lacks. A gtest checks the 9 bytes by equality. The shapes where a value can move to or from the shared data or the shared variant, including the four measured above, keep the row-by-row insertion. The 1,000-path case batches 1,165 rows at 10 MiB. Merge time PR / master over 15 rounds: 20-path JSON 0.69, Dynamic 0.79, 1,000 paths 0.86 with the same peak memory as the default queue.

@cwurm

cwurm commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

@groeneai Could you please also look at projections?

Projection merges never use the batch queue. Even with merge_use_batch_sorting_queue = 1, the child MergeTask that merges a projection's parts stays on the default queue because of this guard in MergeTask::ExecuteAndFinalizeHorizontalPart::createMergedStream:

const auto sorting_queue_strategy
    = !global_ctx->merge_may_reduce_rows
        && !global_ctx->projection
        && (*merge_tree_settings)[MergeTreeSetting::merge_use_batch_sorting_queue]
    ? SortingQueueStrategy::Batch
    : SortingQueueStrategy::Default;

As far as I can tell, the guard wasn't added because of a known bug. It was added in #108468 after the review bot called projection merges an untested surface (#108468 (comment)). From reading the code, lifting it looks safe:

  • A normal projection's merge is a plain Ordinary MergeTask over the projection parts, sorted by the projection's ORDER BY. Aggregate projections get Aggregating mode, so merge_may_reduce_rows keeps them on the default queue anyway.
  • _parent_part_offset is remapped when the projection parts are read (createReadFromPartStep with merged_part_offsets), not by the sorting algorithm. Only the parent merge records the mapping (parent_part == nullptr).
  • Projection merges can be vertical, but the batch queue already handles vertical merges on base tables.

Could you remove !global_ctx->projection and add a focused stateless test that compares projection contents (mergeTreeProjection) after OPTIMIZE FINAL under both queues? It should cover a normal projection with a different ORDER BY, a _parent_part_offset projection (04614 already compares one, and after the change it would also cover the projection merge itself) and a commit-order projection (_block_number / _block_offset). Please also measure merge time on a table with a normal projection, with the setting on and off. If all works, create a PR and ping me on it.

@snelheidai

Copy link
Copy Markdown

@groeneai, two points for the test, checked with clickhouse local on master d88a8f1:

  1. The guard also covers the merges of temporary projection parts. When a merge rebuilds a projection, or a mutation such as MATERIALIZE PROJECTION builds one, MergeProjectionPartsTask writes a temporary part every min_insert_block_size_rows (1,048,449) rows or min_insert_block_size_bytes (about 256 MiB). It then merges those parts with child MergeTasks that have projection set and, for normal projections, Ordinary mode with no deduplication. Removing the guard moves these merges to the batch queue too. The threshold comes from the merge's background context, not the query: with OPTIMIZE ... SETTINGS min_insert_block_size_rows = 10000, rebuilding a 200,000-row projection still wrote a single temporary part, while the same setting for the whole clickhouse local process gave 13 temporary parts and three child merges. To cover this path in the content comparison and the merge-time measurement, the rebuilt projection needs more than about 1.05 million rows.

  2. A commit-order projection is not built on insert (MergeTreeDataWriter skips projections with _block_number), and parts with different projection sets are not merged together. So OPTIMIZE FINAL over inserted parts rebuilds it instead of merging projection parts, and a later OPTIMIZE FINAL after more inserts does not merge ("Parts have different projection sets"). Running ALTER TABLE ... MATERIALIZE PROJECTION first gives every part the projection, and the next OPTIMIZE FINAL then merges the projection parts. MergedProjections and RebuiltProjections in system.part_log.ProfileEvents show which path a merge took.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating lifting the !global_ctx->projection guard so projection merges can use the batch sorting queue, with the projection-content test under both queues and the merge-time measurement you described; I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

I opened #132085. It removes the guard and adds the test you described (plus the temporary parts of MATERIALIZE PROJECTION, with part_log showing that the projections were merged, not rebuilt) and a performance test.

Merge time with the setting on / off on the PR build (release), 10 parts of 1M rows, medians of 32 runs:

projection parts whole merge, ms projection stage, ms
alternate in runs of 100 rows 1123 / 1200 595 / 697
interleave row by row 1387 / 1295 997 / 939

It helps where the projection parts alternate in short runs (projection stage -15% here, -21% with 2M-row parts and a hashed parent key), gives nothing for parts that are disjoint in the projection key (the default queue already moves whole chunks there), and costs up to 6% of the projection stage where the key interleaves row by row.

@snelheidai

Copy link
Copy Markdown

The row-by-row cost isn't specific to projections. It comes from MergingSortedAlgorithm::mergeBatchImpl, so base-table merges pay it too. The same function explains why, in your runs, the parent stage (disjoint key) was also slower with the setting on: whole merge minus projection stage is 528 vs 503 ms and 390 vs 356 ms.

  • A chunk that is moved whole (keys disjoint across parts) first goes through MergedData::rowsToInsertBeforeFlush. Merges have a byte limit (merge_max_block_size_bytes), so that is a virtual byteSizeAt call per row and column of the chunk, and the whole-chunk path then ignores the result.
  • A one-row batch (keys interleaved row by row) goes through the same bookkeeping as a long one: the out-of-line rowsToInsertBeforeFlush call and the clipping and limit checks. mergeImpl inserts such a row directly.

The patch below skips that call for a chunk moved whole and inserts a one-row batch the way mergeImpl inserts a row, both only when there is no row limit (merges never have one). The output doesn't change: merged parts are byte-identical with and without it.

Base tables, 10 parts of 1M rows, OPTIMIZE ... DRY RUN PARTS, server time, setting on / off, medians of 12 interleaved pairs:

sorting key across parts before, ms with the patch, ms patch, setting on
interleaved row by row 1491 / 1415 1452 / 1425 −2.7% [−3.4, −2.0]
disjoint 561 / 523 524 / 527 −6.2% [−7.3, −5.1]
disjoint, 5 columns incl. String 1812 / 1739 1723 / 1725 −4.5% [−5.4, −3.7]
runs of 100 rows 665 / 851 661 / 848 +0.3% [−1.2, +1.8]

With the setting off, the patch makes no measurable difference (−0.3% to +1.0%; every interval includes 0).

Your perf-test tables, setting on / off, medians of 10 alternating rounds:

projection parts whole merge, ms projection stage, ms
interleaved row by row, before 2036 / 1900 1467 / 1378
interleaved row by row, with the patch 1948 / 1906 1424 / 1382
runs of 100 rows, before 1639 / 1794 880 / 1060
runs of 100 rows, with the patch 1614 / 1784 884 / 1063

With row-by-row interleaving, the batch queue now adds 3.0% to the projection stage instead of 6.5%. The parent stage takes the same time with both queues: 514 vs 516 ms, where it was 551 vs 512 ms. What's left comes from the batches longer than one row (with 10 random parts, roughly one batch in ten): the out-of-line search for the batch end (updateBatchSizeSlow) and the per-column byteSizeAtCanUnderestimateGrowth checks in rowsToInsertBeforeFlush, each about 1% of the samples in a profile of the interleaved merge. #131534 skips those checks for fixed-size columns.

Queries that merge sorted streams go through the same function, and without LIMIT they take the new path too. On the interleaved table, SELECT * FROM t ORDER BY b FORMAT Null read in order with 4 threads took 5.6% less (698 → 661 ms, [−6.8, −4.4]). A 4-thread full sort of the disjoint table by b changed by −2.0% [−4.2, +0.3].

@groeneai, the patch is independent of #132085, since base-table merges and these queries gain as well. Could you take it into a PR?

Patch
diff --git a/src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp b/src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp
index 634e7fd8727..6d9878fb614 100644
--- a/src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp
+++ b/src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp
@@ -636,6 +636,16 @@ IMergingAlgorithm::Status MergingSortedAlgorithm::mergeBatchImpl(TSortingQueue &
         auto [current_ptr, initial_batch_size] = queue.current();
         auto current = *current_ptr;
 
+        /// A batch of one row that is not the last one of its chunk: the keys are interleaved between the sources.
+        /// Insert the row as `mergeImpl` does. The bookkeeping below cannot shorten such a batch: `hasEnoughRows`
+        /// has just checked the limits of the block, and there is no row limit.
+        if (initial_batch_size == 1 && !limit && !current.impl->isLast())
+        {
+            insertRow(*current.impl);
+            queue.next(1);
+            continue;
+        }
+
         bool batch_skip_last_row = false;
         if (current.impl->isLast(initial_batch_size) && current_inputs[current.impl->order].skip_last_row)
         {
@@ -658,17 +668,25 @@ IMergingAlgorithm::Status MergingSortedAlgorithm::mergeBatchImpl(TSortingQueue &
             updated_batch_size -= merged_rows + updated_batch_size - merged_data.maxBlockSize();
         }
 
-        const size_t insertable_rows = updated_batch_size - static_cast<size_t>(batch_skip_last_row);
-        const size_t rows_before_flush = merged_data.rowsToInsertBeforeFlush(
-            current.impl->all_columns,
-            current.impl->getRow(),
-            insertable_rows,
-            current.impl->rows);
+        /// The whole chunk is moved below. Then the byte size of its rows matters only for the row limit.
+        const bool insert_whole_chunk = current.impl->isFirst()
+            && current.impl->isLast(initial_batch_size)
+            && !current_inputs[current.impl->order].skip_last_row;
 
-        if (rows_before_flush < insertable_rows)
+        if (!insert_whole_chunk || limit)
         {
-            batch_skip_last_row = false;
-            updated_batch_size = rows_before_flush;
+            const size_t insertable_rows = updated_batch_size - static_cast<size_t>(batch_skip_last_row);
+            const size_t rows_before_flush = merged_data.rowsToInsertBeforeFlush(
+                current.impl->all_columns,
+                current.impl->getRow(),
+                insertable_rows,
+                current.impl->rows);
+
+            if (rows_before_flush < insertable_rows)
+            {
+                batch_skip_last_row = false;
+                updated_batch_size = rows_before_flush;
+            }
         }
 
         bool limit_reached = false;
@@ -685,9 +703,7 @@ IMergingAlgorithm::Status MergingSortedAlgorithm::mergeBatchImpl(TSortingQueue &
             limit_reached = true;
         }
 
-        if (unlikely(current.impl->isFirst() &&
-            current.impl->isLast(initial_batch_size) &&
-            !current_inputs[current.impl->order].skip_last_row))
+        if (unlikely(insert_whole_chunk))
         {
             /** This is special optimization if current cursor is totally less than next cursor.
               * We want to insert current cursor chunk directly in merged data.
Setup and checks

AWS r6i.xlarge (Xeon Platinum 8375C, 4 vCPU). Non-LTO RelWithDebInfo build of 8dc31eb with the MergedData.cpp change of this PR and #132085 applied. MergingSortedAlgorithm.cpp and SortCursor.h are the same on master 4553bee apart from [[nodiscard]]. The ThinLTO release build of 4553bee still calls rowsToInsertBeforeFlush out of line from every mergeBatchImpl instantiation.

Base tables are (a UInt64, b UInt64) with merge_use_batch_sorting_queue as a table setting. Interleaved: ORDER BY b, b = intHash64(a). Disjoint: ORDER BY a, part k holds a from k × 1M to (k + 1) × 1M − 1. Runs of 100 rows: the b of your perf test, ORDER BY b. The 5-column table adds c Float64, d UInt32, s String to the disjoint one. Merges ran as OPTIMIZE TABLE ... DRY RUN PARTS of all 10 parts with optimize_dry_run_check_part = 0, timed by server query_duration_ms. The patch column is the geometric mean of the paired ratios with its 95% interval. The perf-test tables are the two from #132085, plus copies with the setting off; stage times are MergeProjectionStageTotalMilliseconds and MergeHorizontalStageTotalMilliseconds from system.query_log.

Checks: 05813 from #132085 and 04411, 04412, 04413 and 04614 pass. Merged parts, including projection parts, have the same hash_of_all_files with and without the patch. That covers 7 shapes of 8 parts × 100K rows (the three 2-column base tables, your two perf-test tables, and a 6-column table with String and LowCardinality(String) with keys interleaved and disjoint), each with a 10 MiB and a 16 KiB merge_max_block_size_bytes and with a vertical merge, under both queues.

@groeneai

Copy link
Copy Markdown
Collaborator

I opened #132178 with the patch. It reproduces on a release build of current master (10 parts x 1M rows, 12 paired runs, twice with the server core sets swapped): merge with disjoint keys -8.1% / -6.6%, keys interleaved row by row -2.8% / -3.9%, ORDER BY read in order -5.1% / -8.8%, runs of 100 rows and the default queue unchanged. Merged parts stay byte-identical, also with a 16 KiB merge_max_block_size_bytes.

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

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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