Skip to content

Skip the batch bookkeeping for one-row batches and whole chunks when merging sorted streams - #132178

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/merge-batch-one-row-whole-chunk
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/merge-batch-one-row-whole-chunk

Conversation

@groeneai

@groeneai groeneai commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #127826

Changelog category (leave one):

  • Performance Improvement

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

Merging sorted streams with the batch sorting queue is faster when the keys of the sources interleave row by row or do not overlap. This speeds up queries that merge sorted streams without LIMIT, for example ORDER BY read in order, and merges of tables with merge_use_batch_sorting_queue.

Description

MergingSortedAlgorithm::mergeBatchImpl ran the same bookkeeping for every batch. Without a row limit (merges never have one) two shapes make it a no-op:

  • A chunk moved whole (keys of the sources do not overlap) first went through MergedData::rowsToInsertBeforeFlush, which for merges calls byteSizeAt per row and column, and the whole-chunk branch then ignored the result. The call is now skipped for it.
  • A one-row batch (keys interleaved row by row) that is not the last row of its chunk now takes insertRow, as mergeImpl does: hasEnoughRows has just checked the block limits and rowsToInsertBeforeFlush returns 1 for one row.

With a row limit the old code runs. Output does not change: merged parts are byte-identical with and without the change (5 shapes x 16 KiB / 10 MiB merge_max_block_size_bytes x horizontal / vertical), as are read-in-order results.

Release build, 10 parts x 1M rows, geomean of 12 paired PR / master ratios, two runs with the server core sets swapped:

query run 1 run 2
merge, keys disjoint -8.1% -6.6%
merge, keys disjoint, 5 columns with String -4.0% -3.4%
merge, keys interleaved row by row -2.8% -3.9%
merge, keys in runs of 100 rows -0.1% (n.s.) -0.7% (n.s.)
merge with the default queue (setting off) n.s. n.s.
SELECT * ... ORDER BY b read in order, 4 threads -5.1% -8.8%

The new perf test covers the first, third and last rows; the CI comparison flags only changes above 15%, so it will show them as unchanged.

The finding and the patch are by @ snelheidai (#127826 (comment)).

🤖 Generated with Claude Code


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

groeneai and others added 2 commits November 16, 2026 23:31
…merging sorted streams

`MergingSortedAlgorithm::mergeBatchImpl` ran the same per-batch bookkeeping for every batch, but
two batch shapes make all of it a no-op when there is no row limit (merges never have one):

- A chunk moved whole (keys of the sources do not overlap) first went through
  `MergedData::rowsToInsertBeforeFlush`, which for merges walks every row of the chunk calling
  `byteSizeAt` per column, and the whole-chunk branch then ignored the result (it never reads
  `updated_batch_size` / `batch_skip_last_row` without a limit).
- A one-row batch (keys interleaved row by row) that is not the last row of its chunk paid the
  out-of-line `rowsToInsertBeforeFlush` call and the clip / limit / whole-chunk checks:
  `hasEnoughRows` has just checked the block limits, `rowsToInsertBeforeFlush(.., 1, ..)` returns
  1, and `insertRows(cur, 1)` is `insertRow(cur)`. It now takes `insertRow`, as `mergeImpl` does.

With a row limit the old code runs unchanged. Merged parts are byte-identical with and without
the change (5 table shapes x 16 KiB and 10 MiB `merge_max_block_size_bytes` x horizontal and
vertical), and query results are identical.

Release build, 10 parts x 1M rows, 12 paired runs, geomean of fix / base ratios (two runs with
the server core sets swapped): batch-queue merge with disjoint keys -8.1% / -6.6%, 5 columns with
`String` -4.0% / -3.4%, keys interleaved row by row -2.8% / -3.9%, runs of 100 rows -0.1% / -0.7%
(n.s.); `SELECT * ... ORDER BY b` read in order, 4 threads, -5.1% / -8.8%. Merges with the default
queue: no change.

Adds the perf test `merge_batch_sorting_queue.xml`.

Proposed and measured by @ snelheidai: ClickHouse#127826 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reword the two new comments: name `limit` instead of the ambiguous "row limit", and say a whole chunk ignores all block limits (bytes and average size), not only the byte limit.

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 (2 nits). No code change.

# Sev Finding Verdict Evidence / action
1 ⚠️ The perf test has no assertion, so it stays green if either bypass is reverted DISAGREE Perf tests measure time, and a revert changes it (disjoint merge -8.1% / -6.6%, read in order -5.1% / -8.8% in the release A/B). The functional tests already catch a broken bypass: dropping the one-row insertRow fails 04411 and a gtest; gating the call on limit only fails MergingSortedBatchLimits.MaxBlockSizeBytes and AverageBlockSize. A branch counter would mean a new profile event for a test only.
2 💡 The interleaved merge query runs about 1 s, close to the 2 s per-run cap of the perf report noted 0.95 s here, about 1.45 s on r6i.xlarge
3 💡 The comment on the whole-chunk path names only the byte limit; the average-block-size clip is ignored there too noted comment reworded before publishing

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Not a defect, a measured speed-up. Release A/B, 10 parts x 1M rows, 12 paired runs per query, run twice with the two servers' core sets swapped: batch-queue merge with disjoint keys -8.1% [-9.1, -7.0] and -6.6% [-7.7, -5.4]; read-in-order SELECT * -5.1% [-8.8, -1.3] and -8.8% [-12.6, -4.8]. In-tree perf.py --runs 9 on the new perf test: PR / master 0.960, 0.927, 0.948.
b Root cause explained? mergeBatchImpl called rowsToInsertBeforeFlush for every batch. For a chunk moved whole the whole-chunk branch never reads its result without a row limit, yet with merge_max_block_size_bytes the call walks every row of the chunk calling byteSizeAt per column. For a one-row batch that is not its chunk's last row every check is a no-op (hasEnoughRows just passed, the call returns 1 for one row, insertRows(cur, 1) is insertRow(cur)).
c Fix matches root cause? The call is skipped for a whole chunk and a one-row batch takes insertRow, both only without a row limit; with a limit the old code runs unchanged. No new mechanism: insertRow and insertChunk are reused as is.
d Test intent preserved / new tests added? Behaviour-preserving change, no new functional test. Mutations prove the existing tests reach both paths: dropping insertRow from the shortcut fails 04411 (server Logical error) and aborts a gtest; computing the byte cut only with a limit fails MergingSortedBatchLimits.MaxBlockSizeBytes (3 vs 51) and AverageBlockSize. New perf test merge_batch_sorting_queue.xml.
e Both directions demonstrated? Base and fix release binaries on the same data: (a). Output identity: merged part hash_of_all_files equal base vs fix on 20 tables (5 shapes x 16 KiB / 10 MiB byte limit x horizontal / vertical), source parts equal, and 4 of the 10 shape pairs change bytes between 16 KiB and 10 MiB on one binary, so the check sees flush boundaries. Read-in-order, LIMIT 123457 and full-sort result hashes equal.
f Fix is general across code paths? mergeBatchImpl is the only caller of rowsToInsertBeforeFlush, shared by every batch-queue user: merges with merge_use_batch_sorting_queue and all query-time sorted-stream merges (read in order, MergeSortingTransform, FINAL, aggregation in order). Other merging algorithms have their own loops and are untouched.
g Fix generalizes across inputs (params/datatypes/wrappers)? Merged parts identical for UInt64, Float64, UInt32, String and LowCardinality(String) columns, disjoint, interleaved and runs-of-100 keys, both byte limits, horizontal and vertical merges. Paths with a row limit, virtual rows (skip_last_row), use_average_block_size and row filter masks keep their behaviour (gated conditions, gtests, 226 read-in-order / sorting-queue stateless tests with the batch queue forced on for merges: no failure that master does not have).
h Backward compatible? (maintainer-approved exception only) No setting, format or on-disk change; merged parts are byte-identical.
i Invariants and contracts preserved? mergeBatchImpl emits the same chunks, rows, order, block boundaries, limit_reached and row-source bytes: the one-row shortcut does exactly what the old path did for that batch, and the skipped call is const with no side effects.

Session id: cron:clickhouse-impl-slot-4:20261116-222700

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bff98e9]

Summary: ✅


AI Review

Summary

Reviewed commit bff98e949387dab475c0716feba80da020165b61. The PR removes redundant bookkeeping from MergingSortedAlgorithm::mergeBatchImpl for non-final one-row batches and whole chunks when limit is zero, and adds a focused performance test. No actionable findings. The reported paired benchmarks support the performance claim; the existing queue correctness, equal-key ordering, vertical-granularity, and part-offset tests pass in the Fast test report. Local execution was unavailable because this checkout has no ClickHouse binary or build directory.

Final Verdict

✅ 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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

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 ⚠️

3 object files changed (+334.33 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp.o 3.88 MiB 4.20 MiB +334.32 KiB (+8.42%)

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.

Compile time of recompiled translation units

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

Job report

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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant