Skip to content

Bound the shutdown wait for cancelled backups and restores - #115377

Merged
jkartseva merged 7 commits into
ClickHouse:masterfrom
groeneai:backups-shutdown-bounded-wait-115105
Sep 13, 2026
Merged

jkartseva merged 7 commits into
ClickHouse:masterfrom
groeneai:backups-shutdown-bounded-wait-115105

Conversation

@groeneai

@groeneai groeneai commented Aug 19, 2026 •

Copy link
Copy Markdown
Collaborator

Bound the shutdown wait for cancelled backups and restores

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):

With shutdown_wait_backups_and_restores = 0, a BACKUP or RESTORE whose I/O did not return kept the server from terminating on a single SIGTERM, because shutdown waited for it to reach a final status with no timeout. That wait is now bounded by shutdown_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. cancelAll does not help: cancellation is polled per file (checkTimeLimit() before writeFile), and within a file BackupImpl uses the copyData overload with no cancellation hook, so a thread parked in a read never sees it.

Change, all inside the shutdown_wait_backups_and_restores = 0 branch of Server.cpp: refuse new operations, bound the wait at shutdown_wait_unfinished, and on non-convergence feed the forced exit that already handles !joined_refresh_tasks. That exit is _exit, so the unbounded thread_pools->wait() in BackupsWorker::shutdown() is never reached rather than bounded. addInfo refuses after its dedup early-return: UNFINISHED for internal operations (retriable in DDLWorker), QUERY_WAS_CANCELLED otherwise.

Not fixed here. The default = 1 branch 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, and BackupsWorker::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 its CREATING_BACKUP row and can leave partial files.

Validation. The new tests wedge a backup with the existing backup_pause_on_start failpoint, which parks the thread before any checkTimeLimit() check, so the operation never sees its own cancellation. The oracle is whether stop_clickhouse() escalated to SIGKILL, not elapsed time and not a log line (_exit discards 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

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

groeneai and others added 5 commits August 18, 2026 13:55
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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Reviewed cold against the code, then adjudicated with the recorded validation evidence. Four
rounds. Every finding below was fixed rather than argued away, except the two marked as noted or
declined, which carry their reasons.

# Finding Verdict
❌ The regression test proved only that the server self-exited within 30 s, so any hardcoded sub-30 s deadline would have passed it: the dependency on shutdown_wait_unfinished was untested. AGREE, fixed. Added test_shutdown_wait_for_backup_is_configurable, which raises the setting to 600, asserts it is in force via system.server_settings before relying on it, and requires the server to keep waiting. Verified discriminating, not merely passing: rerunning it with the setting left at its pinned value fails at the oracle line. 600 exceeds both the 30 s window and the 180 s coverage-build override, so it is deterministic in every build type.
❌ A comment claimed the paused backup thread holds the failpoint mutex while waiting. A condition-variable wait releases the mutex; the thread is wedged because its predicate only observes a resume epoch. AGREE, fixed. Claim removed; the replacement names the actual mechanism (checkTimeLimit() polls upstream of the injection point).
❌ A comment said UNFINISHED moves an internal operation to another host. It prevents a permanent failure record but does not reassign the per-host task. AGREE, fixed. Reworded to "stays queued for a later retry". Re-verified at DDLWorker.cpp:616-623 and :782-784, where a retriable task is rethrown without the finished-node set request.
❌ Pinning the test's deadline module-wide also shortened two sibling tests' budget below the stock default, narrowing the window in which system.backup_log (7500 ms flush) must persist the BACKUP_CANCELLED row one of them asserts. AGREE, fixed. Pinned value raised so it is longer than the default rather than shorter, while still differing from it so the "config is in force" check stays valid.
❌ The issue relationship was only inside the leading HTML comment, which does not render, so the published description linked nothing; and the attribution link pointed at my own acknowledgment rather than the request it credits. AGREE, fixed. Added a visible Related: #115105 and repointed the link to comment 5326577830.
⚠️ shutdown_wait_unfinished was documented as query-only although it now also bounds backup and restore shutdown waits. AGREE, fixed at the source registration, not the generated page (direct edits to generated regions are rejected by CI).
💡 The same finding also asked for that attribution to become a live @-mention. Declined. The sentence is attribution, not a request for attention, and the reviewers this PR asks for are the two named in the issue. The rendered text is identical either way; only the notification differs.
💡 The new negative arm ends in a deliberate force-kill, so it loses that server lifetime's coverage profile on a coverage build. Noted, not blocking. Inherent to an oracle whose contract is "the server must not self-exit"; the alternative is leaving the settings dependency untested.
💡 #112816 adds a third flag to the same forced-exit condition in Server.cpp without touching the backups branch. Noted. Compatible in substance; expect a small textual conflict in that condition for whichever merges second.

Independently re-derived from the code, since a hang fix lives or dies on these:

  • The post-killAllQueries re-check is not a time-of-check race. It runs only in the branch that
    has already closed admission, and the flag is read in the same infos_mutex critical section as
    the insertion it gates, so the unfinished set cannot grow underneath it.
  • The re-check cannot mask the bug it exists for. A thread wedged upstream of the status update
    never reaches a final status, so a genuinely stuck operation keeps the forced exit armed; only a
    real completion clears it.
  • One absolute deadline is shared across all operations, so total wait is bounded by the deadline
    rather than by deadline times operation count.
  • wait_until returns its predicate, so "did it converge" is exact, and a deadline already in the
    past still evaluates once instead of reporting a false timeout.
  • Nothing erases from the operations map, so an id collected under the lock stays resolvable.

Master was merged in during review, so the last round re-checked what the incoming changes could
break rather than only the conflict that was reported:

  • resumable_backup_from_snapshot is rejected in BackupStarter's constructor, upstream of
    addInfo, so it cannot leave a registered operation for the bounded wait to wait on.
  • Master added no new insertion into the operations map (still one site, downstream of the
    admission check) and no new unbounded wait under src/Backups.
  • backup_pause_on_start survived master's failpoint reordering as PAUSEABLE_ONCE and is still
    injected at the top of doBackup, so both new tests still park the thread where they intend to.
  • The merge also brought in a new mandatory ClickHouse spelling check that did not exist when
    this branch was written. It passes, verified by injecting a misspelling into one of the new files
    and confirming the checker reports that file, so the pass is coverage and not a silent skip.

Tests were re-run on the merged binary, with its Build ID confirmed changed: 4/4 in
test_cancel_backup.py, and the sibling test_shutdown_wait_backup.

Session id: cron:clickhouse-review-slot-9:20260818-233400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SYSTEM ENABLE FAILPOINT backup_pause_on_start, start an async BACKUP, SYSTEM WAIT FAILPOINT ... PAUSE, then one SIGTERM. The failpoint parks the thread at the top of doBackup, upstream of both sites that poll for cancellation (checkTimeLimit() in BackupsWorker and in BackupFileInfo), so the wedged operation never observes a cancellation request. Automated as test_backup_restore_new/test_cancel_backup.py::test_shutdown_cancel_wedged_backup; no timing dependence.
b Root cause explained? Yes. BackupsWorker::wait blocks in status_changed.wait with no timeout and a predicate that only consults the operation status, so shutdown inherits the operation's duration. cancelAll cannot converge either: cancellation is polled once per file (checkTimeLimit() before writeFile) and BackupImpl copies with the copyData overload that has no cancellation hook, so a thread parked inside one file never observes the request.
c Fix matches root cause? Yes. The unbounded wait becomes wait_until on the cancel branch, admission is closed first so the wait cannot miss a late arrival, and non-convergence feeds the forced exit that already exists for !joined_refresh_tasks. No widened bound, no relaxed assertion, no defensive check masking an upstream defect. The residuals (per-file cancellation granularity; the default = 1 branch) are stated in the PR body rather than papered over.
d Test intent preserved / new tests added? Yes. Two new integration tests: the wedge arm above, plus test_shutdown_wait_for_backup_is_configurable, which raises the setting to 600 and requires the server to keep waiting - so replacing the setting-derived deadline with a constant fails it (verified: rerun with the setting left at its pinned value fails at the oracle line). test_shutdown_wait_backup.py is byte-for-byte untouched and passes twice on the final binary; it is the coverage for the default branch, and an earlier iteration that bounded that branch broke it, which is why the scope was narrowed instead of the test weakened.
e Both directions demonstrated? Yes, same test, same command. Base (9e7d226ccfa5272, Build ID 7963c0e8…): FAIL, stop_clickhouse returned None with Force kill clickhouse in stop_clickhouse. ps:11 in the log; the wedge assertion itself passed first, so the failure is the oracle, not the setup. Fix (Build ID 7a665f94…): PASS, no Force kill line. 50 repeat runs on the fix: 50 passed, 0 failed.
f Fix is general across code paths? Carriers enumerated. Both shutdown branches were examined; the cancel branch is fixed, the default branch is deliberately unchanged and disclosed. addInfo is the single admission chokepoint for all four start paths (local and internal backup and restore), so one check covers every producer. BackupsWorker::shutdown() and thread_pools->wait() are untouched: the give-up path is _exit(2), which skips the SCOPE_EXIT_SAFE that reaches them, so the unbounded join is never entered rather than made bounded. The startup-script route to shutdown() is real, disclosed, and not fixable without changing ThreadPool.
g Fix generalizes across inputs? Applies to backups and restores alike (shared wait/cancelAll/addInfo paths) and to local, internal and ON CLUSTER operations. Zero-budget input checked: shutdown_wait_unfinished = 0 yields a deadline of now, i.e. immediate give-up on the cancel branch, which matches that branch's intent; the default branch receives no deadline at all in either case. ON CLUSTER regression arm: test_backup_restore_on_cluster/test_cancel_backup.py, 7 of 7 pass, including test_shutdown_cancels_backup.
h Backward compatible? Yes. No new setting, no default change, no format or serialization change, so no SettingsChangesHistory.cpp row is needed (ServerSettings are not tracked there). The default shutdown_wait_backups_and_restores = 1 behaviour is byte-for-byte unchanged. On the non-default branch an unbounded wait becomes bounded and a BACKUP racing shutdown is refused fast instead of accepted and then abandoned; both are in the changelog entry.
i Invariants and contracts preserved? refuse_new_operations is read inside the same infos_mutex critical section as the infos insertion it gates, so no operation can slip in behind the barrier. The rejection sits after addInfo's dedup early-return, preserving replay idempotency for internal operations, and uses UNFINISHED (retriable in DDLWorker) so an ON CLUSTER task is not permanently failed by one host terminating. waitImpl is private and reachable only from the 2-argument wait (deadline unset) and from cancelAll, so InterpreterBackupQuery's synchronous wait keeps its exact semantics and cannot be handed a non-final status. waitAll and Context::waitAllBackupsAndRestores were reverted to their original void signatures. Durability: the abandoned operation keeps CREATING_BACKUP with no terminal row, since _exit never flushes the system logs; that is inherent to the pre-existing forced-exit path and is disclosed.

Session id: cron:clickhouse-review-slot-9:20260818-233400

@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c74a4a6]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) ERROR IGNORED
AST fuzzer (amd_debug, targeted, old_compatibility) ERROR IGNORED
Docker server image ERROR IGNORED
Docker keeper image ERROR IGNORED

AI Review

Summary

This PR bounds the shutdown-side wait only on the shutdown_wait_backups_and_restores = 0 path by closing admission to new backup and restore operations, waiting for cancellation only until shutdown_wait_unfinished, and falling back to the existing forced-exit path if an operation still does not converge. I reviewed the current diff and the prior PR discussion, and I did not find a remaining correctness, concurrency, or coverage issue that warrants an inline review comment.

Final Verdict

✅ No blocking issues found in the current version of the PR.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 88/98 (89.80%) · 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 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pamarcos @jkartseva, could you review this? PedroTadim suggested you two on the issue. On the shutdown_wait_backups_and_restores = 0 path, shutdown waited for each backup to reach a final status with no timeout, so a BACKUP whose I/O never returns held the server open through any number of SIGTERMs; the wait is now bounded by shutdown_wait_unfinished and non-convergence feeds the forced exit that already handles unfinished refresh tasks.

@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c74a4a61f with master e0bb74066 (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
Binary Master PR Δ
programs/clickhouse-stripped 704.49 MiB 701.44 MiB -3.05 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.

Object file sizes

85 object files changed (+20.19 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Backups/BackupsWorker.cpp.o 567.04 KiB 585.52 KiB +18.48 KiB (+3.26%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 13eca5f

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.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / ERROR: OOM in dmesg host out of memory, not a fuzzer finding: dmesg records constraint=CONSTRAINT_NONE ... global_oom, so the kernel killed clickhouse-serv under whole-host pressure rather than a per-cgroup limit. 45 rows / 44 PRs / 0 master in 30 days a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)
AST fuzzer (amd_debug, targeted, old_compatibility) / runner aborted before writing status.tsv the harness aborted before it could record a verdict: fuzzer exit code 143 (SIGTERM), then the follow-up docker call failed with Get "http://%2Fvar%2Frun%2Fdocker.sock/_ping": EOF. No status.tsv, so nothing was measured. 15 rows / 14 PRs / 0 master in 30 days a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)

The three Bugfix validation (integration tests, *) rows that CIDB records as FAIL for
test_cancel_backup.py are the expected polarity: both jobs report success, because bugfix
validation inverts FAIL/OK so that a regression test failing on master reads as "bug
reproduced". They are not failures.

147 of 172 checks are green (plus 23 skipped). No other failures.

Session id: cron:our-pr-ci-monitor:20260819-073000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug, targeted) ledger line

The ERROR: OOM in dmesg row above resolves to an external fixing PR: #109433 ("Reserve memory for merges up front").

I had read this as a whole-host memory squeeze. That framing was wrong, and the carrier's own server.log says so: it contains 2205 Code: 241 MEMORY_LIMIT_EXCEEDED records, so the server's memory tracker was rejecting allocations throughout, not being bypassed by the kernel. The tracker is already RSS-aware (MemoryTracker.cpp:346), yet RSS still climbed past its own limit and stayed there:

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.

@groeneai

groeneai commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator Author

Related fixing PR for the BuzzHouse variant of the status.tsv abort: #115554 (pauseable failpoints park a fuzzer query with no timeout, so teardown never writes status.tsv).

To be explicit about scope: that PR does not fix the AST fuzzer failure on this head. The reporting signature is the same but the cause is different: the AST fuzzer keeps fail_point_name in its rotation and no .sql corpus file names the failpoint involved, so it cannot reach it. The AST fuzzer (amd_debug, targeted) failure here is a whole-host global_oom and is a separate issue.

@jkartseva

Copy link
Copy Markdown
Member

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

Copy link
Copy Markdown
Collaborator Author

Resolved, the PR is mergeable again (c74a4a61f).

Three conflicts, all from master moving under the branch:

  • Server.cpp, the forced-exit condition: master added !joined_background_queries, this branch added !backups_finished. Kept both terms.
  • ServerSettings.cpp, shutdown_wait_unfinished: master raised the default 5 -> 120, this branch only extended the description. Kept master's 120 with the extended text. Both new tests pin the value in config, so neither depends on the default.
  • Context.cpp: getBackgroundQueryPool() and stopAcceptingNewBackupsAndRestores() were added at the same spot. Kept both.

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 test_cancel_backup.py pass, including the arm that fails if the deadline is hardcoded instead of read from the setting.

Also corrected two comments while here: the failpoint sits before any checkTimeLimit() check rather than before two of them (BackupEntriesCollector routes nine cancellation checks there), and the older "no more backups/restores" note now says "no socket-delivered", since a distributed DDL query can still deliver one after the sockets close.

@jkartseva jkartseva self-assigned this Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c74a4a6

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.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / std::length_error in vector (STID 2508-3132) trunk bug, not from this diff. The abort is sliceMarksAcrossBuckets -> setupDistributedReadBuckets -> tryMakeBucketedReadVariant, sizing a vector<RangesInDataPartsDescription> from the fuzzed distributed_plan_workers_num = 9223372036854775807. This diff touches only Backups, Server and Context: no ReadFromMergeTree / Cascades / RuleUtils file appears in it. The targeted arm picks its query corpus by coverage of the diff, so it reaches code far outside the diff and never confines the crash site. Signature breadth 6 rows / 6 PRs / 1 master in 30 days #115398 (mine, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / ERROR: OOM in dmesg the runner ran out of memory before the job could record a verdict. Root cause is unbounded background-merge memory, as detailed on this PR on 2026-08-19: the carrier's server.log holds 2205 Code: 241 records, 1785 of them background merges, so the tracker was rejecting while RSS ran above its own limit. Breadth 10 rows / 8 PRs / 0 master in 30 days #109433 (external, open)
Docker server image / clickhouse/clickhouse-server:head-arm64 infra, arm64 leg only (Failures: 1/10). The ch-builder apt stage exits 100 after E: Failed to fetch ... 503 Service Unavailable from several distinct ports.ubuntu.com mirror IPs, so the mirror pool was degraded rather than one host. The buildx retry loop fired and was exhausted 5/5 inside about 14 minutes. Family breadth 13 rows / 8 PRs / 1 master in 30 days a fix task is created (investigating at full effort - fixing PR link to follow on this PR)
Docker keeper image / clickhouse/clickhouse-keeper:head-distroless-arm64 same apt-mirror 503 exhaustion as the row above, in docker/keeper/Dockerfile.distroless a fix task is created (investigating at full effort - fixing PR link to follow on this PR)

The six Bugfix validation (integration tests, aarch64/amd64) rows that CIDB records as FAIL
for test_cancel_backup.py are the expected polarity: both jobs report success, because bugfix
validation inverts FAIL/OK so a regression test failing against the pre-fix binary reads as
"bug reproduced". They are not failures. The eight unstable rows are Performance Comparison
per-query verdicts, not failures either.

144 of 173 checks are green (plus 25 skipped). No other failures.

Session id: cron:our-pr-ci-monitor:20260821-050000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the two Docker image arm64 ledger lines (Docker server image / head-arm64 and Docker keeper image / head-distroless-arm64): #115726.

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 (server/Dockerfile.ubuntu, server/Dockerfile.distroless, keeper/Dockerfile.distroless) since they share one build path. I checked its predicate against the captured job log from the failing master job and it matches there.

@clickhouse-gh clickhouse-gh Bot added the comp-backup Backup/restore infrastructure and backup formats. label Sep 4, 2026

@jkartseva jkartseva left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@jkartseva
jkartseva enabled auto-merge September 12, 2026 00:44
@jkartseva
jkartseva added this pull request to the merge queue Sep 12, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 11 not_sure 193 164 -15.0% <0.0001 This PR only changes server shutdown backup/restore teardown; Q11's SELECT path is untouched, and CPU time is flat (1436 vs 1440 ms), so the -15.0% median shift is run-to-run variance, not a PR effect.

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
  • StressHouse run: 64683ae9-5867-44d0-95a1-06493820f0df
  • MIRAI run: 1bb6e3de-ac0a-4916-a4e1-5968753389d2
  • PR check IDs:
    • clickbench_147790_1789194051
    • clickbench_147796_1789194051
    • clickbench_147802_1789194051
    • tpch_adapted_1_official_147812_1789194051
    • tpch_adapted_1_official_147825_1789194051
    • tpch_adapted_1_official_147861_1789194051

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-backup Backup/restore infrastructure and backup formats. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

Server shutdown hangs forever when a backup is blocked on unresponsive I/O

3 participants