Skip to content

Make the wait of OPTIMIZE ... FINAL for running merges of a MergeTree cancellable - #129875

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/optimize-final-wait-for-merges-cancellable
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/optimize-final-wait-for-merges-cancellable

Conversation

@groeneai

@groeneai groeneai commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #127482
Related: #129283
Fixes: #6093

Changelog category (leave one):

  • Improvement

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

KILL QUERY, max_execution_time and server shutdown now stop an OPTIMIZE ... FINAL of a MergeTree table that waits for currently running merges, instead of letting it wait up to lock_acquire_timeout_for_background_operations per finished merge.

Description

Failing job: La Casa Del Dolor (amd_debug) / Server shutdown on #127482 (report). The server was force-killed 30 s after SIGTERM: the main thread was joining DDLWorker, and the DDL worker ran an OPTIMIZE TABLE ... FINAL parked in StorageMergeTree::selectPartsToMerge, waiting for running merges.

That wait (currently_processing_in_background_condition, up to lock_acquire_timeout_for_background_operations, 120 s by default, re-armed after every finished merge) and the memory poll before it never look at the query status, and nothing notifies the condition when a query is killed. Shutdown kills all queries before it joins the DDL worker but cancels merges only after it, so the join blocks.

Both waits now run in slices of at most 1 s and call QueryStatus::checkTimeLimit(OverflowMode::THROW) before each slice and when the wait ends, so a query cancelled just before the awaited merge finishes does not go on to run its own merge. #129283 sliced the ReplicatedMergeTree wait the same way. The total wait and the error on timeout are unchanged. An OPTIMIZE FINAL that waits for merges now fails when its max_execution_time passes, also with timeout_overflow_mode = 'break'.

Validation: the new test pauses a mutation with mt_mutate_task_pause_in_prepare. Before the fix, KILL QUERY and max_execution_time = 2 were ignored and every case ended after 30 s with CANNOT_ASSIGN_OPTIMIZE; after it they end in 1-2 s with codes 394 and 159. The test also checks that a KILL sent together with the release of the mutation stops the OPTIMIZE before it merges the partition, and that without a cancellation the waiting OPTIMIZE merges as soon as the mutation finishes. Locally, ON CLUSTER + SIGTERM shut down in 1.2 s instead of hanging. The test passed 50/50 randomized runs and 20/20 without randomization.


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

groeneai and others added 4 commits November 6, 2026 22:03
…cellable

`StorageMergeTree::selectPartsToMerge` (lambda `select_in_partition`) waits on
`currently_processing_in_background_condition` for up to
`lock_acquire_timeout_for_background_operations` (120 s by default) whenever an
`OPTIMIZE ... FINAL` cannot select its partition while merges are running, and
re-arms the wait after every finished merge; the memory poll before it sleeps
in 1 s steps for up to the same timeout. Neither looked at the query status,
and nothing notifies the condition when a query is killed, so `KILL QUERY`,
`max_execution_time` and the `killAllQueries` of server shutdown were ignored.

At shutdown, queries are killed before the DDL worker is joined, but merges are
cancelled only after it, so a DDL worker running such an OPTIMIZE blocked the
shutdown. Seen in `La Casa Del Dolor (amd_debug)` / `Server shutdown` on
ClickHouse#127482, where the harness force-killed the server after 30 s.

Both waits now run in slices of at most 1 s and call
`QueryStatus::checkTimeLimit(OverflowMode::THROW)` before each slice, as ClickHouse#129283
did for `StorageReplicatedMergeTree::waitForProcessingQueue`. The THROW mode
makes `timeout_overflow_mode = 'break'` stop the wait too. The total wait, the
re-selection after a notification and the timeout error are unchanged.

The new test pauses a mutation with `mt_mutate_task_pause_in_prepare` and checks
`KILL QUERY` and `max_execution_time` (throw and break, explicit partition and
whole table with parallel helpers). The second partition's part is inserted
after the mutation, so it gets no mutation task of its own: the failpoint pauses
only once, and a clone task of that part would otherwise race for it.

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

The sliced wait re-selected only when `wait_for` returned `no_timeout`. libc++
derives that result from the clock after re-acquiring the mutex, so a merge that
finalized around a slice deadline was reported as a timeout and its notification
was lost. If it was the last running merge, nothing notified again and the
OPTIMIZE waited out the rest of `lock_acquire_timeout_for_background_operations`.

`CurrentlyMergingPartsTagger::finalize` now increments a counter under the mutex
before `notify_all`, and each slice waits with a predicate on that counter, so a
finished merge is observed at the latest when its slice ends.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The status was checked only before each slice of the wait, so a wait could end
on a merge that finished after the query was killed. The re-selection then
succeeded and `merge` ran the new merge under the background context, which
never looks at the query; the kill was reported only after the merge was done.
Both waits now check the status once more when they end.

The test covers a `KILL` sent together with the release of the awaited mutation
and the success path of a waiting `OPTIMIZE FINAL`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e waits end promptly

Case 4's Code: 394 is also raised after a merge, by the killed-query check that
executeQuery runs once the interpreter returns, so the case now checks that the
part of partition 0 keeps level 0. Cases 4 and 5 release the mutation only after
the OPTIMIZE logged that it waits for it, so they exercise the wait itself. The
query_log duration bound on cases 2 and 3 catches a wait that is not sliced and
ends only at lock_acquire_timeout_for_background_operations.

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

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review
  • ❌ Fixed in a follow-up round: the 1 s sliced wait did not re-check for a finished merge after a slice that reported a timeout, so a merge finishing at a slice boundary could be missed until the full lock_acquire_timeout_for_background_operations. The wait now uses the predicate overload on a counter bumped when parts stop being merged.
  • ❌ Fixed in a follow-up round: the query status was checked only before each slice, so a KILL that landed in the slice where the awaited merge finished was skipped and the OPTIMIZE went on to run its merge. Both waits now check the status once more when they end.
  • ⚠️ Fixed in a follow-up round: the kill-with-release case only checked for Code: 394, which the killed-query check in executeQuery also raises after a merge; it now checks that the part was not merged, after waiting until the OPTIMIZE is in the wait.
  • ⚠️ Fixed in a follow-up round: nothing checked that the cancelled waits end promptly; the max_execution_time cases now assert they end well before the 30 s lock timeout.
  • ⚠️ Fixed in a follow-up round: the success case could release the mutation before the OPTIMIZE waited and checked only the exit code; it now waits for the wait to start and checks that the part was merged.
  • 💡 Not changed: case 4 relies on the released one-row mutation finishing within the 1 s slice in which the KILL landed; a build without the check after the wait fails it 10/10 locally, and a deterministic version would need a test-only failpoint inside the wait, so I did not add one.
  • 💡 CurrentThread::checkIfNotCancelled() would be shorter but does not stop the wait with timeout_overflow_mode = 'break'; kept checkTimeLimit(OverflowMode::THROW) as in Make SYSTEM SYNC REPLICA and OPTIMIZE of ReplicatedMergeTree cancellable while they wait for the replication queue #129283.

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Failpoint mt_mutate_task_pause_in_prepare holds a mutation of partition 0, then OPTIMIZE ... FINAL waits for it; no randomness involved. The new test fails on every run before the fix.
b Root cause explained? select_in_partition waits on currently_processing_in_background_condition (and polls background memory) without looking at the query status, and nothing notifies the condition on KILL QUERY. Shutdown kills queries before joining the DDL worker but cancels merges after it, so the join blocks.
c Fix matches root cause? Yes. The two waits now run in 1 s slices with checkTimeLimit(OverflowMode::THROW) before each slice and once more when the wait ends, so a query killed just before the awaited merge finishes does not go on to run its own merge; each slice of the merge wait waits with a predicate on a finished-merge counter, so a merge that ends at a slice boundary is not missed. No timeout change, no shutdown reordering.
d Test intent preserved / new tests added? New test 05565_merge_tree_optimize_final_wait_cancellable.sh: KILL QUERY, max_execution_time throw (whole table, parallel helpers), max_execution_time break, a query_log bound that both timeouts ended before 20 s, a check that the mutation was still pending, a KILL sent together with the release of the mutation (the partition's part must keep level 0, i.e. no merge ran), and the success path (the part reaches level 1). Cases 4 and 5 release the mutation only after the OPTIMIZE logged that it waits for it. No existing test changed.
e Both directions demonstrated? Before: each case ended after 30 s with CANNOT_ASSIGN_OPTIMIZE and the killed OPTIMIZE of case 4 still merged (test FAIL). After: 1.0 s (394), 2.0 s (159), 2.0 s (159), case-4 part level 0 (test OK, 90/90 runs). The previous round's binary, which lacked the check after the wait, fails the level line 10/10; a build whose wait is not sliced fails only the duration line. ON CLUSTER + SIGTERM: shutdown blocked over 90 s before, 1.2 s after.
f Fix is general across code paths? Both waits of the lambda are fixed. ReplicatedMergeTree has the same fix (#129283). waitForMutation and MergeTreeBackgroundExecutor::reserveTaskSlots already check cancellation. Background merge selection never enters this lambda.
g Fix generalizes across inputs (params/datatypes/wrappers)? Explicit partition and whole table (parallel helpers carry the query thread group); KILL, throw and break; timeout = 0 still fails without blocking; no query context means no check. Column types do not affect merge selection.
h Backward compatible? (maintainer-approved exception only) No setting or format change. A waiting OPTIMIZE FINAL now honours max_execution_time, as in ReplicatedMergeTree since #129283.
i Invariants and contracts preserved? The mutex is released only inside wait_for, as before, and the finished-merge counter is read and incremented under it; a throw (before a slice or after the wait) unwinds through merge, which holds no slot during the wait and has no future part yet. timeout is only subtracted from, so no chrono overflow.

Session id: cron:clickhouse-impl-slot-41:20261107-002700

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @azat, could you review this and add the can be tested label so CI runs? An OPTIMIZE ... FINAL of a MergeTree run by the DDL worker waited for running merges without checking the query status, so DDLWorker::shutdown blocked and La Casa Del Dolor force-killed the server; the wait now runs in 1 s slices with checkTimeLimit, as #129283 did for ReplicatedMergeTree.

@clickhouse-gh

clickhouse-gh Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [22fb30a]

Summary: ✅


AI Review

Summary

The PR makes the memory-pressure and running-merge waits of OPTIMIZE ... FINAL on MergeTree observe query cancellation and execution time limits, including cancellation when a wait ends. No new blocker or major findings. The existing stale-metadata race when concurrent schema changes occur during the merge wait is already tracked separately in #122704; the cancellation change does not introduce it.

Missing context / blind spots
  • ⚠️ No built server is available in this checkout, so the regression test was not rerun locally. Execution evidence comes from the author's documented before/after runs; the current CI index reports success, but its per-job reports did not expose the new test's result.
Final Verdict

Status: ✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 22fb30a2c with master 7c2e53a38 (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.68, programs/clickhouse-keeper ×0.68 (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.0 s 14.4 s +10.3 s (+254%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.7 s +5.3 s (+229%)
Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 842ab28

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 05457_dictionary_remote_clickhouse_invalidate_query not from this PR (it changes merge selection in StorageMergeTree, not dictionaries or this test): the test, added to master by #129336, hit the 60 s Fast test timeout; it timed out the same way in 12 other PRs and 2 merge-queue runs in the last 3 days #129879 (mine, open)
Mergeable Check, PR praktika rollups of the row above #129879 (the owner above)

No job was dropped. The only other CIDB FAIL rows on this head are Config Workflow / Pre Hooks of the run before the can be tested label.

Session id: cron:our-pr-ci-monitor:20261107-073005

Master's Style check (234b980) now requires every test that reads
system.text_log to have an event_time condition. Use the idiom master's
tests adopted: event_date >= yesterday() AND event_time >= now() - 600.
The polled message is logged by the OPTIMIZE a few seconds before the poll,
so the window cannot exclude it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 19, 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-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Misleading 'Timeout exceeded' for OPTIMIZE TABLE

1 participant