Repository navigation
Batch LowCardinality columns in merges with merge_use_batch_sorting_queue - #127826
Conversation
`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]>
|
Workflow [PR], commit [2f28fce] Summary: ✅
AI ReviewSummaryThe PR enables batched merge insertion for Final Verdict✅ Approve. |
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]>
LowCardinality columns in merges with merge_use_batch_sorting_queue
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Independent measurement of this PR's
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 ( Exact boundaries are possible, at some cost. Counting an upper bound of the This PR also helps the SummingMergeTree batch copy proposed in #131261, which goes through Tables and procedureBackground merges blocked with -- 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.0Exact-boundary bound (measured alternative to this PR's change)It counts every index as 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
left a comment
There was a problem hiding this comment.
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.
|
Acknowledged. I'm measuring merge speed and working on a safe upper bound for the byte growth of |
|
@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
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.
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 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); |
|
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 |
|
@groeneai Could you please also look at projections? Projection merges never use the batch queue. Even with 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:
Could you remove |
|
@groeneai, two points for the test, checked with
|
|
Acknowledged. I'm investigating lifting the |
|
I opened #132085. It removes the guard and adds the test you described (plus the temporary parts of Merge time with the setting on / off on the PR build (release), 10 parts of 1M rows, medians of 32 runs:
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. |
|
The row-by-row cost isn't specific to projections. It comes from
The patch below skips that call for a chunk moved whole and inserts a one-row batch the way Base tables, 10 parts of 1M rows,
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:
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 ( Queries that merge sorted streams go through the same function, and without @groeneai, the patch is independent of #132085, since base-table merges and these queries gain as well. Could you take it into a PR? Patchdiff --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 checksAWS r6i.xlarge (Xeon Platinum 8375C, 4 vCPU). Non-LTO Base tables are Checks: 05813 from #132085 and 04411, 04412, 04413 and 04614 pass. Merged parts, including projection parts, have the same |
|
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%, |
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]>
merge_use_batch_sorting_queueinserts runs of consecutive rows from the same source part with a singleinsertRangeFrominstead of row by row. ButMergedData::rowsToInsertBeforeFlushreturns 1 for any batch with aLowCardinalitycolumn (including insideMap/Array/Tuple) whenevermerge_max_block_size_bytesis 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
LowCardinalityfrom that special case, so the existing per-row byte prediction covers it. For aLowCardinalitycolumn, the sum ofbyteSizeAtover 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 insideMap(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
LowCardinalityspecial 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):
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.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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Merges with
merge_use_batch_sorting_queueenabled no longer fall back to row-by-row insertion for tables withLowCardinalitycolumns, 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 aReplicatedMergeTreecluster 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
26.11.1.2218-master(included in26.11and later)