Skip to content

Copy rows with unique keys in bulk in SummingMergeTree FINAL, merges and INSERT - #131514

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:summing-merge-tree-copy-rows-of-own-groups
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:summing-merge-tree-copy-rows-of-own-groups

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131261
Related: #127826

Changelog category (leave one):

  • Performance Improvement

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

SELECT ... FINAL, merges and INSERT of SummingMergeTree tables copy the rows that have no other row with the same key in bulk instead of summing them one by one. With one large part and a few small parts of new rows for existing keys, FINAL is up to 3.5x faster and merges up to 2.3x faster; an INSERT of new keys is up to 2.3x faster. Closes #131261.

Description

Analysis and patch by snelheidai in #131261, verified and measured here.

SummingSortedAlgorithm starts and finishes a group for every row (Field copies, a sum state per column, a byte check per row), even for rows that have no other row with their key. Rows of a part with a non-zero level have unique keys (#58142), and the batch queue (#115869) reports runs of such rows that are less than every other source's current row, so each row strictly inside such a batch is a group of one row. When every summed column is a plain number summed by sumWithOverflow, that group is the row itself (+0 on floats, so -0.0 becomes +0.0; dropped in merges and INSERT when all sums are zero): such rows are now copied with insertRangeFrom, keeping the block limits. In an INSERT block, a row whose key differs from both neighbours is copied the same way through the sort permutation.

The path is used only when a sample merge (at most 1024 rows, 1/8 of the rows) shows long batches dominate; a batch up to the end of a chunk counts, so merges of parts with consecutive key ranges use it too. JSON, Dynamic and Variant columns (the per-row Field copy can change the alternative of a Variant value) and replicated inputs keep the per-row loop.

Validation (x86, 4 threads, 10-20 paired rounds): FINAL -47% to -71%, merges -19% to -57% (LowCardinality with #127826), merges of parts with consecutive key ranges -42% to -53%, INSERT of new keys -32% to -57%; interleaved merges, point lookups, AggregatingMergeTree and small INSERTs within noise; peak memory at most +3.6%. 468 result and merged-part digests (hash_of_all_files) identical to master over 22 table shapes and 15 INSERT shapes. New performance test and a stateless test checked against a GROUP BY.

🤖 Generated with Claude Code


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

groeneai and others added 3 commits November 14, 2026 01:21
`SummingSortedAlgorithm` starts and finishes a group for every row, even where
no other row has the same key: `Field` copies of the columns that are not
summed, a sum state per summed column and the block byte check per row. Rows
of a part with a non-zero level have unique keys (ClickHouse#58142), and the batch queue
(ClickHouse#115869) already reports runs of such rows that are less than the current
rows of the other sources, so every row strictly inside such a batch is a
group of one row. When every summed column is a plain number summed by
`sumWithOverflow`, the result of such a group is the row itself, with 0 added
to float sums (-0.0 becomes +0.0), and it is removed in merges and INSERT if
all sums are zero. Copy these rows with `insertRangeFrom` instead.

For INSERT (`optimize_on_insert`, one level-0 source) a row whose key differs
from both neighbours is a group of one row too: copy such runs through the
sort permutation, skipping zero rows.

The batch path is used only when a sample merge of at most 1024 rows (and at
most 1/8 of the rows, as in `sourcesHaveRunsWorthSkipping`) shows that long
batches from such sources dominate, for single-column and composite keys
alike. Merges whose keys interleave keep the per-row loop. Columns with a
dynamic structure and replicated inputs keep it too, decided once (the
replicated state reuses `MergedData::mayHaveReplicatedColumns`, whose scan
helpers move from `MergingSortedAlgorithm.cpp` to `IMergingAlgorithm.h`).

Based on the analysis and patch by snelheidai in ClickHouse#131261.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rf test on Iceberg

05633_summing_merge_tree_batch_copy compared the FINAL with
max_block_size = 1000 with the GROUP BY oracle in one direction only, so
rows missing from that FINAL were not seen. That FINAL is the one where the
block limit stops a bulk copy early. Compare it both ways, with the setting
on the outer query.

The new performance test uses FINAL and named parts, which Iceberg tables do
not have, so mark it `iceberg="0"`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove the comments on the design of the new code and shorten the ones that state an invariant.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex) plus my own review, two rounds.
Round 1 (edea4f7): 3 findings from the model, 3 nits from me. Round 2 (cbbde46, tests only): 0 findings from either.

# Sev Finding Verdict Evidence / action
1 ⚠️ The max_block_size = 1000 FINAL check of the stateless test is one-directional, so missing rows are not detected AGREE, fixed in cbbde46 both directions, with the setting on the outer query; a mutation that drops rows after the block limit now fails the new reverse check
2 ⚠️ The new performance test is selected for the Iceberg performance configuration, which has no FINAL or named parts AGREE, fixed in cbbde46 <test iceberg="0">, as final_row_policy_query_constant.xml
3 ⚠️ No test proves that the bulk-copy path runs; add a ProfileEvent DISAGREE the performance test is the activation check (all 5 queries 20-55% faster locally); 7 mutations of the copy path turn the stateless test red; no new counter in src/
4 💡 The sample stops before counting a batch that reaches the end of a chunk, so merges of parts with non-overlapping keys keep the per-row loop noted same as master, not claimed here
5 💡 A refused single-source copy repeats one key comparison noted bounded by the sample; controls within noise
6 💡 group_start_pos is not moved by a copy, which can delay the next one by one group noted heuristic only; every copied pair is checked

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261114-024200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Release builds of master and of this PR on copies of one data directory (identical parts), each pinned to 4 CPUs, 11 rounds alternating the server order: the speed-up shows in every round (sum1 FINAL 194 -> 97 ms, sum2 OPTIMIZE 789 -> 456 ms, INSERT of 4M new keys 1194 -> 542 ms).
b Root cause explained? SummingSortedAlgorithm starts and finishes a group per row. Rows strictly inside a batch from a part with a non-zero level, and rows of an INSERT block that differ from both neighbours, are groups of one row whose result is the row itself (+0 on float sums, dropped when all sums are zero in merges and INSERT).
c Fix matches root cause? Yes. Exactly those rows are copied with insertRangeFrom / insertFrom, with the same zero test and block limits; everything else keeps the per-row loop. The batch path is enabled only when a sample merge shows long batches.
d Test intent preserved / new tests added? New tests/performance/summing_merge_tree_batch_copy.xml (5 queries, all faster in a local perf.py run) and 05633_summing_merge_tree_batch_copy.sql (INSERT, FINAL and merges against a GROUP BY, in both directions). 7 mutations of the new code all turn the test red. No existing test changed.
e Both directions demonstrated? Yes: base vs PR numbers above; the stateless test passes on both builds (behaviour is unchanged) and 50/50 randomized runs; each mutation fails it.
f Fix is general across code paths? FINAL (many sources), merges and INSERT (one source through the sort permutation) are covered. AggregatingSortedAlgorithm shares the base class and keeps the queue exactly as before.
g Fix generalizes across inputs (params/datatypes/wrappers)? Int/UInt 8 to 256 bit, Float32/64 (NaN, inf, -0.0) and Decimal sums are copied; Nullable, LowCardinality, AggregateFunction, SimpleAggregateFunction and ...Map sums and CoalescingMergeTree keep the old path. 426 FINAL, merge and INSERT digests over 18 table and 15 INSERT shapes (String, LowCardinality, Nullable, Array, Variant, Tuple, JSON, partitioned, block-size limits) are identical to master, also with #127826.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; merged parts are byte-identical (hash_of_all_files).
i Invariants and contracts preserved? Every copied row is a one-row group in the current grouping: the first and last rows of a batch and the last row of a chunk keep the normal path. Row counters are updated. The row and byte block limits are kept (rowsToInsertBeforeFlush, which can only stop the copy earlier when zero rows are skipped).

Session id: cron:clickhouse-impl-slot-6:20261113-232700

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [61ef58a]

Summary: ✅


AI Review

Summary

Reviewed #131514 at 61ef58a0e60bb1f2bc38b288f7fd08d665c09438. The change copies single-row groups in bulk for SummingMergeTree INSERT, FINAL, and merges. No unresolved findings remain; the earlier Variant issue is addressed by excluding those types from bulk copying. The new stateless test matches all 17 reference lines, and 21 additional comparisons against scalar aggregation pass, including NaN bit patterns, wide integers, decimals, and small output blocks. Performance measurements are provided in the PR and linked issue.

Final Verdict

Status: ✅ 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. can be tested Allows running workflows for external contributors labels Nov 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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

9 object files changed (+91.97 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/SummingSortedAlgorithm.cpp.o 358.99 KiB 430.18 KiB +71.20 KiB (+19.83%)
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/IMergingAlgorithmWithDelayedChunk.cpp.o 96.21 KiB 115.88 KiB +19.67 KiB (+20.44%)

711 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.59, programs/clickhouse-keeper ×0.62 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.1 s 10.6 s +7.0 s (+195%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.2 s +5.2 s (+250%)
Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.92 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -47.9 s (-10%) in total before that adjustment.

Job report

… per row

The sample in `sourcesHaveLongBatchesOfUniqueKeys` stopped at a batch that reaches the end
of a chunk without counting it, so a merge that starts with such a batch (parts whose key
ranges do not overlap, e.g. a sorting key that starts with a date or a time) sampled no rows
and kept the per-row loop. Count the batch before stopping (found and measured by snelheidai
in ClickHouse#131261). OPTIMIZE DRY RUN, x86, 4 pinned threads, 20 paired rounds against the previous
commit: 30 one-day parts ORDER BY (d, sid) -44.2%, 30 parts of consecutive time ranges
ORDER BY ts -53.4%, a 29-day part plus 10 parts of the next day -42.1%; the worst case (only
the first chunk precedes the other part) +1.4% [-0.7, +3.6]; interleaved keys and
overlapping parts +0.1% / +0.9%. 42 FINAL and merge digests (with `hash_of_all_files`)
identical to master.

`setRow` copies a `Variant` value through a `Field`, and inserting the `Field` picks the
first alternative that accepts it (a UInt64 in `Variant(Date, UInt64)` becomes a Date),
while the bulk copy keeps the alternative, so one INSERT or FINAL returned both. Columns
whose type contains `Variant` keep the per-row loop, as on master.

The performance test gets a merge of ten parts of consecutive time ranges; 05633 checks
that a `Variant` column gets one alternative on INSERT and FINAL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 14, 2026
`sourcesHaveLongBatchesOfUniqueKeys` stopped at a batch that reaches the end of a chunk without
counting it, so a merge whose first batch covers a whole chunk (parts of consecutive key ranges,
or a merged part whose first chunks precede the updated keys) sampled no rows, and with a
single-column key it kept the per-row loop. Without `is_deleted` the whole-chunk shortcut takes
most of those rows; with `is_deleted` it is off, so such merges gained nothing. Count the batch
before stopping, as the same sample in ClickHouse#131514 does (found and measured by snelheidai in ClickHouse#131277).

`OPTIMIZE TABLE ... FINAL` of a copy, x86, 4 pinned threads, 10 paired rounds against the previous commit:
`ReplacingMergeTree(ver, is_deleted)` of 30 parts of consecutive id ranges -38.4% [-39.5, -37.3],
a merged part plus 10 parts of updates of its last 200k ids -35.8% [-37.6, -33.9] (instructions
0.44x on the first); the same tables without `is_deleted` -0.3% / +1.4% and the interleaved worst
case +1.2%, all with CIs including zero (20 rounds: +1.8% [+0.1, +3.4] elapsed for the second,
instructions +0.07%); `cdc1` `FINAL` and `OPTIMIZE` unchanged. 79 result and merged-part digests
(`hash_of_all_files`, several merge block sizes, vertical merge, `CLEANUP`, `FINAL` variants) and the
259-digest differential harness are identical to master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 20, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SummingMergeTree FINAL and merges: copy rows of parts without duplicate keys in whole batches, 53-68% faster FINAL on tables with new parts

1 participant