Skip to content

Do not cancel the parts of ON CLUSTER backups and restores during a graceful shutdown that waits for them - #124334

Merged
jkartseva merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/shutdown-waits-for-late-backup-leg
Oct 19, 2026
Merged

jkartseva merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/shutdown-waits-for-late-backup-leg

Conversation

@groeneai

@groeneai groeneai commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fixed a graceful server shutdown cancelling a BACKUP ... ON CLUSTER or RESTORE ... ON CLUSTER whose part reached this host while it was shutting down, although shutdown_wait_backups_and_restores (enabled by default) makes the shutdown wait for running backups and restores.

Description

On 26.8, a BACKUP ... ON CLUSTER ends BACKUP_CANCELLED when one host gets its part just as it starts a graceful shutdown, although shutdown_wait_backups_and_restores = true makes a graceful shutdown wait for running backups.

Related: #84798. CI failure of test_shutdown_waits_for_backup: #101039.

Root cause. On SIGTERM the server waits only for already registered backups, then killAllQueries() cancels every query. The DDL worker runs until Context::shutdown; in the CI failures it had started the internal BACKUP query ~10 ms before SIGTERM, before registering it, so the kill cancelled it.

Change.

  • In wait mode the Server.cpp kill leaves running the BACKUP/RESTORE parts the DDL worker executes (recognized by a server-side flag, not the client's query kind). After the connection wait and the forced exit check, the server cancels the other queries, stops the DDL worker, which registers every part it delivered, and waits for all backups and restores before the AsyncLoader stops, because a restore can create a database. Any other backup or restore that misses the wait is still cancelled, because an ON CLUSTER initiator needs this host's DDL worker for its own part. shutdown_wait_backups_and_restores = false is unchanged.
  • New failpoint backups_hold_registration_until_ddl_worker_stops holds a part before it is registered until this host's DDL worker stops, which the shutdown does only after the kill, so the tests always exercise the late registration; they assert that the part is not registered when node2 begins shutting down.

Validation. New tests: the BACKUP one fails 6/6 without the fix (BACKUP_CANCELLED), the RESTORE one, which recreates a dropped database and also runs with shutdown_wait_unfinished_queries, 4/4 (RESTORE_CANCELLED); with the fix both pass, as does the original test. The backup modules of test_backup_restore_on_cluster and test_backup_restore_new pass. A shutdown during an unrelated TRUNCATE ... ON CLUSTER stuck on a table lock still exits at the shutdown_wait_unfinished deadline.


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

Version info

  • Merged into: 26.11.1.166-master (included in 26.11 and later)

groeneai and others added 5 commits October 6, 2026 18:20
With `shutdown_wait_backups_and_restores = true` (the default) a graceful
shutdown waits only for backups and restores already registered in
`BackupsWorker`, then `ProcessList::killAllQueries` cancels every query. The
DDL worker keeps running until `Context::shutdown`, so an internal ON CLUSTER
leg it starts right before the kill is cancelled "in pending state", the
backup inherits that cancelled query status, and the whole ON CLUSTER backup
ends `BACKUP_CANCELLED` (flaky `test_shutdown_waits_for_backup`).

In wait mode both shutdown kills now spare BACKUP and RESTORE queries;
`BackupsWorker::shutdown`, which already runs after `DDLWorker::shutdown`,
waits for them. `ContextSharedPart::shutdown` drains the DDL and backups
workers before joining the dictionaries loader threads, because a restore can
create a dictionary, and then kills what is left unconditionally.

The new failpoint `backups_delay_before_registering_operation` holds an
operation before registration so the race is deterministic in a test.

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

An initial BACKUP/RESTORE ... ON CLUSTER sends its own host's part through
this host's DDL queue and then waits for all hosts without a timeout. If it
missed the shutdown wait and were spared by the kill, the DDL worker is
stopped before the local part runs and BackupsWorker::shutdown blocks until
the 3600 s host-disconnect timeout. Keep cancelling initial queries; spare
only the non-initial parts the DDL worker runs for other hosts.

Add a test for the RESTORE part.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A part killed with node2 is re-run by the DDL worker after a restart, so
the new tests now read node1's final status after node2 stops and before
it starts again.

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

The client can send SECONDARY_QUERY, so the shutdown kills now spare only
BACKUP and RESTORE queries whose context the DDL worker made
(Context::isDDLOrOnClusterInternal), captured once in the QueryStatus.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the member comment that restates Context::isDDLOrOnClusterInternal and the duplicate dictionary-ordering clause on the backups worker shutdown; shorten the killAllQueries comment to one line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 7, 2026
@groeneai

groeneai commented Oct 7, 2026

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

Pre-publication review by an independent model (engine: codex; 4 rounds, 8 findings) plus my own review.

# Sev Finding Verdict Evidence / action
1 ❌ Sparing an initial BACKUP/RESTORE ... ON CLUSTER that registered after the shutdown wait lets it wait for its own part after this host's DDL worker stopped AGREE, fixed only the parts run by the DDL worker are spared
2 ❌ The client controls query_kind, so a --query_kind secondary_query initiator would still be spared AGREE, fixed spared by the server-side Context::isDDLOrOnClusterInternal flag; a spoofed query is cancelled as on master (A/B)
3 ⚠️ Only a BACKUP part was tested AGREE, fixed RESTORE test added
4 ⚠️ ContextSharedPart::shutdown half not reached by the test DISAGREE node2 logs: Shutting down ddl worker precedes the held part's Executed query in 7 of 10 runs, so the Context.cpp sparing is needed
5 ⚠️ A part killed with node2 is re-run by the DDL worker after the restart, so the final status did not prove the shutdown finished it AGREE, fixed status is read while node2 is down
6 ⚠️ The tests do not exercise the shutdown reorder (an eagerly loaded dictionary restored by a late part) AGREE, verified A/B with a dictionary_lazy_load = 0 dictionary in the late restore: with the reorder its load starts before Shutting down dictionaries loader threads 3/3, with the reorder reverted 3/3 after it (1.7-4.0 s). Both end RESTORED, so no committed oracle exists
7 ⚠️ The 5 s failpoint delay does not guarantee that SIGTERM lands before registration DISAGREE a missed window only gives a false pass; margin ~4 s, base red 12/12; a pausable failpoint cannot be released after SIGTERM
8 💡 Comments say "other hosts", the predicate also covers the initiator's own part AGREE, fixed wording
9 💡 Failpoint stays enabled on node2 if a test fails before the restart noted, not blocking later operations only slower
10 💡 A forced exit (connections left after shutdown_wait_unfinished) skips BackupsWorker::shutdown noted, not blocking same as any operation running at a forced exit

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. New failpoint backups_delay_before_registering_operation holds node2's internal BACKUP or RESTORE part before registration while node2 restarts gracefully; without the fix the new tests fail 3/3 (BACKUP_CANCELLED, RESTORE_CANCELLED).
b Root cause explained? Shutdown waits only for already registered backups, then killAllQueries() cancels every query; the DDL worker had started the part's query but not registered it, so the kill cancelled it and the operation inherited the cancelled query status.
c Fix matches root cause? Yes. In wait mode both shutdown kills spare the BACKUP/RESTORE parts the DDL worker runs (server-side Context::isDDLOrOnClusterInternal flag, not the client-supplied query kind); the existing BackupsWorker::shutdown (after DDLWorker::shutdown) waits for them. No new wait, refusal or timeout.
d Test intent preserved / new tests added? New integration tests test_shutdown_waits_for_backup_that_arrives_during_shutdown and test_shutdown_waits_for_restore_that_arrives_during_shutdown; test_shutdown_waits_for_backup is unchanged.
e Both directions demonstrated? Base binary (failpoint and tests only): 3/3 FAIL each. Fix binary: 10/10 PASS each, and the original test 10/10 PASS.
f Fix is general across code paths? Both shutdown kill sites (Server.cpp, ContextSharedPart::shutdown). Any other BACKUP/RESTORE, including one a client sends with --query_kind secondary_query, keeps master's behaviour (an ON CLUSTER initiator needs this host's DDL worker for its own part). The OOM canary kill and the introspection-servers kill are intentionally unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Covers the BACKUP and RESTORE parts, both tested. shutdown_wait_backups_and_restores = false is unchanged (both test_cancel_backup.py modules pass).
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; in wait mode a part that arrives during shutdown is now waited for, as the setting documents. Queries not run by the DDL worker and clickhouse-local behave as before.
i Invariants and contracts preserved? The DDL and backups workers are drained before the dictionaries loader threads are joined, followed by an unconditional kill, so no dictionary loading thread outlives that join (#100839); with an eagerly loaded dictionary in the restore, the load starts before that join 3/3, and 1.7-4.0 s after it 3/3 when only the reorder is reverted. DDLWorker::shutdown still runs after a kill and before BackupsWorker::shutdown.

Session id: cron:clickhouse-impl-slot-40:20261006-213800

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0a738e2]

Summary: ✅


AI Review

Summary

The change preserves DDL-worker parts of BACKUP ... ON CLUSTER and RESTORE ... ON CLUSTER during graceful shutdown when shutdown_wait_backups_and_restores is enabled, then drains them before stopping AsyncLoader. Reviewed head: 0a738e28391abfe5175f17c1a5d15c5832623406. No actionable findings remain; the previous loader-ordering and forced-shutdown findings are addressed.

Missing context / blind spots
  • ⚠️ Integration jobs on the current merge head are pending. The targeted ASan/UBSan run at 29dad409 passed the original shutdown test, the late-backup test, both late-restore cases, and the existing cancellation tests. Completion of those jobs on the current head would close this validation gap. No local build or integration run was performed.
Final Verdict

Status: ✅ Approve. No new inline findings or changes to existing review threads are needed.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 7, 2026
Comment thread src/Interpreters/ProcessList.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-backup Backup/restore infrastructure and backup formats. label Oct 7, 2026
@jkartseva jkartseva self-assigned this Oct 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0a738e283 with master 76cb67e41 (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.

Object file sizes

113 object files changed (+19.66 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/ProcessList.cpp.o 370.84 KiB 387.26 KiB +16.42 KiB (+4.43%)

719 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

1354 translation units recompiled, 8950 s compile time in total, 1353 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.8 s

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 9d424487-3b91-4d88-9031-1e4d768ca597
  • MIRAI run: fef26546-b7fa-4782-9867-ba5a1046d5ae
  • PR check IDs:
    • clickbench_772120_1791665618
    • clickbench_772126_1791665618
    • clickbench_772132_1791665618
    • tpch_adapted_1_official_772143_1791665618
    • tpch_adapted_1_official_772154_1791665618
    • tpch_adapted_1_official_772192_1791665618

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

@groeneai Please fix the tests which may be false-green.

"SELECT count() FROM system.processes WHERE query_kind = 'Backup' AND NOT is_initial_query",
"1",
)

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.

If a loaded runner overruns 5s, addInfo completes, and the test then exercises the already-working registered path – while still asserting BACKUP_CREATED/RESTORED, which is exactly what a missed race produces.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed, the fixed 5 s delay could expire before the restart. Fixed in c77b0f1 and 86c7d9e:

  • The failpoint (now backups_hold_registration_until_ddl_worker_stops) no longer sleeps for a fixed time. It holds node2's part before BackupsWorker::addInfo until node2's DDL worker is stopping, and ContextSharedPart::shutdown stops the DDL worker only after killAllQueries. So the part always registers after the kills, however slow the runner is.
  • Before stopping node2, the tests also assert that its part is running but has no system.backup_log entry yet, so a hold that did not take effect fails the test instead of passing through the registered path.
  • If a test fails before the stop, it disables the failpoint, which releases the held part, so it does not block node2's DDL queue for the following tests.

Without the fix both tests fail on every run (BACKUP_CANCELLED 6/6, RESTORE_CANCELLED 6/6); with the fix they pass 15/15 each.

"SELECT count() FROM system.processes WHERE query_kind = 'Restore' AND NOT is_initial_query",
"1",
)

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.

ditto

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Same change for the restore test, in the same commits (c77b0f1, 86c7d9e).

groeneai and others added 2 commits October 16, 2026 06:28
The failpoint used by the two new shutdown tests slept for 5 seconds before
`BackupsWorker::addInfo` registered the operation. If the graceful shutdown of
node2 began more than 5 seconds after node2's part entered that window (a slow
runner), the part was already registered, the shutdown wait covered it, and the
tests passed without exercising the late-registration path at all.

Replace the fixed delay with a hold that lasts until this host's DDL worker is
stopping (or the failpoint is disabled). `ContextSharedPart::shutdown` stops the
DDL worker only after `ProcessList::killAllQueries`, so the part now always
registers after the shutdown cancelled queries, regardless of timing: without
the fix the operation always ends cancelled, with the fix it always completes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Before the graceful stop, both tests now assert that node2's part is running
but has no `system.backup_log` entry yet, so a hold that did not take effect
fails the test instead of letting it pass through the already-working path of
a registered operation.

If the test fails before stopping node2, the failpoint is disabled, which
releases the held part; otherwise it would block node2's DDL queue for the
following tests in the module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/Context.cpp Resolved
The parts of ON CLUSTER backups and restores that the DDL worker registers after
the shutdown wait were spared by both shutdown kills and left to
`BackupsWorker::shutdown`. That runs in `Context::shutdown`, after the scope
guard in `Server.cpp` has already shut down the AsyncLoader. A late
`RESTORE DATABASE ... ON CLUSTER` of a dropped database then fails on the host
being restarted: `InterpreterCreateQuery::createDatabase` schedules the
database's startup job, and `AsyncLoader::schedule` throws
`ASYNC_LOAD_CANCELED: AsyncLoader was shut down: While creating database mydb`.

Drain those parts in `Server.cpp`, before the AsyncLoader stops: kill the other
queries as before, stop the DDL worker (which makes every part it delivered
registered), and wait for all backups and restores again. By default this
happens right after the existing kill. With `shutdown_wait_unfinished_queries`
there is no kill there, so the same kill and drain run after the queries were
waited for. Late initiators are still cancelled before the DDL worker stops,
because an initiator's own part needs it.

A DDL worker whose startup job has not run yet must not be started after it is
stopped, so the drain first removes that job from the AsyncLoader (cancelling
it if pending, waiting for it if running).

Since no such part outlives the drain, the `ContextSharedPart::shutdown` reorder
and its sparing kill are reverted to master. The only path that skips the drain
is a startup failure, where the DDL worker is not running.

The restore shutdown test now restores a dropped database, so it covers the
database and table creation, and it runs twice: restarting node2 (default
settings) and restarting node3, which has `shutdown_wait_unfinished_queries`.
- master shutdown code: RESTORE_CANCELLED (both cases)
- previous head (541c81bf): RESTORE_FAILED, ASYNC_LOAD_CANCELED (both cases)
- this commit without the drain after the query wait: RESTORE_CANCELLED in the
  `shutdown_wait_unfinished_queries` case
- this commit (9120585a): RESTORED (both cases, 3/3 each)

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 163c3c5

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
Build (arm_tidy, 3/4) / Build ClickHouse not from this PR: unit_tests_dbms does not compile on master since af19343b2516 (src/Functions/tests/gtest_functions_stress.cpp:2367: StackTrace::tryResolveAddress no longer returns an optional); the same build fails on 24 other PRs since 09:18 UTC. This failure stopped the workflow, so most test jobs did not run on this head #126269 (external, open)
Finish Workflow / Post Hooks Bugfix validation was dropped because of the row above #126269 (external, open)
Mergeable Check, PR rollups of the rows above #126269 (external, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261016-110007

Comment thread src/Interpreters/Context.cpp Resolved
Stopping the DDL worker joins the task it runs, including ones that are not
backups or restores. Before the connection wait, a `TRUNCATE ... ON CLUSTER`
waiting in `lockExclusively` for a lock held by a native `INSERT` that waits for
client data kept the shutdown waiting until `lock_acquire_timeout`, instead of
exiting forcefully after `shutdown_wait_unfinished` as master does (66.0 s vs
5.5 s with `shutdown_wait_unfinished = 5` and `lock_acquire_timeout = 60`).

The first kill stays where master has it and still spares the DDL worker's
parts, which keep running during the connection wait. After the forced exit
check, the remaining queries are cancelled again, as `ContextSharedPart::shutdown`
does before it stops the DDL worker, then the DDL worker is stopped and all
backups and restores are waited for, still before the AsyncLoader stops. Both
`shutdown_wait_unfinished_queries` modes now use the same place.

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

@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 October 17, 2026 03:01
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 29dad40

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
Stateless tests (amd_debug, parallel) / 05339_string_filters_during_scan_parquet_short_dictionary_values deterministic master failure since 2026-10-16 21:43Z, not from this PR (line 4 prints 0 instead of 1, identical on master in 20 jobs) #126384 (mine, open)
Stateless tests (arm_binary, parallel) / 05339_string_filters_during_scan_parquet_short_dictionary_values same master failure #126384 (the owner of the first row)
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) / 05339_string_filters_during_scan_parquet_short_dictionary_values, Too many test failures same master failure, 5 repeats, then the run stopped at the --max-failures limit #126384 (the owner of the first row)
Stateless tests (arm_asan_ubsan, targeted) / 05339_string_filters_during_scan_parquet_short_dictionary_values, Too many test failures same master failure, 5 repeats, then the run stopped at the --max-failures limit #126384 (the owner of the first row)
Finish Workflow / Post Hooks new_tests_check.py: both integration Bugfix validation jobs were dropped after the targeted failures above #126384 (the owner of the first row)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the rows above #126384 (the owner of the first row)

The two targeted jobs stopped early and the integration Bugfix validation was dropped, so the tests selected for this diff have not fully run on this head.

Session id: cron:our-pr-ci-monitor:20261017-030004

@jkartseva
jkartseva added this pull request to the merge queue Oct 18, 2026
Merged via the queue into ClickHouse:master with commit 02fa087 Oct 19, 2026
177 of 178 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-backup Backup/restore infrastructure and backup formats. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

4 participants