Skip to content

Do not run BlobKiller and BlobCopier threads for disks that never need them - #118662

Merged
alexey-milovidov merged 32 commits into
masterfrom
skip-blob-threads-on-plain-disks
Oct 20, 2026
Merged

alexey-milovidov merged 32 commits into
masterfrom
skip-blob-threads-on-plain-disks

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

BlobKillerThread and BlobCopierThread drain two queues that live in the metadata storage: the dead blobs, submitted for removal by a committed transaction, and the blobs that are still missing in some of the cluster locations. Only the local metadata storage ever fills them.

The plain and plain_rewritable metadata storages remove objects synchronously, right inside the metadata transaction, and the web and web_index ones are read-only, so for all of them both queues stay empty forever. The blob killer is enabled by default with a one second interval, so every such disk woke up a background schedule pool task once a second only to find nothing to do. That is pure overhead for a read-only MergeTree table on a plain_rewritable disk, and there is usually one such disk per table.

The metadata storage is now asked with the new hasDeadBlobsQueue and hasMissingBlobsQueue, and the thread never activates its background task when it answers false. Both default to true, so a metadata storage has to opt out explicitly; a cached disk delegates the copier answer to the storage it wraps, but keeps its own queue of dead blobs (to drop stale cache entries) unless the wrapped storage is read-only, or removes blobs synchronously over a read-only object storage. The threads themselves are still always created, so DiskObjectStorage::blob_killer and blob_copier are never null and every caller stays as it was.

triggerAndWait returns immediately for such a storage. It has to: the task is deactivated, so task->schedule() would do nothing and waiting for the round counter to advance would never return. SYSTEM WAIT BLOBS CLEANUP therefore keeps working on such a disk - nothing is deferred there, so it returns immediately.

Related: #119119

Changelog category (leave one):

  • Performance Improvement

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

Disks that keep their metadata in the object storage itself (plain, plain_rewritable) or serve it from a web server (web, web_index) no longer run the background blob cleanup and blob replication tasks, which had nothing to do there. Previously every such disk woke up a background task once a second, which was noticeable with many read-only MergeTree tables, each on its own plain_rewritable disk.


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

Version info

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

… need them

`BlobKillerThread` and `BlobCopierThread` drain two queues that live in the metadata storage: the dead
blobs, submitted for removal by a committed transaction, and the blobs that are still missing in some of
the cluster locations. Only the `local` metadata storage ever fills them.

The `plain` and `plain_rewritable` metadata storages remove objects synchronously, right inside the
metadata transaction, and the `web` and `web_index` ones are read-only, so for all of them both queues
stay empty forever. The disk created both threads anyway, and the blob killer is enabled by default with
a one second interval, so every such disk woke up a background schedule pool task once a second only to
find nothing to do. That is pure overhead for a read-only `MergeTree` table on a `plain_rewritable` disk,
and there is usually one such disk per table.

Ask the metadata storage with the new `hasDeadBlobsQueue` and `hasMissingBlobsQueue` and skip creating
the corresponding thread when it answers `false`. Both default to `true`, so a metadata storage has to
opt out explicitly. A cached disk delegates the answer to the storage it wraps.

`SYSTEM WAIT BLOBS CLEANUP` keeps working on such a disk: nothing is deferred there, so it returns
immediately.
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6895ed2]

Summary: ✅


AI Review

Summary

The PR avoids periodic BlobKillerThread and BlobCopierThread work on metadata backends without the corresponding queues, while retaining cache invalidation and cleanup waits. No actionable findings remain at 6895ed2430c7a0efd109c8cdbc803f179cd06b34; the earlier findings are addressed in the current code. All three added stateless tests pass in head CI. A review-time harness using the actual scheduling method bodies passed six focused scenarios covering batching, reloads, and late queue publication. Across 1,000 idle read-only cached disks and 60 simulated polling deadlines, cleanup rounds decreased from 60,000 to zero. This validates the scheduling reduction with modeled dependencies; it does not measure server CPU savings.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 7, 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.

Let's just check hasDeadBlobsQueue/hasMissingBlobsQueue in threads startup and applyNewSettings where the underlying task is being activated.

@clickhouse-gh clickhouse-gh Bot added the comp-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... label Sep 7, 2026
…n-plain-disks

# Conflicts:
#	src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.h
`BlobKillerThread` and `BlobCopierThread` were not created at all for a metadata storage that never
defers blob removal or replication, so `DiskObjectStorage::blob_killer` and `blob_copier` could be
`nullptr` and every use of them needed a check. As requested in the review, the pointers are never
null again; instead each thread asks its metadata storage whether the corresponding queue exists and
never activates its background schedule pool task when it does not. This is the only thing that costs
anything: an idle task woken up once a second.

`triggerAndWait` returns immediately in that case. It has to: the task is deactivated, so
`task->schedule()` would do nothing and waiting for the round counter to advance would never return.
`BlobKillerThread::shutdown` also skips the final explicit cleanup round, which had nothing to drain.
…tadata directory

The previous revision of the test defined the `local` metadata disk with `path = 'disks/05136_local_metadata/'`,
which is exactly where the `local` metadata storage puts its own files, and `CREATE TABLE` failed in the
Fast test with `filesystem error: in create_directory: No such file or directory`. `LocalObjectStorage::removeObject`
removes the now empty parent directories of a deleted blob, and its guard against removing the root of
the object storage itself compares a relative path against the canonicalized absolute root, so with a
relative `path` the root is removed too - taking the metadata directory of the disk with it.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118662&sha=d8d6ea69f9f711c6f44b66545c93334eae85a5cb&name_0=PR&name_1=Fast%20test
#118662
`MetadataStorageFromCacheObjectStorage::hasDeadBlobsQueue` delegated the answer to the storage it wraps,
which is wrong: the wrapper does not forward this queue, it has one of its own. Every `commit` and
`tryCommit` moves `underlying->getSubmittedForRemovalBlobs()` into `objects_to_remove`, and
`getBlobsToRemove` drains that local queue, so that `BlobKillerThread` drops the cache entries of the
removed blobs.

A cached `plain` or `plain_rewritable` disk therefore does need a running blob killer, and it is not only a
matter of wasted space: `areBlobPathsRandom` is `false` for those storages, so a new file reuses the path of
a deleted one and a stale cache entry would be read as its contents. With the delegated answer the queue
never drained, and `SYSTEM WAIT BLOBS CLEANUP` became a no-op on such a disk.

The wrapper now reports its own queue. A read-only storage never removes anything, so nothing is ever
queued for it and a cached `web` disk still gets no blob killer.
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6895ed243 with master 70906e3c6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 1d76716b7; 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

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fast test (arm_darwin) is red on 05076_error_trace_file_offsets, which is unrelated to this change: the test asserts on max(address_end) of system.symbols and is failing the same way on many unrelated pull requests today, as well as on master in Stateless tests (amd_release, parallel, 1/2). The fix is already open: #119136 stops indexing absolute ELF symbols as addresses, which inflated max(address_end) by a factor of about 1.7 million.

Both tests of this pull request passed in the same run: 05136_no_blob_threads_on_plain_disks and 05161_blob_killer_on_cached_plain_disk.

Related: #119136

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, please investigate this failure and provide a fix in a separate pull request; if a fix is already in progress, link it here.

Stress test (amd_debug) failed the No such key check, not a test: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118662&sha=7aa0289b631ca318a06313ff319abf1f1bc4b7cc&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

Code: 499. DB::Exception: The specified key does not exist. This error happened for S3 disk:
while reading key: 05104_s3_plain_rewritable_hard_links_test_z8h6c8p7f4q1/__root/mutation_9.txt
(comment: 05104_s3_plain_rewritable_hard_links.sh)

It is not caused by this pull request, which only stops a background blob removal task from running on plain_rewritable disks, where removal already happens synchronously inside the metadata transaction. The same test fails the same way on master and on unrelated pull requests:

when check PR key
2026-09-10 03:29 Stress test (amd_debug) 118662 __root/mutation_9.txt
2026-09-10 02:40 Stress test (arm_msan) 118230 __root/mutation_20.txt
2026-09-10 02:35 Stress test (arm_debug) 119098 __root/mutation_11.txt
2026-09-09 23:14 Stress test (amd_debug) master __root/mutation_5.txt

The shape of it: StorageMergeTree::loadMutations iterates the table directory and reads every mutation_*.txt it finds. On a plain_rewritable disk that listing comes from the in-memory metadata of the disk, so it can name a file whose object the writer has already pruned by then - 05104_s3_plain_rewritable_hard_links.sh creates the readonly reader table over the endpoint of a live writer table that has just run four mutations. I did not push a fix here because I cannot reproduce it locally (it needs S3 and the stress harness), and the right place to synchronize is that test, which belongs to the hard links feature.

I have found no open issue for it.

@groeneai

Copy link
Copy Markdown
Collaborator

Your loadMutations shape is right. Three things to add.

The remover, in that run. The stress harness disrupts itself: RandomDisruptor (ci/jobs/scripts/stress/stress.py) picks one of four disruptions every 3 s, one of which issues an internal KILL MUTATION. There, killMutation removed __root/mutation_5.txt and the test's own CREATE TABLE reader read it 63 ms later. Not clearOldMutations: finished_mutations_to_keep keeps its default of 100 and the test runner does not randomize it.

It needs neither S3 nor the stress harness, so it does reproduce locally. Use a plain_rewritable disk over object_storage_type = local with enable_hard_links = 1: a writer with table_disk = 1 and two applied ALTER ... UPDATEs, a readonly table over the same path, then DETACH the readonly table, KILL MUTATION one finished entry on the writer, and ATTACH it back. The readonly table caches the disk namespace in memory (the mechanism 04318_system_restart_disk_plain_rewritable documents), so it keeps listing an entry the writer has already deleted. On master that fails 3/3 with

Code: 107. ... Cannot open file .../__root/mutation_2.txt ... (in query: ATTACH TABLE reader)

which is the same statement and the same object as CI's 499; only the backend's error code differs. enable_hard_links = 1 is required, and that is why #110939 is the change that first exposed this: without hard links checkMutationIsPossible rejects mutations on such a disk, so no mutation_*.txt could exist there at all.

Where I put the fix, since you named the test. In StorageMergeTree::loadMutations plus a new deterministic test, rather than in 05104. DiskSelector::recordDisk deliberately permits a second plain_rewritable disk on an overlapping prefix when that disk is readonly, so with table_disk = 1 any readonly table shares a live writer's directory, while loadMutations assumes it owns a quiescent one. And independently of any race, it writes three times to that foreign directory (a CSN, plus removal of uncommitted and of tmp_mutation_* entries), each of which throws on a readonly disk with nothing concurrent at all. So an unreadable entry is now ignored only when the disk is readonly, the object is proven absent at the backend, and no active part of this table is below the mutation version; the last condition keeps a removed entry that an older part is still owed from turning the error into stale reads. If you would rather have this synchronized in 05104 instead, say so and I will do that.

The fix is in review and not open yet. I will link it here when it opens.

For prioritizing: my CI scan counts six occurrences of this shape in the 5.2 h after the first one, on amd_debug, arm_debug and arm_msan, on master and five pull requests, and none before 2026-09-09 23:14.

…n-plain-disks

# Conflicts:
#	src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.h
@groeneai

Copy link
Copy Markdown
Collaborator

Fix PR: #119154. It tolerates a mutation_*.txt entry that the owner removed between the directory listing and the read, when the disk is readonly and the object is proven absent at the backend, and it stops a readonly table from writing into a directory it does not own.

It is parked rather than in review: #119276 reverted #110939, so 05104_s3_plain_rewritable_hard_links is no longer on master and plain_rewritable rejects mutations again, which leaves both that test and the new one unreachable on this base. Once #119304 lands I will merge master and re-run CI there with the diff unchanged.

One gap in it, measured on that PR's own CI with the fix present in the build: a mutation that was killed before it had applied to every part leaves a readonly reader permanently unable to attach, and I did not find a reader-side predicate that is safe for that case. Traces and options are in #119154 (comment); my preference is to order the entry unlink after the mutate task's commit barrier, which makes the reader-side reconciliation sound.

Apologies for the late link.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM now. I didn't like the usage of LOG_INFO (instead of LOG_TRACE), but it was pre-existing.

@alexey-milovidov alexey-milovidov self-assigned this Sep 24, 2026
alexey-milovidov and others added 2 commits October 11, 2026 11:25
…he layer after a reload to `readonly`

`MetadataStorageFromCacheObjectStorage::hasDeadBlobsQueue` only told whether new dead blobs can be queued
from now on. If the wrapped disk was reloaded as read-only while `objects_to_remove` still had entries,
`BlobKillerThread` deactivated its task, skipped the final flush on shutdown, and the queue, which is not
persisted, was lost together with the cache invalidations for those blobs. Now a non-empty queue is always
reported, so it is drained first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hen the cache layer has no dead blobs queue

A cache layer over a disk reloaded to `readonly` reports no dead blobs queue of
its own once its in-memory queue is drained, but the wrapped disk may still have
pending removals. `SYSTEM WAIT BLOBS CLEANUP` on the cache disk must still wait
for the wrapped disk in that case.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/PRs/118662/81962ec6f9c0b0551a0308cba8a9a2f7778cbb2e/pr/ast_fuzzer_amd_release_oracle/fatal.log (AST fuzzer (amd_release, oracle): Identity WHERE (NOT(NOT p)) oracle mismatch on a cross join with singleValueOrNull) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is unrelated to this PR, which only changes disk blob background threads.

The other failure, AST fuzzer (amd_debug, targeted) with Cannot capture 2 column(s) because function indexHint has 0 arguments, is unrelated too and is addressed by #125150.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the same negative-zero hash-key defect as on #110626, and #115970 fixes it.

The shard query is SELECT (singleValueOrNull(cityHash64(l.id, r.id)), count()) FROM enc_l l, enc_r r WHERE l.f64a = r.f64a AND r.f64b > l.f64b on the 04533_ie_join_encoded_keys fixture, where 45 rows per table have f64a = -0. and 18/19 have 0.. singleValueOrNull is NULL on both sides; only count() differs. The reference plans f64a = f64a as a hash join key, while NOT(NOT p) stays a cross join with a filter. Counts with the CI release binaries and the job's settings:

build WHERE p (hash key) WHERE NOT(NOT p) full_sorting_merge
this PR, 81962ec6f9c0 3889 4633 4633
#115970, 20a7108c78e7 4633 4633 4633

With l.f64a != 0 added, both forms return 2829 on either build, so the whole difference is -0. vs 0. in the hash table. No separate PR is needed.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, @groeneai. The Identity WHERE (NOT(NOT p)) oracle mismatch is the negative-zero hash key defect, so I'm leaving it to the open #115970 and not making any change here.

The only red check at ab20de5, AST fuzzer (amd_debug) with Cannot capture 2 column(s) because function indexHint has 0 arguments, is fixed by #125150, which has since merged. I merged master to bring that fix in (8c65871). The PR's own diff is the same as before.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 All 12 red Performance Comparison shards at 8c65871 are infrastructure, not this PR: fetch_perf_report.py shows 0 faster / 0 slower across 7921 queries, and every shard fails only because the dashboard verdict was unavailable (the shard's results were not uploaded to CIDB ... LogCluster connection failed: ConnectionError), so the check fell back to flagging pre-existing "too long" tests. PRs run later the same day (e.g. #125668) pass all 12 shards. Merged the latest master (7679b46) to re-run CI; the merged tree builds cleanly.

alexey-milovidov and others added 2 commits October 14, 2026 17:40
… wake up on queued blobs

`BlobKillerThread` no longer deactivates its task when `hasDeadBlobsQueue` answers `false`. The task
stays active, is scheduled only when there may be dead blobs, and `run` stops rescheduling itself once
the queue is drained and nothing new can be queued (a cache layer over a `plain` disk reloaded as
read-only). `MetadataStorageFromCacheObjectStorage` calls a callback registered by the blob killer
after it queued the blobs of a committed transaction, so a commit that is still in flight during the
reload wakes the task up, and `SYSTEM WAIT BLOBS CLEANUP` can always schedule a round instead of
waiting on a deactivated task.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits October 15, 2026 17:15
…s are queued

The callback that `MetadataStorageFromCacheObjectStorage` invokes after queueing dead blobs called
`schedule`, which cancels an already delayed round, so every commit on a writable cached disk started
an immediate cleanup pass and bypassed the batching by `data_background_cleanup.interval_sec`. Use
`scheduleAfter(0, /*overwrite=*/ false)` instead: it wakes up an idle task (e.g. after a reload to
`readonly` stopped the polling) but keeps a pending delayed round as is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The callback of a cache layer used `scheduleAfter(0, false)`. When it fired
while a round was running, the task got `scheduled = true`, so the
`scheduleAfter(interval)` at the end of the round was a no-op and the next
round ran immediately, bypassing `data_background_cleanup.interval_sec`.

Now `BlobKillerThread` tracks whether it stopped rescheduling itself
(`polling_stopped`) under a mutex. The decision to stop at the end of a round
is taken under that mutex, and the metadata storage queues blobs before it
calls the callback, so a commit either makes `hasDeadBlobsQueue` answer `true`
for the round or wakes up the task after it stopped. While polling, the
callback does nothing and ordinary asynchronous removals stay batched.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master (6895ed2). The only red check at 1039a44 was CH Inc sync (build failed). In the private sync PR, only Build (amd_msan) failed: it ran for 272 s on a runner from the private-arm-large pool, while arm_msan and all other 22 builds passed, so this looks like infrastructure rather than this change. The new push re-triggers the sync CI. The changed translation units build locally on the merged tree. There are no unresolved review threads.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM again.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 20, 2026
Merged via the queue into master with commit ffddf87 Oct 20, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the skip-blob-threads-on-plain-disks branch October 20, 2026 20:06
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 20, 2026
thevar1able pushed a commit to actueleai/ClickHouse that referenced this pull request Oct 22, 2026
…` by time

Each query scanned the whole `text_log`, which exceeds the test's
`max_rows_to_read` on a server with a large `text_log`.

Related: ClickHouse#118662

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants