Skip to content

Do not keep waiting for blob removal when the object storage rejects removals - #120166

Closed
groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:blob-removal-wait-stop-on-failure
Closed

groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:blob-removal-wait-stop-on-failure

Conversation

@groeneai

@groeneai groeneai commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118757
Related: #118662

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 DROP/DETACH of a table or database blocking for minutes when the disk's object storage is unreachable. The best-effort wait for blob removal retried already-failing cleanup rounds, each paying the storage client's full retry budget; it now stops as soon as a round fails.

Description

From the Stress test (arm_tsan) hung check on #118757's head, unrelated to that PR (report): azurite refused connections 11 minutes before it tripped. c_stacktraces.log has 128 threads in waitBlobRemoval -> triggerAndWait, 17 asleep in the Azure SDK RetryPolicy::Send, and 19 MergeTreeCleanupThread tasks holding the exec_mutex that 2 DETACH DATABASE queries wait for in IMergeTreeCleanupThread::stop, one already cancelled at elapsed: 392.23.

Cause: waitBlobRemoval runs for (i < 100 && hasPendingRemovalBlobs(blobs)) triggerAndWait(); after the metadata transaction has committed. A failing round records nothing removed, so hasPendingRemovalBlobs never clears and the loop runs to the cap. The 100 bounds rounds, not time: at azure_sdk_max_retries=10 with backoff capped at 1s a round costs ~4.3s, so the cap is ~430s against the observed 392s. disk_transaction_wait_for_blob_removal defaults to true, so released users on Azure or S3 hit this in an outage.

Fix: triggerAndWait now reports whether a cleanup round succeeded while the caller waited, via a succeeded_rounds counter published before finished_rounds; waitBlobRemoval breaks and warns on false. The cap stays; no setting, no noexcept lost. commit and tryCommit share the loop; the signal is removeBlobsBatch's existing result, above the object storage, so every backend is covered. Measured on MergeTree part removal against a rejecting storage: 300 rounds before, 3 after; gtest over 100 vs 1-2.

DiskObjectStorage::startupImpl loops on blob_copier->triggerAndWait with no cap, one round per second: not implicated here, copier off by default, and I can extend the signal there on request. The uninterruptible deactivate that trapped the cancelled DETACH is untouched on purpose: polling it changes scheduling for every task and does not help a plain DROP. #118662 adds an early return at the top of triggerAndWait, overlapping this hunk: whichever lands second keeps that guard and returns true.

Prior art on this seam, including a reverted attempt (click to expand)

@ Michicosun wrote waitBlobRemoval in #100064 and built, reverted and replaced this family of fix on that branch on 2026-03-20: 3a7cf9d1d8ad "stop waiting on error" (16:03), bbadc1522478 reverting it with no recorded reason (17:02), then 133087f728b4 "limit wait rounds" (17:04), which is the i < 100 cap in master today. He also asked for changes on my #101680 ("a timeout would mask the underlying issue") and closed it as unrelated to hung queries.

Two differences matter. 3a7cf9d1d8ad defined a failed round as the round threw, which forced findBlobsToRemove, recordBlobsRemoval and removeBlobs to lose noexcept and rethrow. And that predicate would not have caught this failure: the Azure batch deletes fail without throwing out of the round, since removeBlobsBatch catches, counts BlobKillerThreadRemoveBlobsErrors and returns a bool that removeBlobs discards, so a round of 17 refused batches counts as a success and all 100 rounds still run. This change keys on exactly that discarded bool, keeps every noexcept, adds no throwing path, and keeps the cap.

On masking: this is not a timeout, so a slow but working storage is still waited on in full and only a round that could not remove what it selected ends the wait. The signature here is a hung query rather than slow deletion, and nothing becomes silent. BlobKillerThreadRemoveBlobsErrors and DiskObjectStorageWaitBlobRemovalMicroseconds still count it, removeBlobsBatch still logs the exception, and the new LOG_WARNING names the give-up. The wait is best-effort by construction: the metadata transaction commits first, the blobs are already unreferenced, and BlobKillerThread::run reschedules itself and retries the queue forever.


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

…removals

DiskObjectStorageTransaction::waitBlobRemoval runs

    for (size_t i = 0; i < 100 && metadata_storage->hasPendingRemovalBlobs(blobs); ++i)
        blob_killer->triggerAndWait();

after the metadata transaction has already committed, i.e. it is a best-effort
wait for physical deletion. When the object storage refuses removals,
removeBlobsBatch catches the exception, counts BlobKillerThreadRemoveBlobsErrors
and returns false; nothing is recorded as removed, so hasPendingRemovalBlobs
stays true for every waiter and the loop always runs its full 100 iterations.
The 100 bounds rounds, not time, and once a round costs seconds that bounds
nothing: with azure_sdk_max_retries=10 and the backoff capped at 1s a round
costs about 4.3s, so the cap is about 430s.

That is what the Stress test (arm_tsan) hung check on the head e261595 of
PR ClickHouse#118757 recorded after the local azurite emulator started refusing
connections. c_stacktraces.log has 128 threads in waitBlobRemoval ->
BlobKillerThread::triggerAndWait, 17 asleep in the Azure SDK RetryPolicy::Send,
19 MergeTreeCleanupThread tasks holding their BackgroundSchedulePool exec_mutex
across the whole wait, and 2 DETACH DATABASE queries blocked in
IMergeTreeCleanupThread::stop -> deactivate, which takes exec_mutex before
setting deactivated and so cannot return. hung_check.log shows one of them at
elapsed: 392.230509 with is_cancelled: 1, matching the arithmetic above.
disk_transaction_wait_for_blob_removal defaults to true and waitBlobRemoval is
present on the 26.6, 26.7 and 26.8 release branches, so a released user on Azure
or S3 sees DROP and DETACH block for minutes during any storage outage.

BlobKillerThread::triggerAndWait() now returns whether any cleanup round
succeeded while the caller waited: it snapshots a monotone succeeded_rounds
before trigger() and compares after waitRound(), ANDed with the wrapped (cache)
killer's verdict. succeeded_rounds is published before finished_rounds, both
seq_cst, so a waiter that observes its round finished necessarily observes that
round's outcome; neither atomic may be relaxed. A round counts as succeeded when
findBlobsToRemove did not fail, every removal batch was scheduled and reported
success, and recordBlobsRemoval did not fail. waitBlobRemoval breaks out of the
loop and logs a warning on false.

This is not a timeout: a slow but working storage is still waited on for as long
as it needs, and only a failing round ends the wait, so slowness is never masked.
The 100-round cap is kept, no setting is added, no ProfileEvent is added and no
noexcept is removed. Both callers of the loop, commit() and tryCommit(), are
fixed by construction, and the signal is taken from removeBlobsBatch's existing
result, above the object storage, so all backends are covered rather than Azure
alone. The blobs stay in the metadata removal queue and BlobKillerThread::run()
keeps retrying them, so abandoning the wait cannot affect logical consistency:
the metadata transaction has already committed and the blobs are unreferenced.

Prior art the change deliberately does not repeat. On the ClickHouse#100064 branch,
3a7cf9d "stop waiting on error" introduced this family, bbadc15
reverted it with no recorded reason 59 minutes later, and 133087f
"limit wait rounds" added the i < 100 cap that master carries today. That
version defined a failed round as "the round threw", which forced
findBlobsToRemove, recordBlobsRemoval and removeBlobs to lose noexcept and
rethrow, and it would not have caught this failure at all: the Azure batch
deletes fail without throwing out of the round, so a round of 17 refused
batches counted as a success there and all 100 rounds still ran. Keying on the
bool that removeBlobsBatch already returns and removeBlobs already discarded
avoids both problems.

DiskObjectStorage::waitBlobsCleanup() (SYSTEM WAIT BLOBS CLEANUP) ignores the
new result on purpose: its contract is that the expected blobs are cleaned up
once it returns, it holds no lock, and it runs a single round, so it carries no
100x amplification. BlobKillerThread::shutdown() is a single drain round and is
unchanged for the same reason.

Test: DiskObjectStorageTest.BlobRemovalWaitStopsWhenRemovalFails, added to the
existing suite over the local_blob_storage disk. A new REGULAR failpoint,
local_object_storage_fail_remove_object, throws in
LocalObjectStorage::removeObjectIfExists before the removal, so the object
survives and stays queued across rounds. The oracle is the
BlobKillerThreadRuns delta rather than elapsed time, because an
instantly-throwing failpoint completes all 100 rounds in about 160ms and any
time-based assertion would be vacuous; EXPECT_GT(errors, 0) is the anti-vacuity
arm and fails if the injection is never reached. Measured 105 rounds without
this change and 2 with it, 50/50 repeats stable. On the MergeTree part-removal
path, TRUNCATE of a 3-part table against a rejecting storage runs 300 cleanup
rounds without this change and 3 with it.
`DiskObjectStorageTransaction::waitBlobRemoval` and `BlobKillerThread::triggerAndWait`
described the wait's exit condition as a round that removed nothing, that is, as the object
storage rejecting removals. The implemented predicate is narrower: a round fails when any
removal batch was not scheduled or reported failure, or when `recordAsRemoved` failed, so a
round that removed 1599 blobs of 1600 and lost one batch also ends the wait. Both comments now
state that predicate. The declaration also states that `succeeded_rounds` is compared as a
snapshot, so a concurrent round's success can be attributed to a wait that did not observe
that round; this can only lengthen a wait, never end one early.

`disk_transaction_wait_for_blob_removal` promised that the server waits for background blob
removal to complete before acknowledging the operation. With the early exit that promise is
best-effort, so the `DECLARE` doc string says so. The generated page under `docs/` is left to
the documentation autogeneration workflow. No `SettingsChangesHistory.cpp` entry is added: no
value changed, and server settings are not recorded there.

`DiskObjectStorageTest.BlobRemovalWaitStopsWhenRemovalFails` asserted fewer than 20 cleanup
rounds, which also holds for nineteen failed rounds, about 82 s of the Azure retry budget in
the reported configuration. The bound is 8 now. An exact `rounds == 1` is not available on this
fixture: the disk's own cleanup round at startup can land inside the measured window, and it
counts as a succeeded round because it has nothing to remove, so the wait then runs a second
round. Measured over 50 repeats: 34 runs at 1 round, 16 at 2 rounds, with at least one removal
error every time. Without the fix the same test measures 110 rounds.

The failure this branch fixes is the `Stress test (arm_tsan)` hung check reported on
ClickHouse#118757 with the report
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118757&sha=e26159554835816190f768f5e176d644fe6be3b1&name_0=PR&name_1=Stress%20test%20(arm_tsan)
`BlobRemovalWaitStopsWhenRemovalFails` only observed that the wait ended and
that the injection was reached. It did not observe the retention that the
early return promises, so a build that abandoned the wait and also dropped the
blob from the removal queue - a silent object leak - passed the suite. The test
now asserts, under the injection, that the object is still in the storage, and
then that a later cleanup round removes it once removals work again.

Only `markAsRemoved` erases from `InMemoryRemovalQueue`, so a blob a failed
round wrongly recorded as removed leaves the queue for good. Measured with a
throwaway mutation that records a failed round's whole batch: the two existing
assertions still pass (1 round, 1 error) and only the new poll reddens, after
its full 100 s budget with the object still present.

The comment and the warning in `waitBlobRemoval` also claimed more than the
code does. `removeBlobs` erases the location of every task that reported
success and records every blob that lost its last location before returning
its verdict, so a round that failed one batch out of sixteen did make recorded
progress and an immediate retry can finish the remainder. Both texts now speak
only about the blobs that are still queued, and the warning no longer reports
`blobs.size()`, which is the count this transaction submitted rather than the
count still queued.
`BlobRemovalWaitStopsWhenRemovalFails` bounded the round count from above,
observed that the injection was reached, and observed that the blob stayed
queued. None of that observes a round running to completion inside the window
`removeFile` owns, so a build whose caller-side wait does not happen at all was
reddened only by the accident of the disk's own background round landing in that
sub-millisecond window. The test now also asserts a lower bound on the rounds
it measures.

The bound holds by construction: the blob is queued before the wait starts, so
the loop enters its first iteration and `triggerAndWait` schedules a round and
blocks until one finishes, and `executeBlobsCleanup` counts the round as its
first statement. A round that started before the counter was sampled cannot
have selected the blob, so it removes nothing, counts as succeeded and the loop
triggers a fresh in-window round. 70 runs measured 1 or 2 rounds and never 0.

Measured with a throwaway perturbation that returns from `waitBlobRemoval`
before its loop, leaving the fix in place: the wait measures 0 rounds and 0
errors, the new lower bound reddens, and the upper bound passes, since it cannot
see this build at all. With the three fix files reverted instead the verdict is
the mirror image: 103 rounds redden the upper bound while the lower bound
passes. The two bounds are independent, and together they state the contract as
a range.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 15, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex), four cold review rounds plus my own
each round: 7 gate findings and 3 fix rounds. Every finding that changed the PR or was refused is
listed.

# Sev Finding Verdict Evidence / action
1 ⚠️ The comment justifying the new break described the predicate as "a cleanup round that removed nothing", but a round is reported as failed when any batch or metadata step failed, so the sentence was false for a round that removed 1599 of 1600 blobs (DiskObjectStorageTransaction.cpp:62, BlobKillerThread.h:34) AGREE, fixed @ 6e2ccd4 Both comments now state the implemented predicate
2 ⚠️ The snapshot compare in triggerAndWait can attribute an earlier round's success to a later awaited round, so a failed round can still return true DISAGREE The interleaving is real; the consequence is not a defect. A round counts as succeeded only if every scheduled batch returned true and recordAsRemoved did not throw (BlobKillerThread.cpp:228-246), so with the storage refusing connections removeBlobsBatch fails for every batch (:158-163), the counter is frozen and the first failed round ends the wait. Elsewhere the next iteration re-samples the counter after the failed round published, so a second false positive needs a second concurrent success, which means blobs are being removed for this disk and waiting is correct. Worst case is one extra round against the ~430s removed. Associating the outcome with the awaited round needs a per-round result map and reintroduces a clobbering hole. The imprecision is documented at the declaration @ 6e2ccd4
3 ⚠️ The regression test asserted fewer than twenty cleanup rounds, although the contract is that the first failed round ends the wait AGREE in part, fixed @ 6e2ccd4 Bound tightened to 8 against a measured 109 rounds without the fix and at most 2 with it over 50 repeats. An exact rounds == 1 is not available on this fixture and I measured that rather than assuming it: on a quiet disk (interval_sec 3600) it still failed 23 of 50 runs, because the disk's own startup round can land inside the window and, having nothing to remove, counts as a succeeded round. Pinning it exactly would need the startup round drained before sampling, i.e. an accessor this change does not add. Not agreed on asserting the successful direction: with removals working the loop exits after one round on its hasPendingRemovalBlobs condition without consulting the new result
4 ⚠️ disk_transaction_wait_for_blob_removal still documented an unconditional wait ("waits for background blob removal to complete before acknowledging the operation") AGREE, fixed @ 6e2ccd4 The DECLARE doc string, which is the source of truth for the generated setting page, now describes the wait as best-effort and says the blobs stay queued
5 ⚠️ The test never observes the retention the change promises: a build that abandoned the wait and dropped the blob from the removal queue would pass AGREE, fixed @ bcf3a2a The claim is in the diff twice (the doc string and the new warning), so it is this change's to uphold. The test now asserts the object is still present while removals fail, and that a later cleanup round removes it once they work again. InMemoryRemovalQueue::takeFirst is a const peek and only markAsRemoved dequeues, so a wrongly recorded blob is never retried and that second assertion is what catches it; the mutation arm is recorded
6 ⚠️ The test asserted only an upper bound on cleanup rounds, so it did not pin that a round ran inside the caller's wait at all: a build whose wait is a no-op was reddened only by the background cleanup task being unlikely to land in the measured window AGREE, fixed @ 30ad570 Timing was doing work that an assertion should do, and none of the existing arms perturbed the wait itself, so this was measured rather than argued away. The test now also asserts at least one round, which holds because the loop's first iteration triggers a round and blocks until it finishes while BlobKillerThreadRuns is counted at the round's start. Proven by a new arm that makes the wait a no-op with the fix in place: only that assertion and the error assertion redden. Not agreed on isolating the background task instead, for the reason measured in row 3
7 ⚠️ The lower bound added in row 6 still cannot prove the caller-side wait ran, because an autonomous cleanup round can observe the newly queued blob, hit the injection, increment both counters and satisfy every assertion; quiesce and pre-drain the autonomous cleanup, or synchronise causally with the triggered round DISAGREE Fourth round on this family, so I measured the escape and both proposed remedies rather than arguing. The escape: the arm that makes waitBlobRemoval a no-op with the fix in place measured 0 rounds and 0 errors and reddened both counter assertions, so the coincidence this needs did not occur on the exact build it names. Its window is the metadata commit alone, well under a millisecond, against a round interval of 1s, and the same round must also select this blob, so it is under 1e-3 per run, while the contract the change actually makes is pinned in the other direction at 103 rounds against the bound of 8 (105, 110 and 103 on three trees). Remedy 1: the quiet fixture disk was built in round 1 and was verifiably quiet (its killer logs Scheduled after: 3599999 ms), and rounds == 1 still held only 27 of 50 runs, because the residual is the disk's own startup round. Remedy 1 plus a pre-drain does not close it either: trigger() goes through task->schedule(), so a round can be pending when triggerAndWait returns, which SYSTEM WAIT BLOBS CLEANUP states in its own comment where it calls the same method twice (InterpreterSystemQuery.cpp:1108-1111); an exact pin therefore needs a drain accessor added to production for a test alone. Remedy 2, holding the round to synchronise with it, parks a BackgroundSchedulePool worker for the length of an assertion, which I am not introducing into a shared gtest binary. Published as a known limitation instead: the round count is a two-sided bound, not an exact pin, and the residual is symmetric (about 1e-7 the other way, where an autonomous round selects the blob just before the sample and ends the wait at once). Happy to add the drain accessor and pin rounds == 1 if that trade looks better to you
8 💡 The same comment, and the new warning, still read as if a partially failed round made no progress, and the warning counts every submitted blob rather than the ones still queued AGREE, fixed @ bcf3a2a removeBlobs records the blobs that lost their last location before returning all_removals_succeeded && recorded (BlobKillerThread.cpp:229-246), so a retry can finish the remainder. Both texts now say only that another immediate retry pays the storage's full retry budget again, and the warning names no count
9 💡 The PR body quoted DiskObjectStorage::startup and a bare while (hasUnreplicatedBlobs(local)) triggerAndWait();, but the function is startupImpl and that loop paces itself at one round per second, which is what makes it a different shape AGREE, fixed in the PR body none
10 💡 #118662 inserts an early return at the top of BlobKillerThread::triggerAndWait, overlapping this hunk, which the recorded probe had understated AGREE, fixed in the PR body Linked, with the resolution the merge needs: whichever lands second keeps that guard and returns true
11 💡 The body defended the BlobCopierThread scope boundary but not the deactivate one, which is the mechanism that trapped the already-cancelled DETACH AGREE, fixed in the PR body Stated with the reason it is out of scope here: making that wait pollable changes scheduling for every task in the server and does not help a plain DROP on an unreachable disk, where no deactivate is involved
12 💡 The body pinned the without-fix gtest round count at an exact 109, which is the 100-round cap plus whatever background rounds land and measured 105, 110 and 103 across rounds AGREE, fixed in the PR body Now stated as over 100 against 1 to 2, which holds on every tree measured

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

One expected CI result, so it does not read as an unexplained red: Bugfix validation (unit tests)
reports ERROR here. It builds a merge-base binary with only the new test file overlaid, and that file
uses the failpoint this change adds, so the binary cannot link; the job classifies that as
inconclusive rather than a refutation and is non-blocking. The evidence it cannot produce was measured
locally instead: over 100 cleanup rounds without the fix, 1 to 2 with it.

Session id: cron:clickhouse-review-slot-8:20260915-102100

@clickhouse-gh clickhouse-gh Bot closed this Sep 15, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand: build/src/unit_tests_dbms --gtest_filter='DiskObjectStorageTest.BlobRemovalWaitStopsWhenRemovalFails'. Oracle is the BlobKillerThreadRuns delta (an elapsed-time oracle would be vacuous: an instantly-throwing failpoint completes 100 rounds in ~160 ms). Over 100 rounds without the fix (the 100 cap plus whatever background rounds land: 103 and 109 measured on two trees) against a bound of 8, and at least 1 round measured inside the wait itself; 50/50 repeats stable in both directions (1 round on 43 iterations, 2 on 7, at least one removal error on every one, never 0 rounds across 70 runs).
b Root cause explained? waitBlobRemoval loops for (i < 100 && hasPendingRemovalBlobs(blobs)) triggerAndWait(); after the metadata transaction has committed. A failing round records nothing as removed, so hasPendingRemovalBlobs never clears and the loop always runs to the cap. 100 bounds rounds, not time: at azure_sdk_max_retries=10 with backoff capped at 1s a round costs ~4.3s, so ~430s against the reported elapsed: 392.230509.
c Fix matches root cause? Yes, on the loop that is the defect. Not a timeout (no clock, no setting), not a widened bound, not a no-random-* tag, not a guard at the symptom. The 100-round cap is kept; the change only ends a wait that is provably making no progress. Consistency is unaffected: the metadata transaction has already committed, the blobs are unreferenced, and BlobKillerThread::run keeps retrying the queue forever.
d Test intent preserved / new tests added? New gtest in the existing DiskObjectStorageTest suite, and every assertion in it is individually load-bearing, each proven by its own perturbation: the upper round bound reddens with the fix reverted (103 vs 8), the lower round bound reddens when the caller-side wait is made a no-op (0 rounds measured, while the upper bound stays green there), the error count and the retention-under-injection poll redden with the injection removed, and the final retention poll reddens, and only it, when a failed round's blobs are recorded as removed (100 polls with the object still present). No existing test weakened, retagged, shrunk or relaxed; 28/28 of the owning suite and 164 across 7 suites still pass.
e Both directions demonstrated? Yes, at three layers. Unit: 103 rounds FAIL without the fix, 1 to 2 rounds PASS with it, 50/50 repeats stable; a build whose caller-side wait is a no-op also FAILS, so the measurement is pinned to the wait rather than to the background thread. Retention: the object survives the abandoned wait and a later round removes it, and the mutation that drops it from the queue FAILS. Engine, via TRUNCATE on a MergeTree over an object-storage disk (the incident's own clearPartsFromFilesystem -> IMergeTreeDataPart::remove -> commit chain): 300 cleanup rounds before (3 parts x the cap) vs 3 after, with the new warning appearing 3 times and 0 times respectively. Distinct Build IDs recorded per binary, and the final binary's ID re-asserted after every arm was reverted.
f Fix is general across code paths? Yes. The signal is removeBlobsBatch's existing bool, i.e. above the object storage, so Azure, S3, HDFS, local and the cache wrapper are covered by one change. Both callers of the loop (commit, tryCommit) are fixed by construction; a cache-wrapped disk's second killer has its verdict ANDed in; the two metadata legs that also leave a blob pending (findBlobsToRemove, recordBlobsRemoval) both mark the round not-succeeded, so a Keeper/metadata outage cannot spin either. SYSTEM WAIT BLOBS CLEANUP and BlobKillerThread::shutdown are deliberately unchanged (single round, no amplification, pinned behaviour); BlobCopierThread in DiskObjectStorage::startupImpl (whose wait paces itself at one round per second) is the closest structural sibling and is put to the reviewer as a question in the PR body.
g Fix generalizes across inputs (params/datatypes/wrappers)? No user-input surface is involved (no types, wrappers, parsing or settings matrix). The state space is the round outcome, and all three failure legs land on the same verdict: removal failure (measured), metadata-selection failure, recording failure. Boundary blobs_to_remove.empty() counts as succeeded, the conservative direction, verified by the healthy-storage arm exiting after 1 round. The counter can only over-report progress, never under-report, so a partial outage costs an extra round rather than an early exit.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or changed, so no SettingsChangesHistory.cpp entry; no format or serialization change; the new bool return is additive and the one caller that does not need it ignores it. A healthy storage takes the identical path. Durability is not widened in kind: giving up leaves blobs in the in-memory removal queue, exactly as the existing 100-round cap already does, and persistent_removal_log=true re-queues them on startup.
i Invariants and contracts preserved? Yes. triggerAndWait still triggers a round and waits for it on every path, including the new false return. The new ordering invariant, succeeded_rounds published before finished_rounds (both seq_cst), is stated at the write site, so a waiter that sees its round finished also sees its outcome; neither atomic may be relaxed. succeeded_rounds is monotone and never reset, so no per-round association is assumed. findBlobsToRemove, recordBlobsRemoval, removeBlobs and executeBlobsCleanup all keep noexcept and no new throwing path is added anywhere. The i < 100 cap and the loop-top hasPendingRemovalBlobs re-check are unchanged, so the break can only fire when the blobs are still pending and no round made progress.

Session id: cron:clickhouse-impl-slot-5:20260915-095500

@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9dfbd2f]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (arm_binary, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (arm_asan_ubsan, azure, sequential, 2/2) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (arm_binary, s3 storage, DBReplicated, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) FAIL
05339_iceberg_top_k_query_condition_cache FAIL cidb
01168_mutations_isolation_3 NOT_FAILED cidb

AI Review

Summary

This PR stops foreground blob-removal waits when cleanup makes no recorded progress, reducing repeated storage retries during outages. One concurrency defect remains: the new counters can classify a successful round as no progress and end a healthy wait prematurely.

Findings

⚠️ Majors

  • [P2] A successful cleanup round can end the wait prematurely — BlobKillerThread.cpp:424. run publishes succeeded_rounds before finished_rounds. A caller can snapshot the updated success count, then have trigger read the old completion count. After that same successful round completes, the unchanged success count makes triggerAndWait return false. For a removal spanning multiple rounds, waitBlobRemoval acknowledges the operation with blobs still queued even though cleanup is succeeding. Make publication and snapshot coherent so an awaited successful round cannot produce this false negative.
Tests
  • ⚠️ Add a deterministic regression for the publication interleaving above, with healthy cleanup requiring multiple rounds, and assert that the foreground wait continues. The new test exercises deletion failure only. A standalone Python model reproduces the counter interleaving, but it does not execute ClickHouse; no local ClickHouse build was available for an end-to-end reproduction.
Final Verdict

Status: ⚠️ Request changes. Correct the counter snapshot race and cover successful multi-round waiting with a regression test.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 15, 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.

NEVER add new fail points. Simplify the diff and tests.

@clickhouse-gh clickhouse-gh Bot added the comp-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... label Sep 15, 2026
{
/// Retrying immediately pays the storage's full retry budget again for a round that has
/// already failed. The blobs that are still queued stay queued for background removal.
if (!blob_killer->triggerAndWait())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

On cache-wrapped disks this new early-exit path also fires when the outer cache invalidation round fails, not only when the underlying object-storage deletion is stuck. DiskObjectStorage::wrapWithCache puts a MetadataStorageFromCacheObjectStorage layer on top, and that layer keeps objects_to_remove only in memory (startup()/shutdown() never persist or rebuild it). At the same time CachedObjectStorage still keys the filesystem cache by FileCacheKey::fromPath(object.remote_path), and cached plain_rewritable disks are a supported configuration.

That means one transient removeCacheIfExists exception now makes the foreground path give up after a single round; if the server restarts before the next background retry, the cache invalidation is lost permanently and the stale cache entry survives under the reused path key. Previously we kept retrying that local invalidation in the foreground up to the existing 100-round cap. Can we either keep the old retry behaviour for cache layers, or make the cache-layer removal queue durable before using false to abandon the wait here?

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.

The verdict is no longer per error. A round counts as progress when it removed at least one blob, so a transient removeCacheIfExists failure that still leaves other removals succeeding does not end the wait; only a round that removed nothing does. df5202f additionally stops an idle layer (empty queue, no error) from ending a wait that the other layer is still making progress on.

The durability point is real but pre-existing: the cache layer's objects_to_remove is an InMemoryRemovalQueue, and MetadataStorageFromCacheObjectStorage::startup()/shutdown() only delegate to the underlying storage, so a restart drops that queue on master too. The foreground path was already capped at 100 rounds, which is also a give-up. Making the cache-layer queue durable is a separate change from this one.

Review asked for no new fail point and a simpler diff and test.

The round outcome is now the number of blobs the round removed, which
executeBlobsCleanup already returns. findBlobsToRemove, recordBlobsRemoval and
removeBlobs keep their signatures and their noexcept, no round struct is needed,
and the predicate finally says what the comment claims: only a round that
removed nothing ends the wait. A round that removed some of its blobs and failed
on the rest keeps the wait going, which is what the previous "every step
succeeded" predicate got wrong. The fail point and its LocalObjectStorage
injection point are gone.

The test makes the object storage reject the removal without any production
code: the disk's only blob is replaced with a directory, so unlink fails with
EISDIR and every cleanup round for that blob ends in an error. Measured on this
tree: 1 round with the fix and 100, the whole budget, with the break reverted;
50 repeats measured 1 or 2 rounds with at least one removal error every time;
neutralising the injection alone reddens the removal-error assertion, so the
round bound cannot pass vacuously. DiskObjectStorageTest is 28/28.
A cache-wrapped disk runs a cleanup round per layer and waits for both, and the
two removal queues drain independently: MetadataStorageFromCacheObjectStorage
keeps its own queue and reports pending blobs for either. A layer whose queue is
already empty removes nothing without failing, so keying the round's outcome on
the removed count alone let such a layer end a wait that the other layer was
still making progress on. The queue size the round already samples separates the
two cases.

The test now also proves that the abandoned wait leaves the blob queued, which
is what makes it safe to stop waiting: after the wait it makes the blob
removable again and expects a later round to drain it. Measured: mutating
recordBlobsRemoval to record every blob instead of the fully removed ones leaves
the blob in the storage forever and reddens that assertion, and the round bound
still reddens at 100 rounds with the break reverted.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, done in 054e3d6 and df5202f on top of the reviewed head.

No new fail point. 054e3d6 reverts local_object_storage_fail_remove_object and its injection point in LocalObjectStorage::removeObjectIfExists. The test now makes the object storage reject the removal without any production code: it replaces the disk's only blob with a directory, so unlink fails with EISDIR and every cleanup round for that blob ends in an error.

Simpler diff. The round outcome is the blob count executeBlobsCleanup already returned, so findBlobsToRemove, recordBlobsRemoval and removeBlobs keep their signatures and their noexcept, and there is no round struct left. The PR is 5 files, +84/-5, down from 7 files, +123/-17. The predicate now also says what the comment claims: only a round that removed nothing ends the wait, so a round that removed most of its blobs and failed on the rest keeps waiting, which the earlier "every step succeeded" version got wrong.

One deliberate addition (df5202f): a round whose queue is empty removes nothing without failing, and on a cache-wrapped disk the two removal queues drain independently, so keying the verdict on the removed count alone let an idle layer end a wait that the other layer was still making progress on. The queue size the round already samples separates those two cases.

Measured on this tree: 1 cleanup round with the fix and 100, the whole budget, with the break reverted; 10 repeats gave 1 or 2 rounds with at least one removal error each; neutralising the obstruction alone reddens the error assertion, and recording every blob instead of the fully removed ones reddens the queue-retention assertion; DiskObjectStorageTest is 28/28. The Bugfix validation (unit tests) error I flagged earlier came from the test needing this PR's fail point, and it needs none now.

One thing I did not pin: a transaction submitting more blobs than metadata_request_size takes several rounds, and no test proves the wait keeps going through them. I can add that case if you want it.

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

Remove comments. If you need a comment for a function/method, it is badly designed.

Review asked for no comments: a function that needs one is badly designed. The
two things the removed comments recorded belong here instead of in the code.

succeeded_rounds is published before finished_rounds because waitRound wakes on
finished_rounds, so a waiter woken by that counter must already be able to read
this round's outcome. That is also the order of the earlier attempt at this fix
in 3a7cf9d.

A round whose queue was empty removes nothing without failing, which is why an
empty dead blobs queue counts as progress rather than as a rejected removal.

The bool that triggerAndWait returns is named where it is used, by the warning
logged next to it, rather than in a header comment.
It made the blob removable again and waited for a background round to drain it.
That races with the cleanup thread: LocalObjectStorage::removeObject returns
silently when the object is already gone, so a round landing between the rmdir
and the recreation of the blob dequeues it, and the recreated blob is then an
orphan that no round will ever remove. Measured 1 failure in 12 runs, each
spending the full 100 second poll before failing.

Nothing is recreated now. Removing the obstruction is enough for the next round
to drain the queue, and both properties the wait owes its caller are asserted on
the dead blobs queue rather than on the object listing: the blobs are still
queued when the wait gives up, and a later background round still removes them.

Measured on this tree: 20 of 20 runs pass in 1.1 to 2.1 s each, and neutralising
the obstruction reddens both the removal error assertion and the queued
assertion, so neither can pass vacuously. DiskObjectStorageTest is 28/28.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, comments removed: the diff adds no comment line now (2fff850). What they recorded is in that commit message instead, namely why succeeded_rounds is published before finished_rounds and why an empty queue counts as progress. The bool that triggerAndWait returns is named by the warning logged next to it rather than by a header comment.

Re-running the new test also found it flaky at 1 failure in 12 runs, so I fixed that in the same wave (af14366). LocalObjectStorage::removeObject returns silently when the object is already gone, so a cleanup round landing between the rmdir and the recreation of the blob dequeued it, and the recreated blob was then an orphan no round would remove. Nothing is recreated now: removing the obstruction is enough for the next round to drain the queue, and both assertions read the dead blobs queue instead of the object listing. 20 of 20 runs pass in 1.1 to 2.1 s each, where the failing poll used to cost 100 s. DiskObjectStorageTest is 28/28.

The change is 5 files, +74/-5, with BlobKillerThread.{cpp,h} at 16 changed lines.

`waitBlobRemoval` loops while `hasPendingRemovalBlobs` is true, that is while the
blobs are still on the metadata storage removal queue, but the round verdict was
computed from the physical delete count. The two observe different state.

`removeBlobs` counted blobs whose object storage delete did not throw, before
`recordBlobsRemoval` ran. `MetadataStorageFromDisk::recordAsRemoved` appends a
REMOVED entry to the removal log before erasing from the in-memory queue, so a
failing append leaves the blobs queued while that count stays positive. Retried
rounds then delete already missing objects, which `removeObjectsIfExist` reports
as success, so every round looked like progress and the foreground wait paid the
full 100 round cap again.

`recordAsRemoved` already returns how many blobs it took off the queue, and both
implementations return that exactly, under the same mutex `getBlobsToRemove`
takes. Propagate it instead of the delete count, so the verdict measures the
state the wait loop tests. A round whose recording failed also no longer earns an
immediate reschedule, which stops the background thread from hammering a failing
removal log.

Measured on the gtest fixture with the removal log append forced to throw:
104-107 cleanup rounds before, 1-2 after.

The setting text no longer describes which round ends the wait. A round can
delete blobs physically and still record none, and the local removal log can
throw after the in-memory queue was already updated, so any wording keyed on the
round outcome is wrong in one of those corners. What a user needs is that the
acknowledgement can precede the removal.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a8c68b5

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
Stress test (arm_asan_ubsan) / Cannot start clickhouse-server startup metadata load fails on ATTACH TABLE test_1.t_pfl_05079 (s AggregateFunction(quantile('0.5'), Float64)) with Code: 70, Cannot convert String to double, so the server does not come up after 11 attempts: the quantile parameter is written into the state type name in a form that cannot be parsed back #119810 (mine, open)
Stress test (arm_asan_ubsan) / Check failed the job-level roll-up of the row above (exit code 1) #119810 (mine, open)
Build profile diff CI logs cluster query failed: the has_pr_data read of binary_sizes raised, and the job treats a transient CI-logs-cluster read as a hard failure #120121 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

The failing ATTACH is a randomized stress-suite leftover table, not a table this branch creates; the other ten Stress test flavours are green on this commit. Mergeable Check and PR are the workflow aggregators of the rows above.

Session id: cron:our-pr-ci-monitor:20260915-230549

@Ergus

Ergus commented Oct 22, 2026

Copy link
Copy Markdown
Member

@groeneai merge changes from master and solve conflicts

Conflict in BlobKillerThread.cpp: master added an early return to triggerAndWait for a storage without a dead blobs queue; it now returns the wrapped killer's verdict, or true when there is nothing to wait for.

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

Copy link
Copy Markdown
Collaborator Author

Merged master in 9dfbd2f. The only conflict was in BlobKillerThread::triggerAndWait: master added an early return for a storage without a dead blobs queue, and it now returns the wrapped killer's result (or true when there is nothing to wait for). The unit tests of this PR and master's 05345_blob_killer_on_cached_readonly_plain_disk, which goes through that early return, pass on the merged build.

return true;
}

int64_t succeeded_before = succeeded_rounds.load();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Take a consistent snapshot of round completion and progress

A successful round can be reported as making no progress here. run increments succeeded_rounds before finished_rounds (lines 316–317). If it is preempted between those increments, this load captures the new success count, while trigger still reads the old completion count. The caller therefore waits for that same successful round, then returns false because the success count already equals succeeded_before. Sequential consistency permits this interleaving.

For example, with metadata_request_size = max_metadata_request_size = 100 and 200 pending blobs, the first round can record 100 removals, yet waitBlobRemoval logs no progress and acknowledges the operation with the remaining 100 still queued, despite no deletion or metadata error. This breaks the intended behavior of continuing to wait while healthy cleanup makes progress.

Please make the completion/progress publication and baseline snapshot coherent, and add a regression that exercises this interleaving with a successful removal spanning multiple rounds.

@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9dfbd2f47 with master bb55fa4bf (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 71b8c26a6; 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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9dfbd2f

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, sequential), (amd_debug, distributed plan, s3 storage, sequential), (arm_asan_ubsan, azure, sequential, 2/2), (arm_binary, sequential), (arm_binary, AsyncInsert, s3 storage, sequential), (arm_binary, ParallelReplicas, s3 storage, sequential), (arm_binary, s3 storage, DBReplicated, sequential) / 05339_iceberg_top_k_query_condition_cache master breakage, not from this PR (it changes blob removal waits only): the test failed on all 12 master commits from the #126987 merge 41d5f3406f9d until its revert, and the tested merge tree 657e187caed9 contains #126987 but not the revert #127378 (external, merged revert)
Mergeable Check, PR praktika rollups of the rows above #127378 (the owner of the rows above)
Sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261022-140011

return true;
}

int64_t succeeded_before = succeeded_rounds.load();

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.

With this a round that succeeds can still be reported as "no progress", which ends the wait while blobs are still being removed.

A run publishes its result with two separate atomic writes: succeeded_rounds.fetch_add, then finished_rounds.fetch_add.

triggerAndWait reads succeeded_rounds first and then finished_rounds inside trigger. If the waiter's reads land between the two writes then:

  1. run increments succeeded from S to S+1.
  2. The waiter reads succeeded_before = S+1.
  3. The waiter reads finished = F and sets expected = F+1, which is the round that just finished.
  4. run increments finished to F+1, so waitRound returns at once.
  5. The check S+1 > S+1 is false, so the call returns false.

Swapping the two writes does not fix it, because the waiter can then wake before the success count is visible. Replace the counter with the number of the last round that succeeded.

remove_tasks_pool.setMaxThreads(round_threads_count);
int64_t removed_blobs = executeBlobsCleanup(round_request_batch, round_blobs_in_task, remove_tasks_runner, cluster, metadata_storage, object_storages, log);
int64_t recorded_blobs = executeBlobsCleanup(round_request_batch, round_blobs_in_task, remove_tasks_runner, cluster, metadata_storage, object_storages, log);
succeeded_rounds.fetch_add(recorded_blobs > 0 || dead_queue_estimate == 0);

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.

The verdict comes from whichever round the waiter waits on, not from the waiter's own blobs.

{
if (!blob_killer->triggerAndWait())
{
LOG_WARNING(getLogger("DiskObjectStorageTransaction"), "Blob removal made no progress, not waiting for it anymore");

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.

This new warning does not say which disk it is about.

@Michicosun

Copy link
Copy Markdown
Member

Let's merge this, and we will stop waiting for object storage at all for removals.

#133235

@Michicosun Michicosun closed this Nov 20, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 20, 2026
Address the review of @Ergus on ClickHouse#120166.

`run` published a round's outcome with two separate writes, `succeeded_rounds`
and then `finished_rounds`. A waiter whose reads landed between them took the
new success count as its baseline and then waited for that same round, so a
round that removed blobs was reported as no progress and the wait ended early.
`run` now stores the number of the last round that succeeded before it stores
the number of the last finished round, and `triggerAndWait` compares that
number with the round it waited for.

`trigger` now waits for the next round to start instead of the next round to
finish. A round that is already running read the removal queue before the
caller queued its blobs, so its outcome said nothing about them. The round
that is waited for now always read the queue after the caller's blobs were
queued.

The warning that ends the wait now names the disk.

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

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. The three changes it asked for are on the branch in groeneai@8c3f2e5 (the number of the last succeeded round instead of the counter, the wait judged on a round that starts after the call, and the disk name in the warning), pushed before I noticed the close. Since #133235 replaces this PR, I am leaving it closed.

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-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants