Skip to content

Add timeout to waitBlobRemoval to prevent shutdown deadlock - #101680

Closed
groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:fix-shutdown-deadlock-blob-removal-timeout
Closed

groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:fix-shutdown-deadlock-blob-removal-timeout

Conversation

@groeneai

@groeneai groeneai commented Apr 3, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

  • Not required

What this PR does

Adds a 30-second total timeout to DiskObjectStorageTransaction::waitBlobRemoval().

Problem: waitBlobRemoval() loops up to 100 times calling BlobKillerThread::triggerAndWait(), each of which blocks indefinitely until a full cleanup round completes. Under sanitizer builds (TSAN/MSAN), each round takes many seconds due to overhead. This blocks MergeTreeCleanupThread::iterate() for minutes, causing cleanup_thread.stop() (called during DatabaseCatalog::shutdown()) to hang — triggering the "Possible deadlock on shutdown" stress test failure.

Fix: After each triggerAndWait() call, check total elapsed time. If >30 seconds, break the loop with a warning. Remaining blobs will be cleaned up by the next scheduled BlobKillerThread run — the metadata already records them for removal, so no data is lost.

Why this is safe:

  1. The metadata transaction has already committed — blobs are queued for removal regardless
  2. BlobKillerThread runs on a schedule and will process remaining blobs
  3. Normal operation completes in <100ms — the timeout only triggers under extreme conditions (sanitizer overhead, slow I/O)

Evidence: 3 master failures on April 2 alone — highest single-day count. gdb.log from amd_tsan and arm_tsan shows MergeTreeCleanupThread blocked in waitBlobRemoval → triggerAndWait → waitRound while BlobKillerThread::run() executes slow getBlobsToRemove. Full analysis in PR #101454.

CIDB query for failure trend:

SELECT toStartOfDay(check_start_time) as day, count() as fails,
       countIf(pull_request_number = 0) as master
FROM default.checks
WHERE test_name LIKE '%Possible deadlock on shutdown%'
  AND test_status IN ('FAIL', 'ERROR')
  AND check_start_time > now() - INTERVAL 14 DAY
GROUP BY day ORDER BY day DESC

Fixes: #101383

This is a follow-up to the analysis in #101454. The previous PR used an is_shutdown flag; this approach is simpler — a contained timeout in waitBlobRemoval() with no new state or APIs.


Note

Medium Risk
Touches object-storage cleanup/commit blocking behavior and thread synchronization; while intended to prevent indefinite waits, it can change timing (async cleanup) and could expose latent race/cleanup assumptions under load.

Overview
Prevents DiskObjectStorageTransaction::commit from blocking indefinitely on object-storage blob cleanup by introducing a new server setting disk_object_storage_blob_removal_wait_timeout_ms (default 30s, 0 = infinite) and enforcing a deadline in waitBlobRemoval with a warning when exceeded.

Updates BlobKillerThread waiting semantics to support time-bounded waits: triggerAndWait/waitRound now accept a deadline and use a mutex + condition variable (instead of std::atomic::wait) to avoid missing wakeups and to allow timeouts, ensuring a single slow/stuck cleanup round can’t block callers past the configured budget.

Reviewed by Cursor Bugbot for commit 7d21f91. Bugbot is set up for automated code reviews on this repo. Configure here.

The waitBlobRemoval() function loops up to 100 times calling
triggerAndWait(), each of which blocks indefinitely until the
BlobKillerThread completes a full cleanup round. Under sanitizer
builds (TSAN/MSAN), each round can take many seconds due to overhead.
100 slow rounds blocks MergeTreeCleanupThread for minutes, causing
"Possible deadlock on shutdown" when DatabaseCatalog::shutdown()
tries to deactivate the cleanup thread.

Add a 30-second total timeout. If exceeded, break the loop and log
a warning. Remaining blobs will be cleaned up asynchronously by the
next scheduled BlobKillerThread run — the metadata already records
them for removal, so no data is lost.

This is safe because:
1. The metadata transaction has already committed by the time
   waitBlobRemoval() is called — blobs are queued for removal
2. BlobKillerThread runs on a schedule and will clean them up
3. The timeout only triggers under extreme conditions (sanitizer
   overhead, slow I/O) — normal operation completes in <100ms

Fixes: ClickHouse#101383
@groeneai

groeneai commented Apr 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate

Session: cron:clickhouse-ci-task-worker:20260402-234500

a) Deterministic repro?
The shutdown hang is deterministic when MergeTreeCleanupThread is in waitBlobRemoval() during slow blob removal. Three gdb.logs from April 2 master hits (sha 74c3744b, 29642af4, 28141479) show the exact chain: MergeTreeCleanupThread::iterate() → clearOldPartsFromFilesystem → DiskObjectStorageTransaction::commit → waitBlobRemoval → BlobKillerThread::triggerAndWait → waitRound (blocked).

b) Root cause explained?
waitBlobRemoval() loops up to 100× calling triggerAndWait(). Each call blocks until BlobKillerThread::run() completes a full executeBlobsCleanup round. Under TSAN/MSAN, getBlobsToRemove() is slow (10-20x overhead). 100 slow rounds × seconds each = minutes blocking iterate(). cleanup_thread.stop() can't deactivate until iterate() returns → DatabaseCatalog::shutdown() hangs → "Possible deadlock" timeout fires.

c) Fix matches root cause?
Yes. The fix adds a 30-second total time limit to the waitBlobRemoval() loop. After timeout, remaining blobs are left for the scheduled BlobKillerThread. This directly prevents the unbounded blocking that causes the hang.

d) Test intent preserved?
No test changes. The fix adds a safety timeout to production code. waitBlobRemoval() still waits for blob removal under normal conditions (completes in <100ms). The timeout only fires under extreme conditions.

e) Both directions demonstrated?
The failure direction is demonstrated by 3 master gdb.logs showing the exact blocking chain. The fix direction: with a 30-second cap, the worst-case waitBlobRemoval() duration drops from unbounded (100 × slow round) to 30 seconds — well within the shutdown timeout threshold.

f) Fix is general?
waitBlobRemoval() is the single function called from both commit() (line 564) and tryCommit() (line 638). There are no other call sites. The timeout covers all code paths.

@groeneai

groeneai commented Apr 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @kssenii — could you review this? It adds a 30-second timeout to waitBlobRemoval() to prevent MergeTreeCleanupThread from blocking shutdown indefinitely when BlobKillerThread rounds are slow under sanitizer overhead. This is a simpler approach than the is_shutdown flag in #101454 — just a contained timeout in the existing loop, no new state or APIs.

@groeneai

groeneai commented Apr 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alesapin — requesting a second opinion on this approach. The previous attempt (#101454) used a shutdown flag; this one is simpler — a contained 30-second timeout in the existing waitBlobRemoval() loop. gdb.logs from April 2 master hits show MergeTreeCleanupThread::iterate → waitBlobRemoval → triggerAndWait → waitRound chain blocking shutdown for 90+ seconds under sanitizer overhead.

@groeneai

groeneai commented Apr 4, 2026

Copy link
Copy Markdown
Collaborator Author

Could someone add the can be tested label to enable CI? This adds a timeout to waitBlobRemoval() to prevent shutdown deadlock (9 master hits in 14 days, issue #101383). Thanks!

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

First, I thought about how bad it is that we introduced a constant in the code. But then noticed that we already have another, @Michicosun

@alexey-milovidov alexey-milovidov self-assigned this Apr 10, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1730e14]

Summary: ⏳

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
03360_bool_remote FAIL cidb
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue
Stress test (arm_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue

AI Review

Summary

This PR bounds DiskObjectStorageTransaction::commit waiting for object-storage blob removal by pushing an absolute deadline into BlobKillerThread::waitRound, adding a documented server default plus per-disk override, and covering both bounded and strict-wait behavior with a failpoint test. The prior bot findings about the outer-only timeout, missing configurability, and missing regression coverage are addressed in the current code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Apr 10, 2026

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

It is not correct, it will just hide the issue that blobs are not removed fast enough.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Michicosun I understand the concern — the timeout doesn't address the underlying speed of blob removal, it just caps the wait.

That said, the issue is still very active despite the performance improvements you made in March (parallel trigger, batch Azure remove, narrower tasks, configurable batch sizes):

Day Master PRs Total
Apr 10 1 12 13
Apr 9 1 47 48
Apr 8 1 8 9
Apr 7 1 14 15
Apr 2 3 6 9

88 hits in 7 days, arm_tsan alone contributes 43. The core issue is that under TSAN/MSAN (10–20× overhead), even optimized S3/Azure I/O makes each triggerAndWait() round slow, and 100 slow rounds blocks MergeTreeCleanupThread::iterate() long enough to trip the shutdown hang detector.

A few questions:

  1. Do you have a plan to make blob removal fast enough to handle 100 rounds under sanitizer builds? The slowness is inherent in the instrumentation overhead on network I/O — there may be a ceiling on how fast it can get.

  2. Would you prefer a different approach? For example:

    • Reducing the loop limit from 100 to something smaller (e.g., 3–5 rounds — your commit 133087f728b already reduced it from unbounded to 100)
    • Making waitRound() accept a deadline so the wait is bounded at the BlobKillerThread level
    • Prioritizing the specific transaction's blobs in the BlobKillerThread round, so fewer rounds are needed
  3. Are you planning to address this yourself? Happy to close this PR if you have a fix in mind. Just want to make sure the issue gets resolved — it's the top stress test failure on master right now.

…e it configurable

This addresses the two clickhouse-gh[bot] reviews on PR ClickHouse#101680 (2026-05-16) and
@Michicosun's earlier `CHANGES_REQUESTED`:

  Bot review 1 (DiskObjectStorageTransaction.cpp:70):
  > "This timeout does not actually bound the blocking wait, because the check
  > happens only after `triggerAndWait()` returns. `triggerAndWait` waits in
  > `waitRound` without a deadline, so a single slow or stuck round can still
  > block here indefinitely (or far beyond 30s)."

  Bot review 2 (DiskObjectStorageTransaction.cpp:65):
  > "This introduces a behavior change for `wait_for_blob_removal=true`. The
  > new behavior is not configurable or documented."

  @Michicosun:
  > "It is not correct, it will just hide the issue that blobs are not removed
  > fast enough."

The previous version of the patch added a 30s timeout *around* the
`triggerAndWait` call, so a wait that stalled inside `BlobKillerThread::waitRound`
would never be interrupted. This rewrite pushes the deadline into `waitRound`
itself and surfaces the budget as a documented `ServerSetting`.

Changes:

* `BlobKillerThread::waitRound` now uses `std::condition_variable::wait_until`
  with a caller-supplied deadline instead of `std::atomic<int64_t>::wait`
  (which has no timeout). Returns `bool` (`true` = round completed, `false`
  = deadline expired). Existing call sites pass `time_point::max()` via the
  default argument and keep their "wait indefinitely" semantics.

* `BlobKillerThread::run` increments `finished_rounds` under the new mutex
  before `notify_all`, the standard predicate-CV pattern that avoids missed
  wake-ups.

* New `ServerSetting` `disk_object_storage_blob_removal_wait_timeout_ms`
  (default 30000) bounds the synchronous wait in
  `DiskObjectStorageTransaction::commit`. The contract is documented in the
  setting description; `0` restores the strict pre-fix behavior so operators
  who prefer it can opt back in.

* `DiskObjectStorageTransaction::waitBlobRemoval` reads the setting, computes
  the deadline once before the loop, and propagates it into every
  `triggerAndWait` call so a stuck round is bounded by the same budget as
  the outer loop.

Other callers of `triggerAndWait` (`DiskObjectStorage::waitBlobsCleanup`,
`InterpreterSystemQuery::SYSTEM SYNC FILE CACHE`) are unaffected because
they rely on the default argument and discard the return value.

Re: CI report
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

PR: ClickHouse#101680

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

Copy link
Copy Markdown
Collaborator Author

Thanks for both follow-ups, @clickhouse-gh, and @Michicosun — your previous review was the missing piece. I've reworked the patch (3d2f70b) so the design actually addresses all three concerns rather than papering over the deadlock. Summary first, then point-by-point.

What changed in the new commit

Instead of a 30s wall-clock check around triggerAndWait, the deadline is now pushed into BlobKillerThread::waitRound, and the budget is a documented server setting.

  • BlobKillerThread::waitRound(int64_t expected_round, std::chrono::steady_clock::time_point deadline) now uses std::condition_variable::wait_until instead of std::atomic<int64_t>::wait (which has no timeout). Returns bool: true = round reached, false = deadline expired.
  • BlobKillerThread::triggerAndWait(deadline = time_point::max()) propagates the deadline through both the recursive wrapped-killer call and the local waitRound. The default keeps the "wait indefinitely" semantics for callers that don't care (e.g. DiskObjectStorage::waitBlobsCleanup, SYSTEM SYNC FILE CACHE).
  • BlobKillerThread::run now increments finished_rounds under the new mutex before notify_all, the standard predicate-CV pattern (no missed wake-ups).
  • New ServerSetting disk_object_storage_blob_removal_wait_timeout_ms (default 30000) makes the budget configurable and documented. Setting it to 0 restores the strict pre-fix semantics where commit waits indefinitely.
  • DiskObjectStorageTransaction::waitBlobRemoval reads the setting once, computes a single deadline, and passes it into every triggerAndWait call.

Diff is small (4 files, +87 / -26) — git diff origin/master..3d2f70b271c0.

Re: @clickhouse-gh, first review — "timeout does not actually bound the blocking wait"

You were right. With the old code, if waitRound itself was the slow part (the actual deadlock case in the gdb.logs, where triggerAndWait is blocked in MetadataStorageFromDisk::getBlobsToRemove), the outer watch.elapsed() check never executed. The wait was unbounded.

In the new commit the deadline is enforced inside waitRound via wait_until on the CV. A stuck round terminates when the deadline expires, the outer loop sees the false return and breaks. The bound is real now.

Re: @clickhouse-gh, second review — "behavior change not configurable or documented"

Now configurable via disk_object_storage_blob_removal_wait_timeout_ms:

value behavior
30000 (default) wait up to 30s, then warn and return; remaining blobs cleaned up by next scheduled BlobKillerThread round
0 wait indefinitely — restores the original strict wait_for_blob_removal=true contract
any positive value configurable bound for that operator's environment

The semantics are documented inline in ServerSettings.cpp (rendered into system.server_settings.description). Operators who prefer the strict contract can opt back in with a single config line; the default protects the much larger group of users who hit the shutdown watchdog under sanitizer / heavy-IO builds.

Re: @Michicosun — "it will just hide the issue that blobs are not removed fast enough"

I agree this is a real concern and the new design tries to give it a proper outlet:

  1. 0 = strict — operators who want the failure to surface (so the underlying slowness can be diagnosed) explicitly opt in via the setting. The strict contract is still available; it's just no longer the only option.
  2. The warning log at timeout time is loud and unique ("Waiting for blob removal timed out after {} ms ({} iterations, configured limit {} ms)"), so even with the default in place, slow-blob-removal incidents leave a trail that can be aggregated by SREs.
  3. The metric DiskObjectStorageWaitBlobRemovalMicroseconds is already wired up and unchanged, so the slowness shows up in profiling regardless of the setting.
  4. The deadlock-on-shutdown failures we're seeing in CIDB are not "blobs not removed fast enough" in the data-correctness sense — they're "blobs not removed fast enough under sanitizer overhead during shutdown, when the synchronous wait introduced by DiskObjectStorage synchronously wait blob removal in transactions #100064 inadvertently couples cleanup latency to shutdown latency". The right fix is to decouple them and surface the slowness through metrics+logs, not to keep blocking shutdown.

That said — if you'd prefer the strict contract to remain the default and treat 30s as opt-in rather than opt-out, that's a one-line change in ServerSettings.cpp (30000 → 0 as the default). I'm fine either way; flagging it explicitly because it's a real policy choice rather than a technical one. Happy to flip it if you say so.

CIDB after the previous push

Since 2026-04-10 (your CHANGES_REQUESTED), tracked from PR-monitor cron:

Not blocking, just empirical context for prioritization.

Verification

  • Clean build on debug clang-21 (36/36, exit 0)
  • New setting registered with correct default + description:
    SELECT name, value, default FROM system.server_settings WHERE name = 'disk_object_storage_blob_removal_wait_timeout_ms';
    → disk_object_storage_blob_removal_wait_timeout_ms  30000  30000
    
  • Async-blob-removal stateless tests pass: 03776_local_object_storage_blob_storage_log, 04105_blob_storage_log_read_local, 02714_local_object_storage.
  • The deadlock case itself is hard to reproduce deterministically without a sanitizer build and a fail-point inside getBlobsToRemove; the CIDB will be the ground-truth signal after merge.

Re-requesting review from @Michicosun (code owner), @kssenii, @alesapin. Happy to iterate further or flip the default if you prefer the strict contract opt-in.

…ck-blob-removal-timeout

# Conflicts:
#	src/Disks/DiskObjectStorage/Replication/BlobKillerThread.h
groeneai and others added 2 commits May 30, 2026 10:49
Addresses the clickhouse-gh[bot] inline review on PR ClickHouse#101680 asking for a
deterministic regression test that proves both directions of the new
bounded-wait contract introduced by commit 3d2f70b.

Changes:

1. New `PAUSEABLE` failpoint `blob_killer_thread_pause_in_run` registered
   in `src/Common/FailPoint.cpp` and triggered at the top of
   `BlobKillerThread::run`. While enabled it blocks every cleanup round so
   `finished_rounds` cannot advance and a concurrent `waitRound` exercises
   exactly the code path the bot flagged.

2. Per-disk `wait_for_blob_removal_timeout_ms` config option, mirroring
   the existing per-disk `wait_for_blob_removal` pattern. Falls back to
   the server setting when absent. Stored on `DiskObjectStorage`,
   propagated into `DiskObjectStorageTransaction` so the deadline used by
   `waitBlobRemoval` is per-disk and per-transaction rather than re-read
   from the global server settings on every commit. This is what lets the
   stateless test exercise both `timeout > 0` and `timeout = 0` without
   touching server-wide config.

3. Stateless test `04301_blob_removal_wait_timeout.sh` that drives both
   directions through the failpoint:

   Test 1 (`wait_for_blob_removal_timeout_ms = 500`): after enabling the
   failpoint, `DROP TABLE SYNC` triggers `waitBlobRemoval`; with the fix
   the bounded wait returns within ~500 ms once the parked round fails
   to complete. A regression that ignored the deadline or dropped the
   `false` return from `triggerAndWait` would hang the DROP past the
   30 s `timeout` cap and the assertion would fail.

   Test 2 (`wait_for_blob_removal_timeout_ms = 0`): DROP runs in the
   background; `SYSTEM WAIT FAILPOINT ... PAUSE` deterministically
   synchronises on the killer having paused. After a 1 s sleep the test
   asserts the foreground DROP is still blocked (strict pre-fix
   semantics). `SYSTEM DISABLE FAILPOINT` releases the round and the
   DROP completes. A regression that treated `0` as "immediate timeout"
   would let the DROP finish before the failpoint is released.

The test uses `disk(type = 'object_storage', object_storage_type =
'local_blob_storage', metadata_type = 'local', use_fake_transaction = 0,
...)` so the commit path actually goes through `DiskObjectStorageTransaction`
rather than `FakeDiskTransaction` (which would short-circuit the entire
wait path being tested). Tagged `no-fasttest, no-parallel,
no-shared-merge-tree` because the failpoint is server-wide and inline
`disk(...)` is unsupported on SMT.

Verified locally with the fix in place:

- `DROP TABLE t_timeout_short SYNC` completes with the warning "Waiting
  for blob removal timed out after 500 ms (1 iterations, configured limit
  500 ms)" ~626 ms after the DROP, confirming the bounded wait path.
- `DROP TABLE t_timeout_zero SYNC` blocks until `SYSTEM DISABLE
  FAILPOINT`; commit log shows "Waiting for blob removal took 1186 ms"
  spanning the pause-and-release window, confirming the strict wait
  path.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…lock-blob-removal-timeout

# Conflicts:
#	src/Disks/DiskObjectStorage/DiskObjectStorage.cpp
#	src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp
@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI fully finished on HEAD 211a1ccaac8b98be5e032e5889c959f000311847 (Finish Workflow PASS at 2026-06-04T03:50:04Z, all blocking checks complete).

CI ledger for this SHA — every failure tracked, none PR-caused:

# Check Test Disposition
1 Integration tests (amd_tsan, 1/6) test_refreshable_mat_view_replicated/test.py::test_circular_dependencies_survive_restart Chronic flaky. CIDB 30d: 15 failures across 14 distinct PRs (incl. 1 master, 2026-06-02 20:59 UTC); affected PRs are unrelated to refreshable-MV or replicated-DB code paths. This PR touches BlobKillerThread / DiskObjectStorageTransaction only. Tracked in a new internal task.
2 CH Inc sync (job-level) Known fork/private-sync infrastructure step requiring manual intervention; orthogonal to PR content.

This PR's fix path (waitBlobRemoval deadline pushed into BlobKillerThread::waitRound + disk_object_storage_blob_removal_wait_timeout_ms server setting + wait_for_blob_removal_timeout_ms per-disk override + 04301_blob_removal_wait_timeout regression test) is unaffected by either failure. All bot inline-review feedback from 2026-05-30 plus the master-merge-conflict resolution (2026-06-03 merge commit 211a1ccaac8) are in this HEAD.

Awaiting bot re-review and @ Michicosun re-review on this SHA.

Session: cron:our-pr-ci-monitor:20260604-050120

…ck-blob-removal-timeout

Resolve conflict in src/Common/FailPoint.cpp: both branches appended a new
failpoint to APPLY_FOR_FAILPOINTS. Keep both blob_killer_thread_pause_in_run
(this PR) and mt_mutate_task_can_skip_conversion_to_nullable_force_null_column_desc
(master).

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

Copy link
Copy Markdown
Collaborator Author

CI finished on c1c2931aabb4 (the 2026-06-10 master-merge that resolved the FailPoint.cpp conflict). Finish Workflow, Mergeable Check and PR are all green.

One non-green check: CH Inc sync (FAILURE) - a CIDB log-export infra step that is orthogonal to this PR's diff (BlobKillerThread + DiskObjectStorageTransaction + ServerSettings + the 04301_blob_removal_wait_timeout regression test). It is tracked separately and is not caused by this change. CIDB shows zero test-level FAIL/ERROR rows on this head.

All 145 functional, stateless, stress, integration and unit jobs pass. The 2026-05-30 regression-test commit (d45c9e3d) is part of this merged head. Ready for re-review.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, a few questions:

If a transaction does not wait for the blob removal completely, does it affect the logical consistency? Is leaving some garbage in certain cases acceptable?

If an operation left some garbage, will it be cleaned up eventually?

The same two questions, if we interrupt blob removal on shutdown to prevent hanging for a long time.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, and more questions:

What is the actual reason for BlobKiller to exist - why don't we remove blobs synchronously like before, and why was it invented?

@groeneai

Copy link
Copy Markdown
Collaborator Author

The short answer to the consistency questions: the metadata transaction commits first, the blob wait happens after, so the timing of physical blob deletion never affects logical consistency. The only thing a not-fully-waited or interrupted removal can leave behind is unreferenced object-storage data (garbage), never a wrong/visible result.

Grounding in the code (this PR's HEAD):

Ordering. In DiskObjectStorageTransaction::commit() the metadata transaction commits at DiskObjectStorageTransaction.cpp:598 (metadata_transaction->commit(...)), and waitBlobRemoval(...) is called only afterwards at :607. By the time we are waiting, the committed metadata already does not reference these blobs.

Q1: transaction does not wait for blob removal completely

  • Logical consistency: not affected. The blobs being waited on are already unreferenced by committed metadata, so no reader can reach them whether we delete them now or in 1 second.
  • Is leaving garbage acceptable: yes. It is unreferenced storage (a cost/quota concern), not a correctness concern.
  • Eventual cleanup: yes. Blobs not removed within the budget stay in the metadata storage removal queue (InMemoryRemovalQueue). BlobKillerThread::run() reschedules itself after every round (BlobKillerThread.cpp:267-269, default interval 1s) and keeps retrying. A blob is recorded-as-removed only once it is gone from all locations (BlobKillerThread.cpp:200-206), so a partial or failed delete is naturally retried on the next round.

Q2: interrupting blob removal on shutdown

Two clarifications first:

  1. This PR's timeout bounds only the per-commit waitBlobRemoval path. It does not touch the killer's shutdown drain: BlobKillerThread::shutdown() still calls executeBlobsCleanup(/*max_to_remove=*/0, ...) with no deadline (BlobKillerThread.cpp:289-292), i.e. drain everything. And tables shut down before disks (Context::shutdown calls DatabaseCatalog::shutdown() at Context.cpp:972, disks at ~:1040), so under a normal shutdown no new removals are being issued by the time that final drain runs.

  2. With that in mind:

    • Logical consistency on shutdown: same answer, not affected. The metadata commit already happened; interrupted blobs are unreferenced.
    • Eventual cleanup on shutdown: depends on the path. In a normal shutdown the unbounded drain above empties the queue, so nothing leaks. In a crash / hard kill with blobs still only in the in-memory queue, whether they are recovered depends on persistent_removal_log:
      • It defaults to false (MetadataStorageFactory.cpp:138). With it off there is no orphan re-scan GC, so such blobs leak as unreferenced storage. The code is explicit about this window (MetadataStorageFromDisk.cpp:357: "Blobs are tracked in memory but may become orphaned on crash.").
      • With persistent_removal_log=true, every ADD/REMOVED is appended to .metadata/blobs_to_remove.log; on startup loadRemovalLog() replays it and re-queues anything still pending (MetadataStorageFromDisk.cpp:151-165), so the killer finishes the job after restart.

    This orphan-on-crash window for the in-memory queue is pre-existing and independent of this PR; the timeout added here does not widen it (it only ends a per-commit wait early, leaving the blob in the same queue the killer already drains).

Q3: why does BlobKiller exist, instead of synchronous removal like before?

It came in with the multi-location / replicated object-storage work ("sync disks", Mikhail Artemenko), which is why it lives under Disks/DiskObjectStorage/Replication/ and is driven by a ClusterConfigurationPtr. A blob can need deletion from several locations, and is only safe to forget once removed from all of them. What the code shows the async dedicated thread buys over a synchronous per-blob DELETE on the commit thread:

  • Decoupling: a slow or temporarily unavailable object store no longer blocks or fails the metadata transaction. Commit succeeds, removal is retried in the background (run() reschedule loop).
  • Batching: removals are grouped per location up to the S3 multi-delete limit (BLOBS_IN_TASK_HARDWARE_LIMIT = 1000, BlobKillerThread.cpp:61) and run in parallel via a thread pool, instead of one network round-trip per blob.
  • Retry / all-locations safety: failed deletes are kept in the queue and retried; recorded-removed only when gone from every location.

The slowness is observable via BlobKillerThreadRuns / BlobKillerThreadRemovedBlobs and DiskObjectStorageWaitBlobRemovalMicroseconds profile events, so masking is not silent.

The original design intent is best confirmed by the sync-disks author, but the above is what the current code structure implements.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged current master into the branch (HEAD is now 1730e14fb33) to refresh CI — the branch was ~2 weeks behind and its only red check was a known unrelated flake.

That flake — Stress test (arm_tsan) failing with Logical error: 'Unexpected exception in refresh scheduling' (STID 2508-3e7b), which surfaced as Cannot start clickhouse-server — is the chronic RefreshTask::doScheduling crash tracked in #106737. That issue was closed as completed on 2026-06-29 by #108441, whose fix is now in master and therefore included in this merge. So the fresh run should no longer hit it.

No code change in this merge: the net diff versus master is exactly the PR's 10 files (BlobKillerThread + DiskObjectStorageTransaction + the disk_object_storage_blob_removal_wait_timeout_ms server setting / per-disk wait_for_blob_removal_timeout_ms override + the 04301_blob_removal_wait_timeout regression test). Awaiting fresh CI and re-review.

@alexey-milovidov

Copy link
Copy Markdown
Member

CI on the fresh master merge (1730e14fb33) has finished its build/functional/integration/unit jobs (a handful of stateless/integration shards still running); the net diff versus master is still exactly this PR's 10 files. As predicted, the RefreshTask::doScheduling crash (#106737, fixed by #108441) did not recur. The only red checks are two unrelated, master-wide flakes:

  1. Stress test (arm_tsan) / Stress test (amd_tsan) — Hung check failed, possible deadlock found. This is the chronic hung-check flake (Hung check failed, possible deadlock found #107941): on master alone it fired 171 times in the last 7 days across 336 distinct PRs (CIDB), with arm_tsan/amd_tsan stress hitting it 9–16×/day. The hung thread in the dump is a fuzzer query-analysis thread (executeASTFuzzerQueries → QueryTreePassManager::run → InterpreterSelectQueryAnalyzer); this PR's synchronization code (BlobKillerThread, waitRound, waitBlobRemoval) does not appear anywhere in the thread dump, so the new condition-variable wait is not implicated.

  2. Stateless tests (arm_binary, parallel) — 03360_bool_remote. Failed once with UNEXPECTED_PACKET_FROM_SERVER (expected TablesStatusResponse, got ProfileInfo) — the well-known connection-establishment flake that hit 23 distinct tests, 51 times in 14 days (7 on master). The harness reran it and all reruns passed ("not reproducible"). It exercises remote(...) over system.one, with no overlap with the blob-removal path.

Neither failure touches the change. The deterministic regression test (04301_blob_removal_wait_timeout.sh, blob_killer_thread_pause_in_run failpoint) and all object-storage jobs are green. Ready for @Michicosun re-review on this SHA.

@Michicosun

Copy link
Copy Markdown
Member

this pr has no relation to hung queries, it is not needed, closing.

@Michicosun Michicosun closed this Jun 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, no objection to closing. Recording the reasoning for the record:

The hung-check failures currently firing on master are hung queries (the dumps show fuzzer query analysis: executeASTFuzzerQueries -> QueryTreePassManager::run -> InterpreterSelectQueryAnalyzer), which is a different mechanism from the shutdown-time MergeTreeCleanupThread -> waitBlobRemoval blocking this PR guarded against.

That shutdown symptom is also no longer active: of the 22 "Possible deadlock on shutdown" failures on master in the last 45 days, 0 implicate waitBlobRemoval / triggerAndWait / waitRound. The original signal was the April 2 master hits, which have not recurred. So the timeout is not guarding a live problem, and closing is the right call.

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 pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hung check failed, possible deadlock found

3 participants