Skip to content

Use merge_use_batch_sorting_queue for projection merges - #132085

Merged
Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/projection-merges-batch-sorting-queue
Nov 18, 2026
Merged

Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/projection-merges-batch-sorting-queue

Conversation

@groeneai

@groeneai groeneai commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #127826
Related: #108468

Changelog category (leave one):

  • Improvement

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

With merge_use_batch_sorting_queue enabled, merges of normal projection parts, including the temporary parts written while a projection is built, now also use the batch sorting queue. With the setting enabled, merged projection parts can be split into blocks differently than on previous versions. The data is the same, but in a ReplicatedMergeTree cluster with replicas on different versions this can show up as a harmless "not byte-identical" checksum mismatch, after which the replica downloads the merged part from another replica.

Description

Asked for in #127826 (comment). #108468 kept every MergeTask with global_ctx->projection on the default sorting queue for missing coverage (#108468 (comment)), not for a defect. Now merge_may_reduce_rows alone decides, as for base tables: normal projections merge as Ordinary, row-preserving child tasks, aggregate projections and children of DEDUPLICATE/CLEANUP merges keep the default queue, and _parent_part_offset is remapped while the projection parts are read, not by the sorting algorithm.

Release build, OPTIMIZE ... DRY RUN PARTS of 10 parts, medians:

shape ratio whole merge projection stage
2 columns, 1M rows per part, parent key disjoint, projection parts in runs of 100 rows PR / master 0.909 0.850
same, projection key interleaved row by row PR / master 1.047 1.060
2 columns, 2M rows per part, parent key hashed, runs of 100 rows setting on / off 0.961 0.788
4 columns, SELECT * projection, runs of 100 rows setting on / off 0.994 0.946

Projection parts disjoint in the projection key show no gain (1.03 on / off: the default queue already moves whole chunks there); the temporary parts of MATERIALIZE PROJECTION in runs of 100 rows take 0.953 (on / off). Where the projection key interleaves row by row, the batch queue costs up to 6% of the projection stage.

The new test compares the merged projection parts under both queues (normal, _parent_part_offset and commit-order projections, horizontal and vertical merges, temporary parts) and checks in part_log that the projections were merged, not rebuilt. With the setting forced on, 483 existing projection tests show no content difference (04812 gets 159 instead of 157 marks, a granule layout change master also shows for base tables).

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2764-master (included in 26.11 and later)

groeneai and others added 2 commits November 16, 2026 14:06
The `!global_ctx->projection` guard in `createMergedStream` kept every child
`MergeTask` that merges projection parts (the projection-part merges of a parent
merge and the temporary-part merges of `MergeProjectionPartsTask`) on the default
sorting queue, even with `merge_use_batch_sorting_queue = 1`. It was added in
ClickHouse#108468 for missing coverage, not for a defect. Normal projection merges are
`Ordinary` and row-preserving; aggregate projections and children of
DEDUPLICATE/CLEANUP parents still have `merge_may_reduce_rows` and keep the
default queue. `_parent_part_offset` is remapped when the projection parts are
read, not by the sorting algorithm.

The new test compares the merged projection parts (rows and positions) between
the two queues for a normal projection with another sorting key, a
`_parent_part_offset` projection and a commit-order projection, in horizontal and
vertical merges, asserts via part_log that the projections were merged rather
than rebuilt, and covers the temporary parts that `MATERIALIZE PROJECTION`
writes for a part larger than `min_insert_block_size_rows`.

Related: ClickHouse#127826
Related: ClickHouse#108468

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

Two tables with `merge_use_batch_sorting_queue = 1` and a normal projection, ten
parts each, merged with `OPTIMIZE ... DRY RUN PARTS`. The parts are disjoint in the
table's sorting key, so the parent merge does the same work on master and with this
change. In the first table the projection parts alternate in runs of 100 rows of the
projection key, the case the batch queue serves; in the second they interleave row
by row, where it cannot help.

Measured locally on release builds, 32 alternating runs, PR / master medians: the
runs query 0.909 (projection stage 0.850), the interleaved query 1.047 (projection
stage 1.060). Runs of 1000 rows (0.911) and a second run-shaped projection (0.911)
did not separate the binaries further.

`optimize_dry_run_check_part = 0` keeps `checkDataPart` of the dry-run result out of
the measurement. The test opts out of the Iceberg configuration with
`<test iceberg="0">`: OPTIMIZE DRY RUN is only supported for MergeTree tables, and
an edit of `iceberg_skip_list.txt` would run the whole Iceberg configuration.

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

clickhouse-gh Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [740001e]

Summary: ✅


AI Review

Summary

Reviewed commit 740001e888f99c48251c1e17f5d80565a95f0dc8. The PR extends the opt-in merge_use_batch_sorting_queue setting to normal projection merges, documents its scope, and adds coverage for projection contents, row order, parent offsets, and temporary-part merges. No actionable findings. The description provides local performance measurements; the unchanged regression test passed all 50 ASan flaky-check runs at commit 576c88c2a89d9bb6348e94c972a75b1063e7d284. No local build or tests were run.

Final Verdict

Status: ✅ Approve

@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; bounded: 1 full pass + 1 fix round + 1 delta recheck). My own review found no code issue; it only corrected labels in the PR description.

# Sev Finding Verdict Evidence / action
1 ⚠️ 05813 still passes if projection merges stay on the default queue (05813_merge_batch_sorting_queue_projection_merges.sql) DISAGREE It is the content comparison under both queues asked for in #127826, the same oracle as the setting's existing tests 04411, 04412, 04413 and 04614. SQL cannot observe the queue choice: a ProfileEvent only for a test adds code nobody needs, and asserting the granule layout would pin a side effect that is not part of the contract. The performance test guards the mechanism: projection stage PR / master 0.850, master's own setting on / off 1.006, so restoring the guard brings it back to 1.0.

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

Session id: cron:clickhouse-review-slot-9:20261116-170341

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @cwurm, could you review this? As you asked in #127826, it drops the !global_ctx->projection term from the sorting queue choice in MergeTask, so with merge_use_batch_sorting_queue on, merges of normal projection parts (and of the temporary parts written while a projection is built) use the batch queue; aggregate projections stay on the default queue through merge_may_reduce_rows.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Not a defect, a missed speed-up. The observable is the queue the projection child merge takes: with the setting on, CPU stacks show mergeBatchImpl with this change and mergeImpl on master; the perf test's projection stage is 0.850 PR / master (32 runs; master's own on / off control 1.006).
b Root cause explained? createMergedStream required !global_ctx->projection for the batch queue, so every child MergeTask merging projection parts stayed on the default queue. #108468 added the term for missing coverage (review thread r3616009549), not for a defect.
c Fix matches root cause? The term is deleted; merge_may_reduce_rows stays the only row-preservation predicate, as for base tables.
d Test intent preserved / new tests added? New stateless test comparing mergeTreeProjection contents under both queues (normal, _parent_part_offset, commit-order projections; horizontal, vertical; MATERIALIZE PROJECTION temporary parts), asserting via part_log that projections were merged, not rebuilt; new perf test.
e Both directions demonstrated? Stacks and perf test PR vs master as in (a). The stateless test passes 50/50 randomized, and mutants that reorder the batch tables' inputs make it fail.
f Fix is general across code paths? One condition serves both callers of the child MergeTask (projection merges inside a parent merge and MergeProjectionPartsTask temporary-part merges); aggregate projections and DEDUPLICATE/CLEANUP children keep the default queue through merge_may_reduce_rows; Replicated and Shared MergeTree use the same MergeTask.
g Fix generalizes across inputs (params/datatypes/wrappers)? Equal keys across parts, _part_offset and commit-order projections, horizontal and vertical merges, temporary parts above min_insert_block_size_rows. 483 existing projection tests with the setting forced on: no content difference; one test sees a different granule count (layout only, as on base tables).
h Backward compatible? (maintainer-approved exception only) Opt-in setting, no default, format or settings-history change. Merged projection parts can be split into blocks differently, which a mixed-version ReplicatedMergeTree can report as a harmless "not byte-identical" checksum mismatch; stated in the changelog entry as #127826 did.
i Invariants and contracts preserved? Merged rows, their order, tie order by source, _parent_part_offset, _block_number / _block_offset equal the default queue's (the new test); only granule boundaries may differ.

Session id: cron:clickhouse-impl-slot-40:20261116-143800

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). labels Nov 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 740001e88 with master eb5cbd890 (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

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

Job report

The flaky check ran the test over 180 s in 7 of 126 runs (amd_binary 5,
amd_debug 1, amd_msan 1). The slow runs are the ones whose random
MergeTree settings give the 1.2M-row tables tiny granules or tiny merge
blocks: with `index_granularity` or `merge_max_block_size` below ~2000,
`MATERIALIZE PROJECTION` and `OPTIMIZE FINAL` on them took 100-420 s per
run instead of ~30 s (CI `query_log` and `part_log` of the flaky-check
jobs).

Clamp `index_granularity`, `index_granularity_bytes` and
`merge_max_block_size` from below with a `Random settings limits` line.
The small tables pin `merge_max_block_size` themselves and have one
granule per part either way.

Also write the big table as one part directly, and give the batch-queue
table a copy of it with `ATTACH PARTITION ... FROM`, instead of two
inserts and two `OPTIMIZE FINAL`. The test now checks that the table has
one part, which the temporary projection parts path needs.

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

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review approves this commit, see the AI Review comment.

@cwurm cwurm left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Algunenano Algunenano self-assigned this Nov 18, 2026

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai The test is huge for little benefit (it doesn't even pass the threshold, even if the improvement is good). Longest perf thread in the shard.

Either minimize or drop it please. It's fine if we don't add a perf test for this case really

It is the longest test in its performance shard and its gain stays
below the comparison threshold, so it guards little for its cost.

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

Copy link
Copy Markdown
Collaborator Author

Dropped the performance test in 740001e. The PR now changes only MergeTask.cpp, the setting description and the stateless test 05813; the description keeps the local measurements.

@Algunenano
Algunenano enabled auto-merge November 18, 2026 16:23
@Algunenano
Algunenano added this pull request to the merge queue Nov 18, 2026
Merged via the queue into ClickHouse:master with commit 57b2f01 Nov 18, 2026
193 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 2026
@cwurm

cwurm commented Nov 20, 2026

Copy link
Copy Markdown
Member

@groeneai Thanks! Could you please also remove the remaining !global_ctx->merge_may_reduce_rows term from that condition, so that the queue choice depends only on merge_use_batch_sorting_queue?

It came in the same commit as the projection term (#108468 (comment)), also for missing coverage, not for a defect. Only MergingSortedTransform (Ordinary mode) receives the strategy. The other merging algorithms pick their own queue, so for them the term does nothing. For Ordinary merges it keeps these on the default queue:

  • lightweight deletes (horizontal: filtered at read; vertical: row mask in MergingSortedAlgorithm)
  • patch parts (applied at read)
  • OPTIMIZE ... DEDUPLICATE (DistinctStep after the merge)
  • TTL deletes (horizontal: TTLDeleteFilterStep before the merge; vertical: row mask carried as RowFilterInfo)

In the horizontal cases, the merge itself is a plain sorted merge, so it should get the same gain as other ordinary merges. The batch path already handles row masks (MergingSortedAlgorithm::insertRows writes skipped rows to rows_sources), but this term makes that code unreachable today. The vertical cases matter most: the batch path's mask handling has never been exercised, since it was added in bfb72a13736d while merges still used only the default queue.

Only the queue condition should change. merge_may_reduce_rows is also used elsewhere in MergeTask, for example to decide whether projections, text indexes, statistics and the minmax index are rebuilt, and those uses must stay as they are.

Please update the setting description and add a small, fast stateless test that compares the merged result under both queues for lightweight delete, TTL delete (horizontal and vertical each, including _block_number / _block_offset for the vertical ones), patch parts and DEDUPLICATE. No performance test needed. Local measurements in the description are enough, for example a merge of overlapping parts with a lightweight delete on about 5% of rows, with the setting on and off. If all works, create a PR and ping me on it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'm investigating removing the !global_ctx->merge_may_reduce_rows term from the batch-sorting-queue condition (with the setting description, the both-queues stateless test and a local measurement); I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I opened #133262. It removes the term, rewrites the setting description and adds the test you described; the vertical cases now run the row-mask code in MergingSortedAlgorithm::insertRows, and the merged parts match the default queue's.

Merge time with the setting on / off (release, 10 overlapping parts of 1M rows, 5% of rows deleted): 0.92 for a horizontal lightweight delete merge, 0.98 for vertical lightweight delete and TTL delete merges (masked rows are still inserted one by one), and 1.04 where the keys interleave row by row. One correction to the mechanism: in horizontal merges expired TTL rows are dropped by TTLStep after the merge; TTLDeleteFilterStep exists only for vertical merges.

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-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants