Skip to content

Take rows of parts with unique keys in whole batches in ReplacingMergeTree FINAL and merges - #131552

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:replacing-final-take-unique-batches
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:replacing-final-take-unique-batches

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131277
Related: #131494
Related: #131513
Related: #131514
Related: #131560

Changelog category (leave one):

  • Performance Improvement

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

SELECT ... FINAL and merges of ReplacingMergeTree tables are faster when most rows come from large merged parts and only a few from small parts of updates: the rows of a part without duplicate keys that lie between the keys of the other parts are now taken in batches instead of one at a time. Closes #131277.

Description

Analysis and patch by snelheidai in #131277.

ReplacingSortedAlgorithm handles one row per loop iteration, even inside long runs from a part with a non-zero level, which the merge already treats as having no duplicate keys (rowsHaveDifferentSortColumns). The batch queue (#115869) reports such runs, and every row strictly inside one is a group of its own. A batch of at least 8 such rows is now written in one go: vertical FINAL appends the row numbers to the selection, otherwise MergedData::insertRows within the block limits (row by row when the byte size cannot be estimated). Row sources, is_deleted checks, CLEANUP and the TTL filter stay per row. For a single-column key the detection turns on only when a sample of the first rows is dominated by long batches (the same sample as #131514).

A batch is taken only when its first row is the selected one, so parts that break the no-duplicates premise (a key shortened by MODIFY ORDER BY, #70667; adopted parts, #109686) give the same result as master.

Validation (non-LTO RelWithDebInfo, Xeon 6975P-C, 4 CPUs, 10 paired rounds, user CPU fix/base): FINAL of one 8M-row part plus 10 update parts 0.68 (0.54 with enable_vertical_final = 0), OPTIMIZE FINAL 0.75, 50 small parts 0.76-0.79, merges with a LowCardinality or JSON column 0.90 / 0.96; interleaved parts, a two-column key, point lookups and INSERT not slower. The new performance test under CI's LZ4 pin: 0.56 / 0.40 / 0.59 user CPU, OPTIMIZE 0.74 elapsed. 259 result and merged-part digests (hash_of_all_files) are identical to master over 9 table shapes, and six mutations of the new path are each caught by them or by existing stateless tests.

Batched rows also advance the vertical FINAL selection wait of #131560 (new 05632 case). #131494 and #131514 (mine) touch the same files; whichever merges later adapts.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits November 14, 2026 06:26
…eTree FINAL and merges

`ReplacingSortedAlgorithm::merge` handles one row per loop iteration (compare with the selected
row, write the previous group, select through a reference-counted `RowRef`, advance the queue),
also inside long runs from one part with a non-zero level, which already counts as having no
duplicate keys (`rowsHaveDifferentSortColumns`). A batch from such a part holds rows that are all
less than the other cursors' rows, except that its last row may equal the next source's row, so
every row strictly inside it is a group of one.

- A batch of at least 8 rows from such a part writes the current group and takes its inner rows
  in one go: vertical FINAL appends the row numbers to the chunk's selection, otherwise
  `MergedData::insertRows` within `max_block_size` and `rowsToInsertBeforeFlush`; row sources,
  `is_deleted` validation and CLEANUP, and the TTL row filter are applied per row.
- When `rowsToInsertBeforeFlush` returns one row for more allowed rows (columns whose byte size it
  cannot estimate: `AggregateFunction`, `JSON`, `Dynamic`, replicated columns; or a first row that
  already fills the block), the batch rows are written one at a time with `hasEnoughRows` before
  each, which is the per-row path's own decision, so block boundaries stay exact. Otherwise such
  a merge paid that column scan every three rows (+5% on a merge with a LowCardinality column
  while it was still in that class).
- The batch is taken only when the current row is the selected one. The per-row path never
  compares two rows of such a part, but compares a row with a selected row of another source, so
  on parts that break the premise (a sorting key shortened by `MODIFY ORDER BY`, ClickHouse#70667; adopted
  parts, ClickHouse#109686) the result stays identical to the per-row path.
- For a single-column key the batch detection is enabled only when a sample merge of at most
  1024 rows (and at most 1/8 of the rows of the current chunks) puts at least half of them into
  such batches, so interleaved parts keep the per-row path. The sample is the same as the one
  SummingMergeTree uses for the same purpose.
- The merge loop is a template instantiated with and without the batch check, and the batch
  function is out of line and takes the cursor by pointer: the reporter measured the per-row
  loop 3-6% slower otherwise.
- One predicate, `sourceHasUniqueKeys`, now holds every part-level test of these classes.

A performance test covers FINAL with and without vertical FINAL, FINAL over a two-column key and
OPTIMIZE FINAL of one large merged part plus ten small parts of updates.

Measured (non-LTO RelWithDebInfo, Xeon 6975P-C, 4 CPUs, 10 paired rounds, fix/base user CPU):
`FINAL` of 8M rows + 10 parts of 20k updates 0.68, the same with `enable_vertical_final = 0`
0.54, `OPTIMIZE FINAL` of it 0.75 (`instructions:u` 0.53 and 0.59); a LowCardinality column
0.90, a JSON column 0.96; two interleaved parts and a two-column key unchanged.

Analysis and patch from ClickHouse#131277 by @ snelheidai.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove comments that narrate the new code (NO_INLINE reason, block-limit steps, member docs repeating their names); shorten the remaining ones to one line each, two for the batch-take condition.

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; 1 finding) and my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The performance test cannot fail when the batch path is reverted or never taken, and its setup check compares two runs of the changed algorithm DISAGREE A revert or a never-taken batch changes no result, only speed, which the performance comparison measures (under CI's LZ4 pin: q0 0.62, q1 0.45, q2 0.62, q3 0.74 elapsed vs master). Results are pinned by existing tests with fixed references that fail on broken variants of the new path (03915_auto_statistics_replacing_merge, 05316_lazy_final_aggregation_in_order_batched_merges, 05193_top_k_through_join_final_reverse_order); CI randomizes enable_vertical_final and the vertical merge thresholds, so they also run the selection and row-source paths.
2 💡 Run skipping now also turns on when the new sample enables batch detection (ReplacingSortedAlgorithm.cpp:82) AGREE, not changed Results unaffected; the probe only runs on batches longer than one row from level-0 parts, as master already does for every multi-column key.
3 💡 The is_deleted > 1 check is written three times AGREE, not changed Same code and message in all three places.

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

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, as a work count: cdc1 FINAL (one 8M-row merged part + 10 parts of 20k updates) runs 6.87 G user instructions on master vs 3.64 G with the change (perf stat, 5 runs, spread 0.25%).
b Root cause explained? ReplacingSortedAlgorithm pays a full iteration per row (refcounted RowRef, key comparison, per-row byte check, per-column insert, queue step) even inside long batches from a part with a non-zero level, where every row strictly inside the batch is a group of its own.
c Fix matches root cause? Yes: those rows are written in one go; every per-row side effect (row sources, is_deleted check, CLEANUP, TTL filter) and the block limits are kept. No setting, no change of results.
d Test intent preserved / new tests added? New performance test replacing_final_updated_parts.xml. No new functional test: existing stateless tests (03915, 05193, 05316) fail with mutations of the new path and pass with it; a differential harness covers the remaining mutations.
e Both directions demonstrated? Paired A/B vs master (FINAL 0.68, merge 0.75 user CPU); 259 result and part-file digests identical to master; six mutations of the new path each produce mismatches.
f Fix is general across code paths? Covers vertical and non-vertical FINAL, horizontal and vertical merges (row sources), CLEANUP, TTL row filter, is_deleted validation; reverse order and permutation reads keep the per-row path; other algorithms on the same base only get the shared predicate.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked: one- and two-column keys, String key, no version / version / is_deleted, LowCardinality, Nullable, JSON, AggregateFunction, 16 columns, row/byte merge limits (default, 1000 rows, 64 KiB, both, 0), parts with a shortened key or adopted by ATTACH PART.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or default change; results and merged part files identical to master.
i Invariants and contracts preserved? Rows, order and row sources identical; max_block_size exact; byte limits via rowsToInsertBeforeFlush or per-row hasEnoughRows; the last row of a batch is left to the loop, so the selected row and the queue stay consistent; an invalid is_deleted gives the same error.

Session id: cron:clickhouse-impl-slot-4:20261114-043401

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [00b9f2e]

Summary: ✅


AI Review

Summary

This PR batches rows from parts with unique keys in ReplacingSortedAlgorithm to accelerate ReplacingMergeTree merges and SELECT ... FINAL, and counts those rows toward vertical FINAL selection waits. No actionable findings. The reported paired benchmarks, differential checks, and regression coverage support approval.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 14, 2026
@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 14, 2026
groeneai and others added 2 commits November 14, 2026 08:45
`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 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 00b9f2e0d with master 463f45f5f (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

10 object files changed (+93.54 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/ReplacingSortedAlgorithm.cpp.o 199.32 KiB 275.44 KiB +76.12 KiB (+38.19%)
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/IMergingAlgorithmWithSharedChunks.cpp.o 122.89 KiB 140.15 KiB +17.25 KiB (+14.04%)

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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 00f9039

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, iceberg_local, 1/3) / Insert historical data perf CI harness, the same signature in all six Iceberg jobs: this PR adds tests/performance/replacing_final_updated_parts.xml, so these jobs run only that test, no query of it is measured on both servers, and compare.sh stops before it writes report/all-query-metrics.tsv (FileNotFoundError, Errors while building the report.). Same signature on 11 other PRs since 2026-11-10 #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_local, 2/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_local, 3/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 1/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 2/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 3/3) / Insert historical data same as the first row #129874 (mine, open)
PR praktika rollup of the rows above #129874 (the owner above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261114-120014

The six `Performance Comparison (*, iceberg_*)` jobs run a performance test
that a PR adds on Iceberg tables. This test cannot run there: it modifies
`max_bytes_to_merge_at_max_space_in_pool`, reads with `FINAL` and checks
`system.parts`, none of which the Iceberg rewrite supports (`Setting
'max_bytes_to_merge_at_max_space_in_pool' cannot be modified for Iceberg
storage`). It measures ReplacingMergeTree FINAL and merges, so opt it out with
`<test iceberg="0">`. With it, `changed_iceberg_tests` selects no test and the
Iceberg jobs are not scheduled; the `master_head` jobs still run the test.

The skip list is not used: `tests/performance/iceberg_skip_list.txt` is in
`ICEBERG_PERFORMANCE_PATHS`, so editing it runs the whole Iceberg suite.

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
…e-unique-batches

# Conflicts:
#	src/Processors/Merges/Algorithms/IMergingAlgorithmWithSharedChunks.h
#	src/Processors/Merges/Algorithms/ReplacingSortedAlgorithm.cpp
Since ClickHouse#131560, vertical FINAL emits the rows selected so far from a chunk whose
selection waited longer than a merge of its input should take, measured in
selected rows (`num_selected_rows`). `insertUniqueRows` appended whole batches to
`replace_final_selection` without counting them and without stamping
`replace_final_selection_start` on a new selection, so on a merged part the clock
advanced by about three rows per batch and the small part's selection waited to
the end of the merge.

Measured on a debug build: a merged 200000-row part plus a 400-row part holding
the newest version of every 500th key, `SELECT k FROM t FINAL WHERE v = 'target'
LIMIT 1` with `enable_vertical_final = 1, max_threads = 1` read 200400 rows
without this change and reads 4496 with it, the same as master. Results of
FINAL with and without vertical FINAL are unchanged.

The new case in 05632 fails without this change (5 of 5 randomized runs) and
passes with it (30 of 30) and on master.

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.

ReplacingMergeTree FINAL and merges: take rows from parts without duplicate keys in whole batches, 33-45% faster FINAL on tables with recent updates

1 participant