Skip to content

Assign merges for all partitions at once for OPTIMIZE FINAL - #109004

Merged
alexey-milovidov merged 75 commits into
masterfrom
optimize-final-parallel-partitions
Sep 26, 2026
Merged

alexey-milovidov merged 75 commits into
masterfrom
optimize-final-parallel-partitions

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 30, 2026 •

Copy link
Copy Markdown
Member

Closes: #46770

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. The degree of parallelism is bounded by the configured background_pool_size and reserves only currently available merge-executor capacity. This mirrors how StorageReplicatedMergeTree::optimize already assigns a merge per partition and then waits for all of them.

Notes:

  • 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 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 ... FINAL now runs 8 merges concurrently (observed via system.merges) instead of one at a time, and every partition is still correctly merged into a single part (checked for MergeTree, OPTIMIZE ... FINAL DEDUPLICATE, and ReplacingMergeTree, plus the optimize_skip_merged_partitions / optimize_throw_if_noop no-op paths and two concurrent OPTIMIZE FINAL queries).

Changelog category (leave one):

  • Performance Improvement

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

OPTIMIZE TABLE ... FINAL on a non-replicated MergeTree table 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

  • Merged into: 26.10.1.776-master (included in 26.10 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e8fb928]

Summary: ✅


AI Review

Summary

This PR parallelizes non-transactional OPTIMIZE TABLE ... FINAL across partitions for non-replicated MergeTree, adds explicit merge-slot reservation for foreground OPTIMIZE paths, and hardens the TTL rollback paths when a selected merge is discarded before it starts. The retry/rollback work is much stronger now, but one material contract violation remains: the new reservation logic still lets foreground OPTIMIZE FINAL run on top of already-busy background merge workers, so the total merge concurrency can exceed the operator’s configured background_pool_size.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Assign merges for all partitions at once for OPTIMIZE FINAL #109004#discussion_r3503675769] [src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp:231-245, src/Storages/StorageMergeTree.cpp:2948-2994] The new foreground reservation path only checks the worker-thread budget against reserved_task_slots, while trySchedule still admits background work as long as the shared task metric stays below max_tasks_count. With background_pool_size = 16 and the default concurrency ratio 2, a server that already has 16 executor merge workers running still grants 16 foreground reservations because reserved_task_slots == 0 and BackgroundMergesAndMutationsPoolTask == 16 < 32; OPTIMIZE FINAL then starts 16 synchronous merge threads of its own. That breaks the PR’s stated contract that it “reserves only currently available merge-executor capacity” and can double the merge CPU/disk parallelism exactly when the background pool is already saturated. Suggested fix: share a real worker-permit counter between trySchedule and tryReserveTaskSlots (or run the foreground merges through the executor) so both paths consume the same worker budget instead of only the same task-slot metric.
Final Verdict

⚠️ Needs changes before merge: foreground OPTIMIZE FINAL still oversubscribes total merge worker capacity when background merges are already using the pool.

LLVM Coverage Report

Measured on commit e8fb928.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.40% -0.10%

Changed lines: Changed C/C++ lines covered: 254/281 (90.39%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 30, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 2 commits July 1, 2026 00:43
…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]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 2 commits July 1, 2026 02:11
…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]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 4 commits July 1, 2026 04:00
`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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

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
  • StressHouse run: fe4d9eae-c8e8-4aef-aac4-ef84e28fd250
  • MIRAI run: ace15153-a289-4828-b529-51e8ea9e0149
  • PR check IDs:
    • clickbench_1785966_1790343776
    • clickbench_1785972_1790343776
    • clickbench_1785978_1790343776
    • tpch_adapted_1_official_1785990_1790343776
    • tpch_adapted_1_official_1786002_1790343776
    • tpch_adapted_1_official_1786036_1790343777

Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 3 commits July 1, 2026 06:18
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The sole CI red on the current head (48d23ad1) is the Stress test (arm_debug) AST-fuzzer flake Logical error: Unexpected return type from A. Expected B. Got C (STID: 3262-40aa).

The stack is entirely in the correlated-subquery decorrelation path (executeASTFuzzerQueries → buildQueryPlanForCorrelatedSubquery → decorrelateQueryPlan → ExpressionStep::updateOutputHeader → ActionsDAG::updateHeader). This PR touches only StorageMergeTree.cpp (OPTIMIZE FINAL merge assignment) and nothing in the planner/decorrelation path, so it cannot be the cause.

It is a chronic master-wide flake, not a regression: over the last 60 days it fired on pull_request_number = 0 (master) on multiple days and across ~20 unrelated PRs. Tracked by open issues:

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]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The only non-green check on the current head (8e3e1dba) is CH Inc sync, and its failure is unrelated to this PR.

The sync run stalled on infrastructure, not on a real test regression:

  • One Stateless tests (amd_asan_ubsan, distributed cache, …, 1/2) shard hung in its Run step for ~6 hours (the runner died and never reported completion), which kept the whole run in_progress.
  • One integration test flaked: test_refreshable_mv_no_multi_read/test.py::test_refreshable_mv_attach_without_multi_read failed with AssertionError: 'Disabled' in 'Running'. This is a known async race — the test's own comment notes that ATTACH schedules the graceful-stop pass asynchronously, so the status read can observe the transient Running/Scheduling state before doScheduling reaches Disabled — and the run additionally logged Failed connecting to Zookeeper within the connection retry policy. The same test flaked on unrelated PR Stop refreshable MV gracefully when the Keeper feature-flag check races on attach #108890.

This PR only touches StorageMergeTree.cpp, MergeTreeBackgroundExecutor.{cpp,h}, CurrentMetrics.cpp, and the new 04489/04490/04491 tests — nothing in the refreshable-MV or Keeper multi-read path, so neither failure can be caused by it.

I cancelled the stalled sync run and re-ran the two affected jobs; the rest of public CI (including all Performance Comparison shards) is green.

alexey-milovidov added a commit that referenced this pull request Jul 20, 2026
… 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]>
alexey-milovidov and others added 6 commits August 30, 2026 20:12
…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.
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… 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]>
alexey-milovidov and others added 5 commits September 16, 2026 13:08
`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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 data race in natsLibuv_Attach, contrib/nats-io/src/adapters/libuv.h:400, failing the whole test_storage_nats/test_nats_jet_stream.py module in nats_setup_teardown) and provide a fix in a separate PR. If the fix is already in progress, link it here. This PR only changes OPTIMIZE ... FINAL merge scheduling in StorageMergeTree. The Build profile diff red is a CI-logs cluster query failure in the job script itself.

The branch has been merged with the latest master (one trivial include conflict in StorageMergeTree.cpp), new head e8fb928ca78b. The remaining AI-review Major (foreground reservations vs. busy background workers) is the author-dismissed design point from #109004 (comment) and is unchanged.

@groeneai

Copy link
Copy Markdown
Collaborator

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 contrib/nats-io at 3e3a3f10, where src/adapters/libuv.h:400 is the racing write itself:

398    if (s == NATS_OK)
399    {
400        nle->socket = socket;
401        nle->events = UV_READABLE;

natsLibuv_Attach writes nle from the calling thread while the loop thread reads it. #120202 moved the pin 3e3a3f10 -> b88704df, which brings in ClickHouse/nats.c@37532c32 ("libuv adapter: do not let an attach overtake a queued poll removal"): the socket now travels inside the queued event and natsLibuv_Attach writes no nle field at all. #120202 merged 2026-09-21T20:20:24Z, 2 days 21 hours after that job ran, so the fix could not have been in it.

This PR's current head e8fb928c already pins b88704df, so the CI now running on it is the post-fix measurement.

Breadth for test_storage_nats/test_nats_jet_stream.py, 30 days of CIDB split at the pin bump: 1250 reds / 74 distinct PRs / 66 true-master rows before it, and 2 reds / 2 PRs after it, both on Integration tests (arm_binary, distributed plan, 1/4), no sanitizer and no module wipe. No TSan red on that module since the bump.

One neighbour is still live on the post-fix pin and has its own fix in progress: test_storage_nats/test_nats_core.py wipes in full (latest #122000, amd_msan, 4/8, 2026-09-24). Its fix is ClickHouse/nats.c#11 (open).

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Acceptable.

@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov alexey-milovidov removed the submodule changed At least one submodule changed in this PR. label Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into master with commit d176065 Sep 26, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the optimize-final-parallel-partitions branch September 26, 2026 23:16
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Oct 27, 2026
@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 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... pr-performance Pull request with some performance 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.

When I do OPTIMIZE FINAL for non-Replicated table, it should assign merges for all partitions at once.

3 participants