Skip to content

Faster FINAL and merges of ReplacingMergeTree and CollapsingMergeTree tables - #131494

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:replacing-collapsing-merge-no-per-row-rowref
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:replacing-collapsing-merge-no-per-row-rowref

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131239
Related: #120649

Changelog category (leave one):

  • Performance Improvement

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

FINAL queries and merges of ReplacingMergeTree and CollapsingMergeTree tables are faster: FINAL over many overlapping parts uses 9-25% less CPU.

Description

ReplacingSortedAlgorithm::merge and CollapsingSortedAlgorithm::merge built a RowRef for every input row only to compare it with the kept row. The out-of-line RowRefWithOwnedChunk::set took the chunk pointer by value (a reference count increment and decrement per row), and vertical FINAL recorded each kept row through IColumn::insert(const Field &). Analysis and patches by @ snelheidai.

The change is made once, in the shared helpers: set is inline, takes the chunk by const reference and re-binds it only when it changes, and rowsHaveDifferentSortColumns compares a row with the cursor. Collapsing builds a RowRef only for a row with an invalid sign; vertical FINAL appends the row number directly. VersionedCollapsingMergeTree queues every row, so it keeps its RowRef and gains only from the inline set. The part-level shortcut questioned in #120649 is unchanged and now has one implementation.

Local A/B on the issue's data (release build without ThinLTO, 4 cores, 20 paired rounds, fix/master, 95% CI):

Query elapsed user CPU
FINAL, 50 parts, unique keys 0.90 [0.85, 0.96] 0.84 [0.81, 0.88]
FINAL, 50 parts, version column 0.88 [0.84, 0.92] 0.84 [0.81, 0.88]
FINAL, 4 large parts 0.88 [0.83, 0.93] 0.75 [0.72, 0.78]
CollapsingMergeTree FINAL, 50 parts 0.92 [0.88, 0.96] 0.91 [0.89, 0.93]
OPTIMIZE ... FINAL, version column 0.88 [0.85, 0.91] 0.88 [0.85, 0.91]
OPTIMIZE ... FINAL, plain MergeTree (control) 0.99 [0.95, 1.03] 0.99 [0.95, 1.03]

User-space instructions of the first query drop by 22%. Output is byte-identical to master in 393 checks (both FINAL modes, merges, CLEANUP, TTL, lightweight deletes, invalid signs, insert-time merges); two mutations of the new code break 145 and 363 of them. A new performance test covers both engines over overlapping parts.


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

…ngMergeTree merges

`ReplacingSortedAlgorithm::merge` and `CollapsingSortedAlgorithm::merge` built
`RowRef current_row` with `setRowRef` for every input row. That copied the chunk's
`SharedChunkPtr` by value into the out-of-line `RowRefWithOwnedChunk::set`
(refcount up, release of the row's previous chunk, refcount down when the row
dies), only to compare the row with the kept one and to read its source number.
Collapsing also copied it into `last_row` at every new key, and vertical FINAL
recorded every kept row number through `IColumn::insert(const Field &)`.

Change the two shared helpers once instead of adding per-algorithm copies:

- `RowRefWithOwnedChunk::set` is inline, takes the chunk by const reference and
  re-binds it only when the row points to another chunk. A held reference keeps
  its allocator slot alive, so an equal pointer is the same live chunk.
- `IMergingAlgorithmWithSharedChunks::rowsHaveDifferentSortColumns` compares a
  row with a cursor (same logic: the part-level shortcut, `prev_unequal_column`,
  `checkEqualsFirstNonEqual` on the cursor's `sort_columns` and `getRow()`).
  The RowRef/RowRef form had no other caller, so the shortcut questioned in
  ClickHouse#120649 stays in one place for both algorithms.

Replacing and Collapsing compare against the cursor and take the source number
from it; Collapsing builds a RowRef only for a row with an invalid sign, which
it inserts or buffers. Vertical FINAL appends the row number to its
`ColumnUInt64` directly. `max_row_refs` is unchanged: the slots counted for
"current" are headroom that vertical FINAL's `to_be_emitted` queue uses.

Local A/B, non-LTO RelWithDebInfo, Xeon 6975P-C, 4 pinned cores, 10 paired
rounds, user CPU fix/base geomean [95% CI]: rsrc50 FINAL 0.86 [0.79, 0.94],
rver50 FINAL 0.84 [0.77, 0.92], rver4 FINAL 0.79 [0.74, 0.84],
ccol50 FINAL 0.90 [0.87, 0.93], OPTIMIZE FINAL rver50 0.87 [0.81, 0.93];
instructions:u rsrc50 FINAL 0.78, ccol50 FINAL 0.92; plain MergeTree OPTIMIZE
0.996 (control). Adds a performance test for Replacing/Collapsing FINAL over
overlapping parts (no CollapsingMergeTree FINAL perf test existed).

Analysis and patches from ClickHouse#131239 by @ snelheidai.

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) plus my own review (3 findings).

# Sev Finding Verdict Evidence / action
1 ❌ The level>0 shortcut in rowsHaveDifferentSortColumns splits a merged CollapsingMergeTree part's -1/+1 pair, so a re-merge turns sum(sign) 1 into 0 (#120649) DISAGREE (separate PR) Real and pre-existing: the issue's repro prints the same wrong result on master and on this PR, and the shortcut predicate is unchanged. Fixing it changes results and Collapsing merge cost, so it gets its own Bug Fix PR; this PR leaves the shortcut in one place for it.
2 ⚠️ The new performance test may exceed the perf CI time limits DISAGREE Locally every query runs in 0.24-0.44 s on master and each fill in about 1.3 s; the limits are 2 s per run and about 60 s per test.
3 💡 VersionedCollapsingMergeTree still builds a per-row RowRef AGREE, description updated It queues every row it reads, so it keeps the RowRef and only gains from the inline set.

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

Session id: cron:clickhouse-review-slot-9:20261114-002402

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: user-space instructions of rsrc50 FINAL fix/master 0.78 (master run-to-run spread 0.3%); user CPU CI excludes 1 for every headline query in 20 paired rounds.
b Root cause explained? Every input row got an owning RowRef (chunk pointer copied by value into the out-of-line RowRefWithOwnedChunk::set) only to be compared with the kept row; vertical FINAL recorded each kept row via insert(const Field &). Master profile: setRowRef 7.5%, set 4.1%, insert(Field) 1.7%, Field::safeGet 1.0%; all gone with the change.
c Fix matches root cause? Yes: the per-row RowRef and the by-value copy are removed in the shared helpers; no guard, no setting.
d Test intent preserved / new tests added? Behaviour-preserving performance change: a new performance test (no CollapsingMergeTree FINAL perf test existed); existing tests unchanged.
e Both directions demonstrated? Faster than master on the same data and binary config; output byte-identical to master in 393 checks, while two mutations (stale row number, getPos instead of getRow) break 363 and 145 of them.
f Fix is general across code paths? Changed once in IMergingAlgorithmWithSharedChunks / RowRefWithOwnedChunk, used by Replacing, Collapsing, VersionedCollapsing and Graphite; Summing/Aggregating/Distinct use the non-owning RowRef without a reference count.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked with UInt64, DateTime64 and String keys, no version / version / is_deleted, level 0 and 1 parts, small and default blocks, vertical and horizontal merges, TTL and lightweight-delete row filters, invalid signs, reverse reads, permuted insert merges.
h Backward compatible? (maintainer-approved exception only) Yes: no format, setting or result change.
i Invariants and contracts preserved? A held reference keeps its allocator slot alive, so an equal chunk pointer is the same live chunk and skipping the self-assignment changes no reference count; chunk lifetimes, the vertical FINAL emit order and the allocator capacity are unchanged.

Session id: cron:clickhouse-impl-slot-7:20261113-230600

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dbdbe0e]

Summary: ✅


AI Review

Summary

Removes temporary owning RowRef objects from the ReplacingSortedAlgorithm and CollapsingSortedAlgorithm loops, inlines RowRefWithOwnedChunk::set, and appends vertical FINAL selections directly to ColumnUInt64. Reviewed the full diff and current code at dbdbe0e95e799d2b0b9d2f90d4543b0675dd01eb, shared-helper callers, and all prior discussion. No actionable findings. The supplied paired benchmarks support the performance claim, and the current head's Fast test passed 15,094 tests, including relevant merge and FINAL regression tests.

Missing context / blind spots
  • ⚠️ Broader CI, sanitizer runs, and performance comparisons for the current head are still pending. Their completed reports would close this validation gap. No local server tests or benchmarks were run because this checkout has no ClickHouse binary; performance assessment relies on the measurements supplied in the PR and linked issue.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements 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
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dbdbe0e95 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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7eb9620

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_collapsing_final_overlapping_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.) #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)

The Config Workflow / Pre Hooks failure in CIDB comes from the run before the can be tested label was added. CIDB has no other FAIL or ERROR row on this head.

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

…g perf jobs

The test measures FINAL and merges of ReplacingMergeTree and
CollapsingMergeTree, and Iceberg storage does not support FINAL
("Storage IcebergLocal doesn't support FINAL"), so the six
`Performance Comparison (*, iceberg_*)` jobs that a new MergeTree test
schedules could not run any of its queries. Opt the test out with
`<test iceberg="0">` instead of an iceberg_skip_list.txt entry: that
file is in ICEBERG_PERFORMANCE_PATHS, so editing it would run 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
…g-merge-no-per-row-rowref

Conflicts resolved against master:
- ClickHouse#126158 added [[nodiscard]] to lines this PR edits: kept, except on
  RowRefWithOwnedChunk::firstNonEqualSortColumnsWith, which this PR removes.
- ClickHouse#131513 gated the part-level shortcut of rowsHaveDifferentSortColumns with
  nonzero_level_parts_have_unique_keys: the cursor overload keeps that gate,
  so CollapsingMergeTree still compares rows of merged parts.
- ClickHouse#131560 counts selected rows in vertical FINAL: kept, the selection is
  appended with push_back instead of insert(Field).

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

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 and CollapsingMergeTree FINAL: skip the reference-counted RowRef copy per row in the merge algorithms, 6-25% faster FINAL

1 participant