Skip to content

Cancel in-flight merges and mutations on server shutdown - #115733

Merged
alexey-milovidov merged 6 commits into
masterfrom
shutdown-cancel-merges
Aug 29, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
shutdown-cancel-merges

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Related: #115732

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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::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. 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 3 MergeOnKey patch parts, left over from 04509_lwu_sorting_key_common_prefix) spent ~37 seconds per 8192-row block inside applyPatchesMergeOnKey under MSan — quadratic patch application over an all-equal sorting key, tracked separately in #115732. Together with a randomized merge_max_block_size of ~24k rows and 5 sources to prime, the first pull of the merge pipeline alone needed ~8 minutes, so the executor thread never reached a step boundary, MergeTreeBackgroundExecutor::wait blocked the whole time, and the hung check fired: gdb.log shows the main thread in ContextSharedPart::shutdown → MergeTreeBackgroundExecutor::wait and the MergeMutate thread inside processEqualKeyCursors (applyPatches.cpp:468); the server log shows Shutting down merges executor at 01:27:53 and no further shutdown progress until gdb attached at 01:33:53, with MergeWrittenRows flat 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:

  1. MergeTreeBackgroundExecutor::requestShutdown flips all four background executors into shutdown mode without joining them: new tasks are rejected by trySchedule and pending tasks are not started (worker threads exit at the next step boundary), so the set of running tasks cannot grow anymore.
  2. MergeList::cancelAll and the new ReplicatedFetchList::cancelAll cancel 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.
  3. The executors are joined.

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. In-flight fetches are cancelled too, checked in ReplicatedFetchReadCallback on every buffer refill: a replicated merge can fall back to executeFetch inside the same task step before any MergeList entry exists, and a plain GET_PART fetch would otherwise block the fetch_executor join 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 ReplicatedFetchList entry is created and the read callback installed before the remote_fs_metadata branch of fetchSelectedPart, 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 honors max_read_buffer_size_remote_fs (the default is unchanged) to make the granularity configurable.

Also adds the merge_tree_sequential_source_sleep_before_read and replicated_sends_sleep_before_file_send failpoints 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

  • Merged into: 26.9.1.345 (included in 26.9 and later)

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

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [39a740d]

Summary: ✅


AI Review

Summary

This PR changes ContextSharedPart::shutdown to stop the MergeTree executors from accepting new work, cancel in-flight merges, mutations, and replicated fetches, and adds integration coverage for slow merges plus regular and zero-copy fetches. The code side of the previously reported races now looks consistent, but the new tests still do not prove the final fetch-cancellation invariant.

Tests
  • ⚠️ [tests/integration/test_shutdown_cancels_merges/test.py:117] Both fetch tests wait for system.replicated_fetches before shutting the receiver down. That only happens after fetchSelectedPart has already consumed the part-header prefix and created the ReplicatedFetchList entry, so the suite still does not exercise the pre-registration / first-read windows fixed in 69aa7f447b83 and 39a740ddd19e. A focused case needs to stall before the entry appears and stop the receiver during that earlier phase.
Final Verdict

Implementation 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 Report

Measured on commit 39a740d.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.80% 80.80% +0.00%

Changed lines: Changed C/C++ lines covered: 86/93 (92.47%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 21, 2026
Comment thread src/Interpreters/Context.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 39a740ddd with master 194df773e (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c0938b0c2; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 710.13 MiB 707.08 MiB -3.04 MiB (-0.43%)

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 units

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

Job report

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.
alexey-milovidov and others added 2 commits August 27, 2026 04:05
… 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):

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.

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.

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.

Some incompleteness of the tests is tolerable.

@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.

Good.

@alexey-milovidov alexey-milovidov self-assigned this Aug 29, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 29, 2026
Merged via the queue into master with commit 691db87 Aug 29, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the shutdown-cancel-merges branch August 29, 2026 15:14
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default 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.

2 participants