Skip to content

Faster merges of many small parts with fixed-size columns - #131534

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/issue-131192-merged-data-fixed-size-bytes
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/issue-131192-merged-data-fixed-size-bytes

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #131192

Changelog category (leave one):

  • Performance Improvement

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

Merges of many small parts are faster for tables with fixed-size columns (numbers, dates, decimals, UUIDs, IP addresses, FixedString): the merge no longer asks every column for its size after every row, and when it merges at least 8 parts it prefetches the next rows of each part. OPTIMIZE FINAL of 50 parts of 200000 rows with 9 columns uses 9% less CPU, and 11-12% less with merge_use_batch_sorting_queue = 1.

Description

Analysis, prefetch and original measurements by snelheidai in #131192, verified and reworked.

To respect merge_max_block_size_bytes, MergedData asks every output column for its size through the virtual IColumn interface: byteSize() per merged row with the default sorting queue, byteSizeAt() per row and column with the batch queue. Columns whose getPlanes() is Shape::Fixed (ColumnVector, ColumnDecimal, ColumnFixedString) are now counted from the row count. The count is exact, so blocks are cut at the same rows and merged parts stay byte-identical. When at least 8 inputs are merged, the next cache line of each fixed-size column of the source just consumed is prefetched, only inside its data.

The issue's in-place copy is not included: it saved about 5% more CPU with the default queue and nothing with the batch queue, which with this PR is 11-18% cheaper than the default queue for these tables.

Release ThinLTO, Xeon 6975P-C, 4 pinned vCPUs, 20 paired runs, CPU time, PR / master (95% CI):

OPTIMIZE FINAL, 50 parts of 200000 rows ratio
9 columns 0.911 [0.900, 0.923]
3 columns, batch queue 0.876 [0.859, 0.893]
9 columns, batch queue 0.887 [0.880, 0.894]
read in order of the 50 parts, 9 columns 0.948 [0.934, 0.963]
3 columns; String-only; 6 parts 1.013; 0.998; 0.996 (n.s.)
full ORDER BY, 4 / 16 threads 1.021 [1.004, 1.038] / 1.013 (n.s.)

Memory is unchanged. Merged parts are identical to master for 20 cases (both queues, vertical merges, TTL and lightweight deletes, 4096-byte blocks, 30 fixed-size types, sparse columns), 7 of them also under ASan+UBSan. New perf test optimize_many_small_parts.xml.

My #131486 (JSON/Dynamic batching) also changes MergedData::rowsToInsertBeforeFlush; the two are independent, whichever merges second is rebased.


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

groeneai and others added 4 commits November 13, 2026 22:00
…rges of many sorted inputs

`MergedData` measured the output block through the virtual `IColumn` interface for every column,
per row in `hasEnoughRows` (default queue) and per row and column in `rowsToInsertBeforeFlush`
(batch queue), even for plain fixed-size columns whose size is exactly `rows x value size`.
`MergingSortedAlgorithm` now asks `MergedData` to classify its columns through
`IColumn::getPlanes` while no `ColumnReplicated` column can reach the merge: columns with
`Shape::Fixed` planes (`ColumnVector`, `ColumnDecimal`, `ColumnFixedString`) are counted as
`base + merged_rows x stride` (the base is `sizeof(n)` for `FixedString`, zero otherwise), so
merge blocks are cut at the same rows as before and merged parts stay byte-identical. The
classification is redone after `insertChunk`, the only place the destination columns are
replaced.

When at least 8 inputs are merged, each run inserted from a source is followed by a prefetch of
the cache line 64 bytes past the start of that source's next row in each of its fixed-size
columns, formed only when it lies inside the chunk column's data. With many interleaved parts
the merge reads more streams than the hardware prefetcher follows; with few inputs the prefetch
was measured in ClickHouse#131192 to cost more than it gains.

The analysis, the prefetch and the original measurements are from ClickHouse#131192.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`OPTIMIZE ... FINAL` of 50 parts of 100000 rows sorted by `(sid, ts)`, with the default and with
the batch sorting queue, the same merge of a table without fixed-size columns, and a read in order
of the 50 parts. Every timed merge re-attaches the source parts first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…irst block of the byte-limit gtest

The Iceberg performance configuration selects every new test that creates a
MergeTree table unless it opts out. `optimize_many_small_parts.xml` checks
`system.parts` and runs `ATTACH PARTITION ... FROM` and `OPTIMIZE ... FINAL`,
which cannot work on the rewritten Iceberg tables, so it opts out with
`<test iceberg="0">`, like `coalesce_short_circuit.xml`. The skip list is not
used because changing it runs the whole Iceberg configuration.

`MergingSortedBatchLimits.MaxBlockSizeBytes` only compared the default and the
batch queue, which share the fixed-size byte count, so a miscount common to
both passed. It now also checks that the 100-byte limit cuts the first block
after 3 rows, which is master's behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the refuted-alternative clause from the enableFixedSizeByteCount doc comment.

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; 3 findings over 2 rounds).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new perf test would be selected by the Iceberg performance configuration, where its system.parts checks and ATTACH PARTITION cannot run AGREE, fixed @ 313ac37 <test iceberg="0">
2 💡 Query-side merges (max_block_size_bytes = 0) still classify the fixed-size columns at each inserted chunk although nothing reads it AGREE, not changed per chunk, not per row; no effect on results
3 💡 No gtest has a FixedString column, so its constant sizeof(n) in the byte count is not pinned AGREE, not changed the constant is derived from byteSize(); merged parts with FixedString and 4096-byte blocks are identical to master

Severity: ❌ blocker / ⚠️ major / 💡 nit. Also from my own review: MergingSortedBatchLimits.MaxBlockSizeBytes compared the two queues only, so it now also pins the first block at 3 rows (fixed @ 313ac37).

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Performance change. Release ThinLTO, 4 pinned vCPUs, 20 paired rounds per shape, CPU time from system.query_log: OPTIMIZE FINAL of 50 parts x 200000 rows, 9 columns 0.911 [0.900, 0.923], 3 columns batch queue 0.876 [0.859, 0.893], 9 columns batch queue 0.887 [0.880, 0.894], read in order 0.948 [0.934, 0.963]; intervals exclude 1.
b Root cause explained? MergedData asks every output column for its size through the virtual interface per merged row (default queue) or per row and column (batch queue) to honor merge_max_block_size_bytes; with many interleaved parts the first read of a run misses cache.
c Fix matches root cause? Columns with Shape::Fixed planes are counted from the row count (exact, base + rows x stride); the other columns are asked as before. With >= 8 inputs the next row of the source just consumed is prefetched, inside its data only.
d Test intent preserved / new tests added? New perf test optimize_many_small_parts.xml (default and batch queue merges, String-only control, read in order). MergingSortedBatchLimits.MaxBlockSizeBytes covers the new byte count and now also pins the first block at 3 rows (master's cut), so a miscount shared by both queues that moves the cut fails it; three mutants of the count each fail it.
e Both directions demonstrated? Same data on master and PR binaries (above); perf.py on the new test: -9.3% / -17.1% / -16.6%, String-only n.s.; the gtest mutants fail and the restored code passes 32/32.
f Fix is general across code paths? All MergingSortedAlgorithm users: horizontal merges, key columns of vertical merges, read in order, final merge of ORDER BY. Other merging algorithms do not enable it and are unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Merged parts identical to master for 20 cases: both queues, merge_max_block_size = 100, merge_max_block_size_bytes = 4096, vertical merges, TTL and lightweight deletes, Nullable/LowCardinality/String, 30 fixed-size types incl. FixedString, UInt256, Decimal256, sparse columns. Wrapped columns keep the old path.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or on-disk change; merged parts are byte-identical.
i Invariants and contracts preserved? The counted size equals the sum of byteSize() while no ColumnReplicated column can reach the merge; classes are recomputed after insertChunk. ASan+UBSan gtests and server cases clean; 0 stateless tests fail with the PR that pass on master.

Session id: cron:clickhouse-impl-slot-6:20261114-042900

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ddad531]

Summary: ✅


AI Review

Summary

Reviewed #131534 at ddad531c2877e87b269a1e427abc450b9f5399ad, including all six changed files, surrounding merge logic, callers, column representations, and prior discussion. The change replaces per-row fixed-size column measurements with row-count arithmetic and prefetches fixed-size source data for merges with at least eight inputs. No actionable correctness, memory-safety, compatibility, or performance findings remain. The reported paired benchmarks and correctness comparisons support the change.

Missing context / blind spots
  • ⚠️ No local build directory or ClickHouse binary was available, so runtime tests and benchmarks were not rerun. The fetched CI reports contain passing Fast test results but no detailed unit-test or performance-comparison results. Runtime evidence beyond Fast test comes from the author's reported regression, sanitizer, byte-identical-part, and before/after performance checks; completed unit-test and performance reports would independently confirm it.
Final Verdict

Status: ✅ Approve. No new inline findings or existing review threads require action.

@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 ddad531c2 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.58, programs/clickhouse-keeper ×0.64 (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 11.9 s +8.3 s (+232%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.3 s +5.2 s (+255%)
Compile time of recompiled translation units

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

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

Job report

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

1 participant