Repository navigation
Assign merges for all partitions at once for OPTIMIZE FINAL - #109004
Conversation
For a non-replicated `MergeTree` table, `OPTIMIZE TABLE ... FINAL` without an explicit partition used to process partitions one by one: it selected and ran the merge for one partition, waited for it to finish, and only then moved on to the next one. On a table with many partitions this serialized all the work and only ever showed a single merge in `system.merges`. Now the per-partition merges are assigned and executed in parallel, so all partitions are merged at once (bounded by the configured background merge concurrency, `background_pool_size` * `background_merges_mutations_concurrency_ratio`). This mirrors how `StorageReplicatedMergeTree::optimize` already assigns a merge per partition and then waits for all of them. Tables inside an explicit transaction keep the sequential path, because parallel merges would otherwise share a single transaction object that is not made for concurrent use. The wait for already-running merges inside `selectPartsToMerge` (the `OPTIMIZE FINAL` path) is now scoped to the current partition: merges in other partitions cannot prevent selecting all parts of this one, and waiting for them would needlessly serialize the parallel assignment. Closes: #46770 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [e8fb928] Summary: ✅
AI ReviewSummaryThis PR parallelizes non-transactional Findings
Final Verdict
LLVM Coverage ReportMeasured on commit e8fb928.
Changed lines: Changed C/C++ lines covered: 254/281 (90.39%) · Uncovered code |
…ty, add concurrency test Bound the parallel `OPTIMIZE FINAL` degree by the currently free capacity of the background merge pool instead of always using its full size: read the same `BackgroundMergesAndMutationsPoolTask` counter that background merge selection consults, so a foreground `OPTIMIZE FINAL` does not start more merges than the operator's configured merge concurrency (`background_pool_size` * `background_merges_mutations_concurrency_ratio`). The counter is only read, not incremented, because `getMaxSourcePartsBytesForMerge` treats a value above `getMaxTasksCount` as a logical error. Add `04490_optimize_final_partitions_merge_concurrently`, which deterministically proves the issue's contract: it holds merges in flight with the `merge_task_projection_stage_pause` failpoint and asserts that more than one partition merge is present in `system.merges` at the same time (the old sequential implementation could only ever show one). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Sampling the free merge capacity from `BackgroundMergesAndMutationsPoolTask` did not actually reserve it: two concurrent `OPTIMIZE FINAL` queries could observe the same free slots and each start that many foreground merges, and background merge selection still did not see these local merges at all. Now the slots are reserved atomically in that same counter before any merge is assigned, and the reservation is held for the whole query and released at the end. The reservation is clamped to the free capacity, so the counter never exceeds `getMaxTasksCount()` (which `getMaxSourcePartsBytesForMerge` treats as a logical error) and concurrent OPTIMIZE FINAL queries and background merge selection all account for these merges through the same metric. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…same-partition ones Scoping the OPTIMIZE FINAL retry-wait to merges of the current partition was too narrow: `selectAllPartsToMergeWithinPartition` can also fail on a shared resource, e.g. the free-space check, when a concurrently assigned merge for another partition has reserved disk space through `CurrentlyMergingPartsTagger`. Such a failure would have returned `Cannot OPTIMIZE` (or thrown with `optimize_throw_if_noop`) instead of waiting for that merge to finish and free the space, as the sequential path did. Wait while any merge is active again (a running merge frees both source parts and reserved space), but keep skipping the wait when there is simply nothing to merge in the partition (e.g. `optimize_skip_merged_partitions`), which was the case that would otherwise needlessly hold a pool slot during a parallel OPTIMIZE FINAL. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous reservation CAS'd `BackgroundMergesAndMutationsPoolTask` from outside the executor. That still raced with `MergeTreeBackgroundExecutor::trySchedule`, which checks the same metric and increments it (when constructing `TaskRuntimeData`) under the executor mutex: the external CAS could slip between `trySchedule`'s check and its increment and push the counter to `max_tasks + 1`, which `getMaxSourcePartsBytesForMerge` reports as a logical error. Add `tryReserveTaskSlots` / `releaseTaskSlots` to `MergeTreeBackgroundExecutor`, which reserve free slots under the same lock and in the same metric as `trySchedule`, and use them from `OPTIMIZE FINAL`. The reservation is now atomic with scheduling, so the counter never exceeds the configured maximum and concurrent OPTIMIZE FINAL queries and the background pool all account for these merges. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`getMaxTasksCount()` is the task-slot budget (`background_pool_size` * `background_merges_mutations_concurrency_ratio`), which is larger than the number of worker threads because scheduled executor tasks can be postponed. OPTIMIZE FINAL merges run synchronously on real threads and cannot be postponed, so sizing the local pool from the task-slot count could start up to `ratio` times more merge threads than the pool has workers. Request at most `getMaxThreads()` (`background_pool_size`) slots from the executor reservation instead. The reservation is still clamped to the free task capacity, so a single OPTIMIZE FINAL never runs more concurrent merges than the pool has worker threads and still backs off while the pool is busy. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Regression for the fix in the previous commit: `OPTIMIZE TABLE ... FINAL` on a non-replicated `MergeTree` assigns one merge per partition and runs them synchronously on real threads, so the foreground parallelism must stay within the merge worker budget (`background_pool_size`), not the larger task-slot count (`background_pool_size` * `background_merges_mutations_concurrency_ratio`). `04491_optimize_final_bounded_by_worker_threads` creates a table with more partitions than worker threads, holds every merge at the projection stage with the `merge_task_projection_stage_pause` failpoint, and asserts that at most `background_pool_size` partition merges are in flight at once. Background merges are kept out of the picture with `max_bytes_to_merge_at_max_space_in_pool = 1` (`OPTIMIZE ... FINAL` merges regardless of size, background merges do not), so the only merges observed are the ones the query assigns. A build that sized the local pool from the task-slot count would show up to `background_pool_size` * `background_merges_mutations_concurrency_ratio` merges here. This is the focused regression requested in the AI review. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address review: the concurrency test counted every merge for the table in `system.merges`, but the `merge_task_projection_stage_pause` failpoint also pauses ordinary background merges, so a background merge for another partition could make the "more than one merge in flight" assertion pass even without `OPTIMIZE ... FINAL` assigning merges for multiple partitions at once. Create the table with `max_bytes_to_merge_at_max_space_in_pool = 1` (and `min_age_to_force_merge_seconds = 0`) so ordinary background merges never select these parts, while `OPTIMIZE ... FINAL` still merges every part of a partition through the whole-partition path regardless of size. Now the only merges the test observes are the ones the query assigns. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Requesting min(partitions, getMaxThreads) at the call site was not enough: the reservation was still clamped against the free task-slot count, so when the pool already had `background_pool_size` merges running (and `ratio - 1` times as many task slots still free) a foreground OPTIMIZE FINAL could reserve another `background_pool_size` slots and run up to `ratio` times more merge threads than the pool has workers. Clamp the reservation inside `tryReserveTaskSlots` by the worker-thread count, so the accounted merges (executor tasks plus foreground OPTIMIZE FINAL) never exceed `background_pool_size` regardless of how the free capacity is split between running and postponable work. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there. no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
ThreadPoolCallbackRunnerLocal requires callbacks not to reference stack locals: if enqueueAndKeepTrack throws after a task was scheduled but before it is tracked, stack unwinding can start before the runner waits, so an already-running task must not read the unwinding frame. The per-partition task captured partition_ids and the optimize_partition lambda (which itself captured the merge inputs by reference), so capture the partition id and merge inputs by value instead, keeping the task self-contained. `this` (the storage) and the shared results vector outlive any task. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`04491_optimize_final_bounded_by_worker_threads` exceeds the per-test time limit (>180s) in the slow-build + object-storage configuration: it creates one part per partition per INSERT across `background_pool_size * 2 + 2` partitions, each part carrying a projection, and writing all of those parts on object storage under a sanitizer build is slow (the test already takes ~100s even when it passes, so it flakes over the 180s limit). The public `amd_asan_ubsan, flaky check` (local storage) passes; only the private `CH Inc sync` `amd_asan_ubsan, flaky check, s3 storage, meta in keeper` job hits the limit (196s at run 59/100). The property under test - that `OPTIMIZE TABLE ... FINAL` bounds the number of concurrent partition merges by the worker budget - is independent of the storage backend, so adding `no-object-storage-with-slow-build` skips only this slow combination and loses no coverage. CI report: ClickHouse/clickhouse-private#62824 (sync of #109004) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…r 04491 The previous commit tagged `04491_optimize_final_bounded_by_worker_threads` with `no-object-storage-with-slow-build`, but that does not skip the `amd_asan_ubsan` job that was timing out: sanitizer builds are configured with `-DCMAKE_BUILD_TYPE=None`, which `CMakeLists.txt` resets to `RelWithDebInfo`, so `system.build_options` reports `BUILD_TYPE = RelWithDebInfo` and `clickhouse-test` adds `BuildFlags.RELEASE` to the build flags. The `no-object-storage-with-slow-build` skip only fires when `RELEASE` is absent (effectively `Debug` builds), so it never applied to the failing `amd_asan_ubsan, s3 storage` flaky check. Switch to the plain `no-object-storage` tag, which skips whenever S3 or Azure object storage is used regardless of the build type. The test still runs on local storage in every build (including the public `amd_asan_ubsan, flaky check` and the coverage jobs), so the merge-concurrency property stays covered. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
The sole CI red on the current head ( The stack is entirely in the correlated-subquery decorrelation path ( It is a chronic master-wide flake, not a regression: over the last 60 days it fired on
The rest of CI is green or still in progress; a re-run of the stress job should clear it once the workflow finishes. |
The `Stateless tests (amd_asan_ubsan, flaky check, s3 storage)` job in the private sync `clickhouse-private#62824` failed because `04489_optimize_final_all_partitions_at_once` intermittently exceeded the 180s per-test limit on object storage (up to ~200s across 4 of 50 flaky-check runs), while every run on local storage passes. The test creates 16 partitions with several parts each (16 partitions x 3 inserts) and then lets `OPTIMIZE FINAL` merge every partition into a single part; writing all of those parts and the merge results to object storage is slow, and under a sanitizer build with randomized settings it occasionally pushes the test past the per-test time limit. The property under test - that `OPTIMIZE FINAL` merges every partition into a single part - does not depend on the storage backend, so add the `no-object-storage` tag, matching the earlier fix for `04491_optimize_final_bounded_by_worker_threads`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The reservation was taken for every partition candidate and held for the whole query, so on a table where most partitions are already merged (or with `optimize_skip_merged_partitions`) the slots reserved for the no-op partitions stayed charged in `BackgroundMergesAndMutationsPoolTask` for the lifetime of the few real merges, needlessly throttling background merges and skewing `getMaxSourcePartsBytesForMerge`. Track the still-reserved count and, as each partition task finishes, release the slots beyond the number of partitions still to process, so the reservation follows the actual remaining work down to the merges that are really running. Verified: on 8 partitions with 6 no-ops and 2 (paused) real merges, the metric settles at 2 instead of staying at the reserved 8. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
The only non-green check on the current head ( The sync run stalled on infrastructure, not on a real test regression:
This PR only touches I cancelled the stalled sync run and re-ran the two affected jobs; the rest of public CI (including all |
… tests The `04417_part_loading_tree_rollback_evict_reinsert_contains` and `04500_part_loading_tree_rollback_tmp_metadata` tests fabricate part directories out-of-band while the table is `DETACH`-ed, exactly like their siblings already fixed in this PR, and hit the same corruption under stress-test restarts: a stress run of #109004 failed with `Part all_5_6_1_0 intersects previous part all_1_5_4_1 and the transaction metadata of at least one of them could not be read` while loading `t_plt_evict_reinsert` at startup, failing the run with "Cannot start clickhouse-server". Use `DETACH TABLE ... PERMANENTLY` in these two tests as well. Example report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109004&sha=e26111dca401681dbc6b4ba4a9c42b6fe23a4a36&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29 Related: #109004 Co-Authored-By: Claude Fable 5 <[email protected]>
…sk churn The flaky check failed `05023_optimize_final_respects_free_slots` in every build flavor: a foreground `OPTIMIZE` could wait in `reserveTaskSlots` for minutes. The reservation bound (`min(max_tasks_count, threads_count)`) was checked against the shared task metric, which also counts in-flight background tasks (pending and active). Background `trySchedule` admits tasks up to the larger `max_tasks_count`, so on a busy server the steady churn of system-table merges kept the metric at or above the foreground bound indefinitely, starving every foreground reservation. The CI metric log shows `BackgroundMergesAndMutationsPoolTask` pinned in the 16-21 range for the whole five-minute window while a blocked `OPTIMIZE` waited for a slot. Now the worker-thread bound is checked against other reservations only, while the shared metric still caps the total number of in-flight tasks (reservations included) by `max_tasks_count`, the same invariant that `trySchedule` maintains. Failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109004&sha=e7cf724b9f923de9c90729dfa1b2ffa42f1f0256&name_0=PR PR: #109004 Co-Authored-By: Claude Fable 5 <[email protected]>
…iscarded When `tryReserveTaskSlots` returns zero, `StorageMergeTree::merge` discards the selected merge and retries after a slot becomes available. If the discarded selection was a `TTLDelete` or `TTLRecompress` merge, the `bookMergeWithTTL` booking taken during selection stayed behind, leaking one unit of `max_number_of_merges_with_ttl_in_pool` capacity even though no TTL merge ran. Give the booking back on the discard path; a retried selection books again if it picks a TTL merge once more. PR: #109004 Co-Authored-By: Claude Fable 5 <[email protected]>
`04907`, `04909`, `04910` and `04911` compared `BackgroundMergesAndMutationsPoolTask` against a baseline taken before the `OPTIMIZE` query, plus the growth of the total number of merges in flight. The baseline also counted unrelated background tasks (e.g. merges of system tables) that were already gone by the time the check ran, which made the threshold unreachable: the polling loop then span until the test was killed for running longer than 180 seconds - as happened in the flaky check for `04909`, where the paused merge sat in the projection stage for 164 seconds while the loop never accepted it. Take the two merge counts and the metric in a single snapshot instead, and require the metric to account for every merge in flight - the same shape that `04631` already uses. The loop now issues one query per iteration instead of three, is bounded by a wall-clock deadline so that it reports `no` instead of hitting the harness time limit, and the paused `OPTIMIZE` gets a receive timeout above the default.
…election A table-wide `OPTIMIZE TABLE t` selects a merge before it reserves a merge-executor slot; when no slot is free it discards the selection, waits for a slot and retries. Selecting a `TTLDelete` or `TTLRecompress` merge also advances `next_delete_ttl_merge_times_by_partition` / `next_recompress_ttl_merge_times_by_partition` in `MergeTreeDataMergerMutator::updateTTLMergeTimes`, and the discard path did not undo that. A partially expired single part has no regular merge to fall back to, so slot contention could defer its TTL cleanup or recompression until `merge_with_ttl_timeout` / `merge_with_recompression_ttl_timeout` expired instead of running it as soon as a slot freed. `MergeTreeDataMergerMutator::rollbackTTLMergeTime` now restores the previous due time of the partition, and the discard path calls it next to `cancelMergeWithTTL`. The rollback is a compare-and-restore: it only reverts the value when it is still exactly the one the discarded selection installed, so a newer selection of the same partition is never overwritten and no TTL merge can be double-booked. Test `05055_optimize_ttl_merge_retries_after_slot_wait` occupies every executor slot with paused merges, makes a table-wide `OPTIMIZE` pick the single-part `TTLDelete` merge of another table, and checks that the expired row is gone once a slot frees.
The first version of `05055` could be satisfied by a background merge: a background selection of the same partition performs the TTL rewrite once the executor slots free, which hides a leaked postponement. Park background merge selection with `mt_merge_selecting_task_pause_when_scheduled` while the foreground `OPTIMIZE` waits for a slot, so the expired row can only disappear if the retried foreground selection picks the TTL merge again. Verified locally against a server built from this branch: the `OPTIMIZE` query thread selects `Merge #0 type TTLDelete`, gives it up, and selects it again 2.2 seconds later - which `merge_with_ttl_timeout = 10000` makes impossible unless the postponement was rolled back.
… tests The `04417_part_loading_tree_rollback_evict_reinsert_contains` and `04500_part_loading_tree_rollback_tmp_metadata` tests fabricate part directories out-of-band while the table is `DETACH`-ed, exactly like their siblings already fixed in this PR, and hit the same corruption under stress-test restarts: a stress run of ClickHouse#109004 failed with `Part all_5_6_1_0 intersects previous part all_1_5_4_1 and the transaction metadata of at least one of them could not be read` while loading `t_plt_evict_reinsert` at startup, failing the run with "Cannot start clickhouse-server". Use `DETACH TABLE ... PERMANENTLY` in these two tests as well. Example report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109004&sha=e26111dca401681dbc6b4ba4a9c42b6fe23a4a36&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29 Related: ClickHouse#109004 Co-Authored-By: Claude Fable 5 <[email protected]>
`Build (arm_tidy)` failed with `constructor does not initialize these fields: installed` (`cppcoreguidelines-pro-type-member-init`) on the struct that records the last TTL merge due time advance of a partition. CI report: https://github.com/ClickHouse/ClickHouse/actions/runs/34184694476/job/101930977315 PR: #109004 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ailure of a selected merge `MergeTreeDataMergerMutator::selectPartsToMerge` postpones the next TTL merge of a partition by `merge_with_ttl_timeout` / `merge_with_recompression_ttl_timeout` as soon as it selects a `TTLDelete` / `TTLRecompress` merge, before the future part is constructed and the parts are tagged and the disk space reserved. `rollbackTTLMergeTime` was only called on the executor slot discard path of `StorageMergeTree::merge`, so a selected TTL merge that died on one of those earlier paths - or that the background assignee could not schedule - left the partition postponed although no TTL merge ran. The postponement map is shared with background selection, and a partially expired single part has no regular merge to fall back to. Now `StorageMergeTree::selectPartsToMerge` remembers the selected partition and merge type of a table-wide selection and rolls the due time back whenever constructing the future part or the `MergeMutateSelectedEntry` fails or throws, and `scheduleDataProcessingJob` does the same next to `cancelMergeWithTTL` when the task could not be scheduled. New failpoint `mt_fail_selected_merge_before_start_once` fails a selected merge right where the parts are tagged; test `05218_optimize_ttl_merge_retries_after_failed_start` checks that the next `OPTIMIZE` selects the TTL merge again and drops the expired row (background merge selection is parked so that only the foreground `OPTIMIZE` can perform the rewrite). Co-Authored-By: Claude Fable 5.1 <[email protected]>
A test whose file name contains `fail` makes every log scanner that greps for a failure report it, so the style check rejects such a name. The merge here is aborted before it starts, which the new name says. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…llel-partitions # Conflicts: # src/Storages/StorageMergeTree.cpp
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109004&sha=e6f7b6754810d0a7da1ce28d1fcda2322a7d6fd1&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%202%2F6%29 (TSan The branch has been merged with the latest |
|
Investigated. No new PR from me: the fix is already on master and it is your own #120202. Fix-presence probe on the build that failed. The job started 2026-09-18 22:50:21Z and the tree it built pins
This PR's current head Breadth for One neighbour is still live on the post-fix pin and has its own fix in progress: |
Closes: #46770
For a non-replicated
MergeTreetable,OPTIMIZE TABLE ... FINALwithout an explicit partition used to process partitions one by one: it selected and ran the merge for one partition, waited for it to finish, and only then moved on to the next one. On a table with many partitions this serialized all the work and only ever showed a single merge insystem.merges.Now the per-partition merges are assigned and executed in parallel, so all partitions are merged at once. The degree of parallelism is bounded by the configured
background_pool_sizeand reserves only currently available merge-executor capacity. This mirrors howStorageReplicatedMergeTree::optimizealready assigns a merge per partition and then waits for all of them.Notes:
selectPartsToMerge(theOPTIMIZE FINALpath) is now scoped to the current partition: merges in other partitions cannot prevent selecting all the parts of this one, and waiting for them would needlessly serialize the parallel assignment.Verified on a local build: on a table with 8 partitions,
OPTIMIZE TABLE ... FINALnow runs 8 merges concurrently (observed viasystem.merges) instead of one at a time, and every partition is still correctly merged into a single part (checked forMergeTree,OPTIMIZE ... FINAL DEDUPLICATE, andReplacingMergeTree, plus theoptimize_skip_merged_partitions/optimize_throw_if_noopno-op paths and two concurrentOPTIMIZE FINALqueries).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
OPTIMIZE TABLE ... FINALon a non-replicatedMergeTreetable now assigns and runs the merges for all partitions at once instead of processing them one partition at a time.Workflow [PR]
Sync PR [sync-upstream/pr/109004]
Version info
26.10.1.776-master(included in26.10and later)