Repository navigation
Bound the shutdown wait for cancelled backups and restores - #115377
Conversation
A single SIGTERM never completed while a BACKUP was in flight and its I/O did not return. The shutdown handler blocked in BackupsWorker::wait(), an unbounded condition_variable::wait whose predicate consults only the operation status, so nothing could wake it. Both branches of shutdown_wait_backups_and_restores reached it (waitAll() and cancelAll(wait=true)), so no server setting avoided the hang, and cancellation does not converge either: inside one file the backup copy path uses the copyData overload without a cancellation hook, so a thread parked in a read never observes the cancel. The process was therefore always force-killed by systemd, docker stop or the test harness rather than shutting down. Give the shutdown-side wait a deadline and feed a non-convergence into the forced exit that already exists further down the same handler, which is the shape RefreshSet::joinBackgroundTasks uses for the same class of bug. Taking that exit is also what covers the thread-pool join one frame later: safeExit is _exit(2), which skips every SCOPE_EXIT_SAFE including the one that reaches ContextSharedPart::shutdown -> BackupsWorker::shutdown -> ThreadPools::wait, itself unbounded. Bounding that join instead would only relocate the hang into ~ThreadPoolImpl, which joins unconditionally. New operations are refused before the deadline is computed, otherwise the bound is not meaningful: waitAll() snapshots the unfinished operations once, and a distributed DDL query can still deliver an internal backup afterwards, which would leave the give-up decision false and then block in the same join. The refusal is placed after addInfo's deduplication branch so a replayed internal operation still gets its status, and it reports UNFINISHED for internal work, which DDLWorker retries, rather than QUERY_WAS_CANCELLED, which it records as permanently failed. The give-up decision is re-read immediately before the exit because killAllQueries and the connection drain can let a cancelled backup reach a final status meanwhile; that is sound precisely because admission is already closed, so the unfinished set can only shrink. The client wait keeps its exact current semantics: waiting forever is the contract of a synchronous BACKUP, and the deadline parameters are defaulted so that call site is unaffected.
Scopes the previous commit to shutdown_wait_backups_and_restores = false and adds the regression test. Bounding the wait on the default = true branch was wrong: that setting is documented as waiting for running backups and restores to finish, so capping it redefines a default-on guarantee, and the existing test_shutdown_wait_backup needs about 31 s while shutdown_wait_unfinished defaults to 5 s. No default timeout can be picked defensibly either - docker stop force-kills at 10 s and much of the integration harness at 30 s - and inferring "stuck" from the progress counters does not work, because BackupImpl::writeFile bumps num_files and total_size before copying a file and internal ON CLUSTER legs do not publish them at all. That branch is therefore left exactly as it was, and the contract question goes to the owners. On the = false branch there is no such guarantee to weaken: the wait is only supposed to cover cancellation, which test_cancel_backup.py states should take 2000-2500 ms. An unbounded wait there is a defect against that expectation, because a thread parked in a socket read never observes the cancellation, so it is bounded at shutdown_wait_unfinished. The admission barrier moves inside the same branch. Left branch-agnostic it can deadlock a healthy BACKUP ON CLUSTER on the default branch: the initiator is admitted before its background job fans out and then blocks waiting for the other hosts, so a barrier closing in that window refuses every internal leg and no leg ever reports. On the = false branch a refused leg is part of the cancellation that is happening anyway. waitAll and Context::waitAllBackupsAndRestores go back to their original void signatures - with everything scoped to the else branch, neither of their two callers ever passes a deadline. The new test wedges a backup with the existing backup_pause_on_start failpoint, whose action holds the failpoint mutex while paused, so the backup cannot observe cancellation. It asserts on stop_clickhouse()'s return value rather than on elapsed time or a log line: the forced-exit path is _exit(2), which discards the asynchronous log queue, so even the pre-existing "Closed connections." message does not reach any log file. Related: ClickHouse#115105
Correct three comments and make the shutdown deadline explicit in the test. The test comment claimed the paused thread holds the failpoint's own mutex while waiting. That is wrong: notifyPauseAndWaitForResume waits on a condition_variable, which releases the mutex. waitForPause also locks it and is called after the target pauses, so the test would deadlock on every run if the mutex were held. The real reason the operation cannot observe cancellation is that the pause is injected at the top of doBackup, upstream of both checkTimeLimit() poll sites. The UNFINISHED comment claimed an ON CLUSTER operation is retried on another host. DDLWorker does list UNFINISHED as retriable, so the error code is right, but a retriable task is rethrown without writing a finished node and stays queued for this host's own retry loop. Peers run their own legs; nothing reassigns ours. shutdown_wait_unfinished was documented as bounding unfinished queries only. It now also bounds the wait for running backups and restores when shutdown_wait_backups_and_restores is disabled, so the description says so. The .mdx page is generated from this string by the nightly job and is left untouched. The test relied on the global default of 5 seconds for its deadline, so it passed under any sub-30-second bound and did not show which setting supplies it. Pin the setting in the test's own config instead. Co-Authored-By: Claude Fable 5 <[email protected]>
The module-wide shutdown_wait_unfinished pin also bounds the connection drain and the refresh-task join in the same shutdown block, so the earlier value of 3 gave test_cancel_backup and test_shutdown_cancel_backup less margin than the stock default. Raise it to 10: still explicitly test-owned and different from the default, but strictly more margin than master. The wedged backup exits well inside its 30 second window either way. Add a negative arm that raises the setting to 600 and requires the server not to self-exit within the SIGTERM window. Without it the existing oracle is satisfied by any fixed sub-30-second deadline, so the dependency on the setting is untested. 600 is outside both the 30 second window and the 180 second one that stop_clickhouse uses on a coverage build, so the arm is deterministic in every build type.
Resolves one conflict in src/Backups/BackupsWorker.cpp: both sides add a single line to the ErrorCodes block (ours UNFINISHED, master's WRONG_BACKUP_SETTINGS from fd2d962). Both declarations are kept in the block's existing alphabetical order; no other hunk needed resolution.
Internal second-model review (click to expand)Reviewed cold against the code, then adjudicated with the recorded validation evidence. Four
Independently re-derived from the code, since a hang fix lives or dies on these:
Master was merged in during review, so the last round re-checked what the incoming changes could
Tests were re-run on the merged binary, with its Build ID confirmed changed: 4/4 in Session id: cron:clickhouse-review-slot-9:20260818-233400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-9:20260818-233400 |
|
Workflow [PR], commit [c74a4a6] Summary: ❌
AI ReviewSummaryThis PR bounds the shutdown-side wait only on the Final Verdict✅ No blocking issues found in the current version of the PR. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 88/98 (89.80%) · Uncovered code |
|
cc @pamarcos @jkartseva, could you review this? PedroTadim suggested you two on the issue. On the |
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. Object file sizes85 object files changed (+20.19 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1251 translation units recompiled, 7435 s compile time in total, 1251 of them have a recent master baseline. |
CI finish ledger - 13eca5fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The three 147 of 172 checks are green (plus 23 skipped). No other failures. Session id: cron:our-pr-ci-monitor:20260819-073000 |
Fixing PR for the
|
| time | tracked | current RSS | limit |
|---|---|---|---|
| 04:22:40 | 3.34 GiB | 43.10 GiB | 43.10 GiB |
| 04:27:10 | 2.09 GiB | 56.86 GiB | 46.29 GiB |
| 04:34:23 | 2.13 GiB | 56.91 GiB | 46.29 GiB |
1785 of the 2205 rejections (81%) are background merges (MergePlainMergeTreeTask::executeStep 893, MergeTreeBackgroundExecutor 892); the remaining 417 are system-log flushes failing as collateral. Untracked memory reads 433 KiB to 1.53 MiB, so the ~54 GiB gap between tracked bytes and RSS is not untracked-thread accounting.
That is the mechanism #109433 describes: background_memory_tracker sees only memory already allocated, so canEnqueueBackgroundTask admits many merges whose IO buffers then grow and collide. It touches MergePlainMergeTreeTask.cpp, the frame throwing 893 of the rejections here.
No PR from me for this line. I am not raising a fuzzer-runner memory-budget change: lowering the runner's max_server_memory_usage_to_ram_ratio would only start the Code 241 flood earlier while the unbounded merge growth continued past it, which is how the analogous #110293 was reverted.
Details on #108689.
|
Related fixing PR for the BuzzHouse variant of the To be explicit about scope: that PR does not fix the |
|
@groeneai Resolve merge conflicts |
…shutdown-bounded-wait-115105 # Conflicts: # programs/server/Server.cpp # src/Core/ServerSettings.cpp # src/Interpreters/Context.cpp
The backup path has more than two checkTimeLimit() sites: BackupEntriesCollector routes nine checkIsQueryCancelled() calls to it, plus BackupFileInfo and the write loop in BackupsWorker. The failpoint sits at the top of doBackup, so it precedes all of them; say that instead of naming a count. Closing the listening sockets stops socket-delivered requests, but a distributed DDL query can still deliver a backup afterwards, which is the case the new refusal gate covers. Narrow the older comment so the two do not contradict each other. Comments only, no behaviour change.
|
Resolved, the PR is mergeable again ( Three conflicts, all from master moving under the branch:
Verified after the merge: the diff against master is still exactly the 8 files and +262/-21 this PR started with, no submodule pins moved, and all 4 tests in Also corrected two comments while here: the failpoint sits before any |
CI finish ledger - c74a4a6Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The six 144 of 173 checks are green (plus 25 skipped). No other failures. Session id: cron:our-pr-ci-monitor:20260821-050000 |
|
Fixing PR for the two Docker image arm64 ledger lines ( Both were the apt-mirror 503 exhaustion signature: the in-region mirror pool degraded, every buildx retry re-ran the byte-identical command against that same pool, and the retry ladder was exhausted in ~14 min. #115726 rebuilds against Canonical once the retries are used up on an apt download failure, which covers all three affected Dockerfiles ( |
|
📊 Cloud Performance Report ✅ AI verdict: This is a shutdown-path change: it bounds how long the server waits for running backups/restores during teardown (new deadline plumbing in BackupsWorker and Context, plus a server setting doc and integration tests). None of it touches the SELECT query-execution hot path. ClickBench Q11 was flagged as a -15.0% improvement, but CPU time is essentially unchanged (1436.6 vs 1439.9 ms) while only wall-clock median moved, so the delta is run-to-run variance rather than a real PR effect; it has been downgraded to not_sure. No plausible per-query performance impact from this diff. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
c185437
Bound the shutdown wait for cancelled backups and restores
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
With
shutdown_wait_backups_and_restores = 0, aBACKUPorRESTOREwhose I/O did not return kept the server from terminating on a singleSIGTERM, because shutdown waited for it to reach a final status with no timeout. That wait is now bounded byshutdown_wait_unfinished, and new backups and restores are refused once shutdown has begun.Description
Closes: #115105
Reported by @ PedroTadim, who asked me to take it. The issue stays open.
Cause. Shutdown waits with
status_changed.wait- no timeout, predicate on the operation status only, so it lasts as long as the operation.cancelAlldoes not help: cancellation is polled per file (checkTimeLimit()beforewriteFile), and within a fileBackupImpluses thecopyDataoverload with no cancellation hook, so a thread parked in a read never sees it.Change, all inside the
shutdown_wait_backups_and_restores = 0branch ofServer.cpp: refuse new operations, bound the wait atshutdown_wait_unfinished, and on non-convergence feed the forced exit that already handles!joined_refresh_tasks. That exit is_exit, so the unboundedthread_pools->wait()inBackupsWorker::shutdown()is never reached rather than bounded.addInforefuses after its dedup early-return:UNFINISHEDfor internal operations (retriable inDDLWorker),QUERY_WAS_CANCELLEDotherwise.Not fixed here. The default
= 1branch is untouched, so the hang is still reachable with stock settings: that setting is documented as waiting for backups to finish, so capping it changes the guarantee and is your call. Also unchanged: the per-file cancellation granularity, andBackupsWorker::shutdown()reached without this guard (failed startup script), where bounding its status waits just moves the block to the pool join. An abandoned backup keeps itsCREATING_BACKUProw and can leave partial files.Validation. The new tests wedge a backup with the existing
backup_pause_on_startfailpoint, which parks the thread before anycheckTimeLimit()check, so the operation never sees its own cancellation. The oracle is whetherstop_clickhouse()escalated toSIGKILL, not elapsed time and not a log line (_exitdiscards the async log queue). One arm requires self-exit and fails on master; a second raises the setting to 600 and requires the server to keep waiting, so a hardcoded deadline fails it. 50/50 stable; sibling shutdown and on-cluster cancel tests pass.Workflow [PR]
Sync PR [sync-upstream/pr/115377]
Version info
26.9.1.1340(included in26.9and later)