Repository navigation
Cancel in-flight merges and mutations on server shutdown - #115733
Conversation
`ContextSharedPart::shutdown` waits for the MergeTree background executors before `DatabaseCatalog::shutdown` (the reordering that fixed the SIGBUS in #85433), but nothing cancels the tasks that are already running: the executors' `wait` only prevents new steps from starting, and the per-storage `merges_blocker` cancellation happens later, in `DatabaseCatalog::shutdown`. A single slow step blocks shutdown for its whole duration. In the linked stress test run, a background merge of `t_lwu_key_prefix` (854090 rows in 5 parts plus 3 patch parts, from test 04509_lwu_sorting_key_common_prefix) spent ~37 seconds per 8192-row block inside `applyPatchesMergeOnKey` under MSan, and the first `pull` of the merge pipeline could not finish within the hung check timeout, so the check reported `Possible deadlock on shutdown (see gdb.log)`. Cancel all `MergeList` entries before waiting for the executors. Merge and mutate tasks check `MergeListElement::is_cancelled` on every block through `MergeProgressCallback` (the same mechanism the OOM canary uses), so a running merge aborts with the `ABORTED` exception within one block instead of running to completion; its result would have been discarded on restart anyway. Also add the `merge_tree_sequential_source_sleep_before_read` failpoint and an integration test that restarts the server in the middle of a slow 16-part merge. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=a013c79d6ac80373b820381527ea85823ab03834&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_msan%29&name_1=Stress%20test%20%28azure%2C%20amd_msan%29 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [39a740d] Summary: ✅
AI ReviewSummaryThis PR changes Tests
Final VerdictImplementation looks correct on the current head, but the regression coverage is still weaker than the final contract of the PR. I would add one focused fetch test for the pre-registration / first-read cancellation window before merging. LLVM Coverage ReportMeasured on commit 39a740d.
Changed lines: Changed C/C++ lines covered: 86/93 (92.47%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units339 translation units recompiled, 3220 s compile time in total, 339 of them have a recent master baseline. |
Address the review: `merge_list.cancelAll()` only cancelled tasks that had already inserted a `MergeListEntry`, so a merge or mutation scheduled between the cancellation and `MergeTreeBackgroundExecutor::wait` was invisible to it and could still block shutdown; a replicated merge could also spend its first step in `prepare` or fall through to `executeFetch` before any entry exists. - `MergeTreeBackgroundExecutor::requestShutdown` flips the executor into shutdown mode without joining the worker threads: new tasks are rejected and pending tasks are not started. `wait` implies it. - `ContextSharedPart::shutdown` now stops all four executors first, then cancels, then joins, so the set of running tasks cannot grow after the cancellation. - `MergeList::cancelAll` also cancels entries inserted later, so a task that is inside its first step and has not registered itself yet cannot escape. - In-flight fetches are cancelled the same way through the new `ReplicatedFetchList::cancelAll`, checked in `ReplicatedFetchReadCallback` on every buffer refill: a replicated merge falls back to a fetch inside the same task step, and a plain `GET_PART` fetch would block the `fetch_executor` join for the whole download otherwise. Before the executor reordering (issue #85433), `fetcher.blocker.cancelForever` in the per-storage shutdown used to cancel those fetches before anything waited on the executors. - Add `test_shutdown_cancels_running_fetch`: a 150 MB part is fetched from a sender throttled to 1 MiB/s, and the server must still stop within 90 seconds. Co-Authored-By: Claude Fable 5 <[email protected]>
The zero-copy fetch branch of \`fetchSelectedPart\` returned through \`downloadPartToDisk(..., true, ...)\` before creating a \`ReplicatedFetchList\` entry, so \`ReplicatedFetchList::cancelAll\` on server shutdown could not reach those fetches. Create the entry and install \`ReplicatedFetchReadCallback\` before branching on \`remote_fs_metadata\`, so both fetch modes share the cancellation path. The callback observes the cancellation between refills of the HTTP read buffer (\`ReadBufferFromIStream\` blocks until a whole buffer is received), so the buffer size of the fetch stream now honors \`max_read_buffer_size_remote_fs\` (the default is unchanged). Also add the \`replicated_sends_sleep_before_file_send\` failpoint (which flushes and then sleeps before each file the sender writes) and the \`test_shutdown_cancels_running_zero_copy_fetch\` integration test: a zero-copy fetch of a 20-column wide part from a sender sleeping 5 seconds per metadata file, with a 1 KiB read buffer on the receiver, must not delay the shutdown beyond 90 seconds.
… read The fetch was registered in the ReplicatedFetchList only after the part header (sizes, TTL infos, part type, UUID, projection count) had been read from the HTTP stream, so a sender stalled in that prefix could pin the fetch worker until the HTTP timeouts fired, keeping the shutdown timing-dependent. Install a next-callback right after the buffer is created that checks the new ReplicatedFetchList::isAllCancelled flag and aborts with ABORTED, and tighten the integration tests to assert the explicit "Fetching of part ... was cancelled" message instead of a generic fetch log line. Co-Authored-By: Claude Fable 5 <[email protected]>
…tion `fetchSelectedPart` created the HTTP buffer with `withDelayInit(false)`, and `ReadWriteBufferFromHTTP` performs the first blocking read directly in the constructor in that case - before `setNextCallback` could install the shutdown cancellation check. A sender stalled while filling the very first buffer would still pin the fetch worker until the HTTP timeouts fire. Use delayed initialization, install the cancellation callback, and only then trigger the request and the first read with an explicit `next` call: `nextImpl` runs `next_callback` before the connection and each blocking refill, so the whole transfer participates in the cancellation.
| ORDER BY k | ||
| """) | ||
|
|
||
| for _ in range(300): |
There was a problem hiding this comment.
This waits until the fetch is already visible in system.replicated_fetches, which only happens after fetchSelectedPart has finished the part-header reads and created the ReplicatedFetchList entry. That proves cancellation of an already-registered fetch, but it does not exercise the two late review fixes in this PR: the header-prefix window before registration (69aa7f447b83) and the very first ReadWriteBufferFromHTTP refill before any callback was attached (39a740ddd19e).
If either of those gaps regresses, both fetch tests still pass. We need one focused case that stalls before the entry appears in system.replicated_fetches and stops the receiver during that pre-registration / first-read phase.
There was a problem hiding this comment.
Some incompleteness of the tests is tolerable.
Related: #115732
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Cancel in-flight merges, mutations and part fetches during graceful server shutdown instead of waiting for the running step to finish. Previously a single slow merge step or a large part download could delay shutdown for its whole duration.
Description
ContextSharedPart::shutdownwaits for the MergeTree background executors beforeDatabaseCatalog::shutdown(the reordering that fixed the SIGBUS in #85433), but nothing cancels the tasks that are already running: the executors'waitonly prevents new steps from starting, and the per-storagemerges_blockercancellation happens later, inDatabaseCatalog::shutdown. So shutdown blocks until the currently running task step completes.This caused the
Possible deadlock on shutdown (see gdb.log)failure in the stress test (azure, amd_msan) on master:https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=a013c79d6ac80373b820381527ea85823ab03834&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_msan%29&name_1=Stress%20test%20%28azure%2C%20amd_msan%29
There, a background merge of
t_lwu_key_prefix(854090 rows in 5 parts plus 3MergeOnKeypatch parts, left over from04509_lwu_sorting_key_common_prefix) spent ~37 seconds per 8192-row block insideapplyPatchesMergeOnKeyunder MSan — quadratic patch application over an all-equal sorting key, tracked separately in #115732. Together with a randomizedmerge_max_block_sizeof ~24k rows and 5 sources to prime, the firstpullof the merge pipeline alone needed ~8 minutes, so the executor thread never reached a step boundary,MergeTreeBackgroundExecutor::waitblocked the whole time, and the hung check fired:gdb.logshows the main thread inContextSharedPart::shutdown→MergeTreeBackgroundExecutor::waitand theMergeMutatethread insideprocessEqualKeyCursors(applyPatches.cpp:468); the server log showsShutting down merges executorat 01:27:53 and no further shutdown progress until gdb attached at 01:33:53, withMergeWrittenRowsflat the whole time.The fix cancels the in-flight work before waiting for the executors, in three ordered steps so that the cancellation is not racy:
MergeTreeBackgroundExecutor::requestShutdownflips all four background executors into shutdown mode without joining them: new tasks are rejected bytryScheduleand pending tasks are not started (worker threads exit at the next step boundary), so the set of running tasks cannot grow anymore.MergeList::cancelAlland the newReplicatedFetchList::cancelAllcancel everything that is currently running, and also mark entries inserted later as cancelled, so a task that is inside its first step and has not registered itself in the list yet cannot escape the cancellation.Merge and mutate tasks check
MergeListElement::is_cancelledon every block throughMergeProgressCallback(the same mechanism the OOM canary uses), so a running merge aborts with theABORTEDexception within one block instead of running to completion. In-flight fetches are cancelled too, checked inReplicatedFetchReadCallbackon every buffer refill: a replicated merge can fall back toexecuteFetchinside the same task step before anyMergeListentry exists, and a plainGET_PARTfetch would otherwise block thefetch_executorjoin for the whole download. The results of these merges and fetches would have been discarded after the restart anyway, so finishing them was pure waste. This also restores the pre-#85433 semantics, where per-storage shutdown cancelled merges and fetches before anything waited on the executors.The zero-copy fetch branch is covered too: the
ReplicatedFetchListentry is created and the read callback installed before theremote_fs_metadatabranch offetchSelectedPart, so remote-disk metadata downloads participate in the same cancellation. The callback observes the cancellation between refills of the HTTP read buffer, so the fetch stream now honorsmax_read_buffer_size_remote_fs(the default is unchanged) to make the granularity configurable.Also adds the
merge_tree_sequential_source_sleep_before_readandreplicated_sends_sleep_before_file_sendfailpoints and an integration test (test_shutdown_cancels_merges) with three cases: a 16-part merge whose every reading step sleeps for 10 seconds, a fetch of a ~150 MB part from a sender throttled to 1 MiB/s, and a zero-copy fetch of a 20-column wide part from a sender that sleeps 5 seconds per metadata file — in all of them, the server must stop within 90 seconds.Workflow [PR]
Sync PR [sync-upstream/pr/115733]
Version info
26.9.1.345(included in26.9and later)