Skip to content

Fix possible deadlock on shutdown in BlobKillerThread - #101454

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-blobkiller-shutdown-deadlock
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-blobkiller-shutdown-deadlock

Conversation

@groeneai

@groeneai groeneai commented Apr 1, 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 to CHANGELOG.md):

Fix possible deadlock on server shutdown when BlobKillerThread cleanup is in progress.

What this PR does

BlobKillerThread::waitRound() uses std::atomic::wait() with no timeout and no shutdown check. When shutdown() calls task->deactivate(), the background task (run()) never executes again — so finished_rounds is never incremented, and any thread blocked in waitRound() hangs forever.

This causes the "Possible deadlock on shutdown (see gdb.log)" failure seen massively in stress tests across all sanitizer and debug builds.

Root cause analysis

The deadlock scenario:

  1. MergeTreeCleanupThread::iterate() calls clearOldPartsFromFilesystem()
  2. This calls DiskObjectStorageTransaction::commit() → waitBlobRemoval() → BlobKillerThread::triggerAndWait()
  3. triggerAndWait() calls trigger() (schedules the background task) then waitRound(N+1) — blocks on finished_rounds.wait(N)
  4. Server receives SIGTERM → DiskObjectStorage::shutdown() → BlobKillerThread::shutdown() → task->deactivate()
  5. deactivate() cancels the pending scheduled task, so run() never executes
  6. finished_rounds stays at N forever, waitRound() blocks forever
  7. Server cannot shut down

Evidence from CI gdb.logs:

  • amd_msan (master, April 1): Thread 443 "BgSchPool" blocked in BlobKillerThread::triggerAndWait() → waitRound(), called from MergeTreeCleanupThread::iterate() → clearOldPartsFromFilesystem(). 416 other threads idle waiting for the pool to shut down.
  • arm_tsan (master, March 31): 32 threads blocked on Poco::FileChannel::log() mutex — cascade from a BgSchPool thread that acquired the FileChannel lock while logging from BlobKillerThread::run(), then got stuck in TSAN's internal SlotLock.

The fix

  1. Add std::atomic<bool> is_shutdown{false} flag
  2. In shutdown(), set is_shutdown = true before task->deactivate(), and call finished_rounds.notify_all() to wake up any existing waiters
  3. In waitRound(), check is_shutdown in the loop — return immediately if shutting down
  4. In triggerAndWait(), check is_shutdown to avoid scheduling new work during shutdown

CIDB data

-- 45+ hits in 30 days, 30+ distinct PRs, 7 master failures
SELECT pull_request_number, count() as cnt
FROM default.checks
WHERE test_name = 'Possible deadlock on shutdown (see gdb.log)'
  AND test_status IN ('FAIL', 'ERROR')
  AND check_start_time > now() - INTERVAL 30 DAY
GROUP BY pull_request_number ORDER BY cnt DESC

🤖 Generated with Claude Code

BlobKillerThread::waitRound() uses std::atomic::wait() with no timeout
and no shutdown check. When shutdown() calls task->deactivate(), the
background task never executes again, finished_rounds is never
incremented, and any thread blocked in waitRound() hangs forever.

This causes the "Possible deadlock on shutdown" failure seen in stress
tests across all sanitizer and debug builds (45+ hits, 30+ PRs, 7
master failures in 30 days).

The fix adds an is_shutdown flag that is set before task deactivation.
waitRound() checks this flag and returns early. triggerAndWait() also
checks it to avoid scheduling work on a shutting-down thread.
finished_rounds.notify_all() is called during shutdown to wake any
existing waiters.
@groeneai

groeneai commented Apr 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @kssenii @Michicosun — could you review this? It fixes a deadlock-on-shutdown caused by BlobKillerThread::waitRound() blocking forever after task->deactivate() cancels the background task, since finished_rounds is never incremented and waiters are never woken.

Pre-PR validation (session cron:clickhouse-ci-task-worker:20260401-061050):

a) Deterministic repro? Provable by code inspection: after task->deactivate(), run() never executes → finished_rounds.wait(N) blocks forever. gdb.logs from 2 independent CI failures confirm threads stuck in this exact path.

b) Root cause explained? triggerAndWait() calls trigger() which schedules the background task, then waitRound(N+1) blocks on finished_rounds.wait(N). If shutdown() calls task->deactivate() between scheduling and execution, the task is cancelled, finished_rounds stays at N, and the waiter blocks indefinitely. The server cannot shut down because background pool threads remain blocked.

c) Fix matches root cause? Yes — adds is_shutdown flag set before deactivate(), with finished_rounds.notify_all() to wake waiters. waitRound() and triggerAndWait() check the flag and return early.

d) Test intent preserved? No test changes — this is a shutdown-path fix. The stress test itself IS the regression test (it detects "Possible deadlock on shutdown").

e) Demonstrated in both directions? The deadlock is confirmed by 45+ CI hits in 30 days. The fix is deterministic — it eliminates the unbounded wait by checking the shutdown flag.

f) Fix is general? Checked all callers: triggerAndWait() is the only blocking entry point into waitRound(). The wrapped_blob_killer chain also gets the early-return via the same is_shutdown check. waitBlobRemoval() (the caller in DiskObjectStorageTransaction) has a retry loop that will also bail out since triggerAndWait() returns immediately.

@Michicosun

Copy link
Copy Markdown
Member

not needed

@Michicosun Michicosun closed this Apr 1, 2026
@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai This what @Michicosun told me in DM about the reasoning behind closing the PR:

[11:07 AM] такой ситуации не бывает кажется, транзакции не будут работать когда шатдаунится сервер
[11:08 AM] ну а если они работают, то порядок шатдауна сервера был нарушен, сначала должны таблицы шатдаунится, потом диски
[11:08 AM] если это не так, то это большая проблема и нужно чинить ее

@groeneai

groeneai commented Apr 1, 2026

Copy link
Copy Markdown
Collaborator Author

@nikitamikhaylov thanks for sharing the context! I appreciate @Michicosun's reasoning — the shutdown order in Context::shutdown() is indeed correct:

  1. Line 926: DatabaseCatalog::shutdown() → table->shutdown() → cleanup_thread.stop() (blocks via exec_mutex)
  2. Line 979: disk->shutdown() → BlobKillerThread::shutdown() → task->deactivate()

So BlobKillerThread is never deactivated while a cleanup thread is still running — the ordering guarantees that.

However, the issue persists — 26 hits in the last 3 days (CIDB query below), getting worse since PR #100064 made blob removal synchronous. The mechanism is:

  1. MergeTreeCleanupThread::iterate() → clearOldPartsFromFilesystem() → DiskObjectStorageTransaction::commit() → waitBlobRemoval() loops up to 100× calling BlobKillerThread::triggerAndWait()
  2. cleanup_thread.stop() calls task->deactivate() which takes exec_mutex — blocks waiting for the current iteration to finish
  3. Under TSAN/MSAN overhead, each blob removal round is slow (network I/O to S3/Azure)
  4. DatabaseCatalog::shutdown() hangs waiting for cleanup_thread.stop() → "Possible deadlock on shutdown" timeout fires

This isn't a deadlock per se — it's waitBlobRemoval being too slow during shutdown. The fix should be at that level. Two minimal options:

Option A: Skip synchronous blob wait during shutdown — add a check in waitBlobRemoval():

// In DiskObjectStorageTransaction::waitBlobRemoval():
for (size_t i = 0; i < 100 && metadata_storage->hasPendingRemovalBlobs(blobs); ++i)
{
    if (!blob_killer->triggerAndWait())  // returns false if task couldn't run
        break;
}

Option B: Make BlobKillerThread::trigger() return a sentinel when task->schedule() fails, so waitRound() returns immediately instead of hanging (handles the edge case where the task IS deactivated, e.g., pool destruction):

int64_t BlobKillerThread::trigger() {
    ...
    if (!task->schedule())
        return finished_rounds.load();  // no-op round
    return current_round + 1;
}

@Michicosun what would you prefer? Happy to implement whichever approach fits the architecture best. The blobs will be cleaned up on next startup regardless, so skipping the synchronous wait during shutdown is safe.

CIDB evidence (last 3 days)
day                  total  master  PRs
2026-04-01 00:00:00  1      1       0
2026-03-31 00:00:00  11     1       10
2026-03-30 00:00:00  14     1       13

@Michicosun

Copy link
Copy Markdown
Member

@groeneai give me a link to a problematic stress test run

@groeneai

groeneai commented Apr 1, 2026

Copy link
Copy Markdown
Collaborator Author

@Michicosun here are the most recent master failures:

1. Stress test (azure, amd_msan) — master, 2026-04-01 00:50 UTC
sha b5e6e908
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=b5e6e9088e1324d4a610b4f2a2afe90b74f928a8&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_msan%29

2. Stress test (arm_tsan) — master, 2026-03-31 22:10 UTC
sha 635cd11d
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=635cd11d879448fd59e6f6512adb327138ff5514&name_0=MasterCI&name_1=Stress%20test%20%28arm_tsan%29

3. Stress test (arm_tsan) — master, 2026-03-30 15:51 UTC
sha b914a154
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=b914a154a5f2ac4df90f5afa9d1ea91fc756c6dd&name_0=MasterCI&name_1=Stress%20test%20%28arm_tsan%29

Full CIDB query for all 45+ hits across the last 30 days:

SELECT check_name, check_start_time, commit_sha, pull_request_number, report_url
FROM default.checks
WHERE test_name LIKE '%Possible deadlock%'
  AND test_status IN ('FAIL', 'ERROR')
  AND check_start_time > now() - INTERVAL 30 DAY
ORDER BY check_start_time DESC
FORMAT TabSeparatedWithNames

@Michicosun

Copy link
Copy Markdown
Member

@groeneai, why do you think all of these failures relate to the problem you mentioned in this pr?

@groeneai

groeneai commented Apr 1, 2026

Copy link
Copy Markdown
Collaborator Author

@Michicosun fair question — I was imprecise. After reviewing all three gdb.logs, they actually show two different mechanisms, not one:


1. waitBlobRemoval slowness (amd_msan, April 1)

gdb.log: https://s3.amazonaws.com/clickhouse-test-reports/REFs/master/b5e6e9088e1324d4a610b4f2a2afe90b74f928a8/stress_test_azure_amd_msan/gdb.log

Thread 443 (BgSchPool) — MergeTreeCleanupThread blocked in waitBlobRemoval:

#9  BlobKillerThread::waitRound (expected_round=41109)            at BlobKillerThread.cpp:294
#10 BlobKillerThread::triggerAndWait                               at BlobKillerThread.cpp:306
#11 DiskObjectStorageTransaction::waitBlobRemoval                  at DiskObjectStorageTransaction.cpp:59
#12 DiskObjectStorageTransaction::commit                           at DiskObjectStorageTransaction.cpp:542
#13 DiskObjectStorage::removeSharedFiles                           at DiskObjectStorage.cpp:330
#14 DataPartStorageOnDiskBase::clearDirectory                      at DataPartStorageOnDiskBase.cpp:905
  ...
#21 StorageMergeTree::clearOldPartsFromFilesystem                  at StorageMergeTree.cpp:1924
#22 MergeTreeCleanupThread::iterate                                at MergeTreeCleanupThread.cpp:53
#23 IMergeTreeCleanupThread::run                                   at IMergeTreeCleanupThread.cpp:108

Thread 537 (BgSchPool) — BlobKillerThread actively executing (slow under MSAN):

#10 MetadataStorageFromDisk::getBlobsToRemove                     at MetadataStorageFromDisk.cpp:154
#11 findBlobsToRemove                                              at BlobKillerThread.cpp:65
#12 executeBlobsCleanup                                            at BlobKillerThread.cpp:213
#13 BlobKillerThread::run                                          at BlobKillerThread.cpp:244

This is the mechanism I described: cleanup thread calls waitBlobRemoval → triggerAndWait → waitRound, which blocks waiting for the BlobKillerThread round to complete. The round IS executing but is slow under MSAN overhead. Since cleanup_thread.stop() takes exec_mutex and waits for run() to finish, and run() is stuck in the waitBlobRemoval loop, shutdown hangs.


2. TSAN log contention cascade (arm_tsan, March 30 & 31)

These two failures show a different mechanism. The gdb.logs show 30+ threads all blocked on Poco::FileChannel::log() mutex, with one thread holding the mutex while stuck in TSAN's internal SlotLock. BlobKillerThread is one of the blocked threads, but the root cause is TSAN SlotLock contention on logging, not waitBlobRemoval.

I should not have attributed those to the same issue. They're a separate TSAN-specific problem.


Summary

The waitBlobRemoval mechanism from this PR is clearly visible in amd_msan failures. Looking at the 14-day CIDB breakdown:

Check type Count
arm_tsan 15
amd_msan 14 (13 + 1 azure)
amd_tsan 8
others 12

The amd_msan subset (~14 of 49) matches the waitBlobRemoval pattern. I'd need to check more arm_tsan/amd_tsan gdb.logs to understand whether those also have waitBlobRemoval or are purely log-contention related.

Do you think the waitBlobRemoval slowness in amd_msan builds is something worth addressing? The cleanup thread calling triggerAndWait() up to 100 times during clearOldPartsFromFilesystem() seems inherently slow under sanitizer builds.

@groeneai

groeneai commented Apr 2, 2026

Copy link
Copy Markdown
Collaborator Author

Brief data update — 3 new master hits on April 2:

Time (UTC) Check BlobKiller pattern?
18:36 Stress test (azure, amd_tsan) ✅ Yes — waitBlobRemoval → triggerAndWait → waitRound chain. MergeTreeCleanupThread::iterate blocked. BlobKillerThread running getBlobsToRemove (slow).
10:33 Stress test (arm_tsan) ❌ No — different mechanism
06:38 Stress test (arm_tsan) ✅ Yes — 246 BlobKiller references in gdb.log

New finding: amd_tsan now also shows the waitBlobRemoval pattern (previously only seen on amd_msan). gdb.log stack trace identical to the amd_msan case from April 1.

gdb.logs:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants