Repository navigation
Do not create background schedule pools when reading system.background_schedule_pool - #111209
Conversation
…d_schedule_pool StorageSystemBackgroundSchedulePool::fillData called every getXxxSchedulePool() getter, and each pool is created lazily on first access. A read-only SELECT from the table therefore force-created any not-yet-created pool. Under a saturated global thread pool the BackgroundSchedulePool constructor cannot spawn its initial threads and calls abort(), so a benign read-only query could kill the server. The iceberg pool is the exposed one (created only by an active Iceberg table); it was added to fillData in ClickHouse#110172. Report the pools only if they already exist. Add getXxxSchedulePoolIfExists() for all six pools, guarded by a per-pool atomic flag set inside the existing callOnce initializer (acquire/release, no new lock). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 0 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck). No blockers, majors, or nits raised. Diff reviewed: 5 files, +101/-6 (the 3 source files + the regression test). Session id: cron:clickhouse-author-slot-1:20260721-091000 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-1:20260721-091000 |
|
cc @Algunenano @antaljanosbenjamin — could you review this? Reading |
|
Workflow [PR], commit [c33f691] Summary: ❌
AI ReviewSummaryThis PR removes the Findings❌ Blockers
Final VerdictChanges requested: the LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 353/386 (91.45%) · Uncovered code |
Algunenano
left a comment
There was a problem hiding this comment.
I understand the PR and like the change, but this does not fix the issue in https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111172&sha=12f6f37961f2de0a8877131cac110ed7906b053d&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29
It will happen in the same way if the pool is reached via the normal path: IcebergMetadata::IcebergMetadata. I don't think aborting the server when failing to initialize this pool, or similar ones not critical to the general behaviour of the server, is ok. Abort() should be used when the server cannot safely continue, which is not the case; in fact I'd argue that by aborting we are unsafely terminating and can cause more harm than good. We should tackle that too
BackgroundSchedulePool's constructor caught any failure to spawn its initial threads and called abort(). A transient CANNOT_SCHEDULE_TASK (the global thread pool momentarily saturated under stress) therefore killed the whole server. This is reachable from every lazy pool getter, e.g. IcebergMetadata creating the iceberg pool via getIcebergSchedulePool, and previously from a read-only SELECT FROM system.background_schedule_pool. Aborting is only appropriate when the server cannot safely continue, which is not the case here. The constructor now tears down any partially-spawned threads and rethrows, so the caller gets a recoverable exception instead of a dead server. Teardown reuses join(), made null-safe for the case where a worker spawn threw before the delayed thread was constructed; ~ThreadFromGlobalPoolImpl aborts on a still-joinable thread, so the join must run before the throw. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Agreed on both points. Pushed a follow-up commit that fixes the root cause: the One subtlety: Regression test ( I treated all these pools as non-critical (throw, do not abort). If you think a specific pool must still fail-fast, I can gate that. |
Internal second-model review (click to expand)Independent diff review before pushing. Findings triaged and adjudicated: 💡 Nits
No blockers or majors. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-0:20260721-122200 |
CI finish ledger - 9292274Every failure below has an owner. Only
Session id: cron:our-pr-ci-monitor:20260721-233000 |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…utex `Context::shutdown` clears the six background schedule pool members under `shared->mutex` and destroys the pools afterwards, while the accessors read the members with no lock. The non-creating `getXxxSchedulePoolIfExists` accessors returned a raw pointer keyed off an `atomic<bool>` that shutdown never cleared, so a peek could hand out a pointer to a pool about to be freed. The reference-returning `getXxxSchedulePool` getters have the same problem one level up: whatever lock the getter takes is released before the caller dereferences the returned reference, and four callers store that reference for their whole lifetime. Annotate the six members with `TSA_GUARDED_BY(mutex)` and make both families of accessors return `BackgroundSchedulePoolPtr`, read under the lock. Pools are still constructed outside the lock, since creating one spawns threads and can throw `CANNOT_SCHEDULE_TASK`, and published under it. The six `atomic<bool>` flags are gone: the lock plus a non-null `shared_ptr` is the created test. The annotation makes this compiler-enforced. Without it, dropping the lock from an accessor compiles cleanly; with it, `-Wthread-safety-analysis` rejects any unsynchronized access to these members. A deterministic regression test is not implementable in `gtest_context_race.cpp`: `ContextSharedPart`'s constructor terminates on a second instance in a process, so a test cannot build a private shared context, and the shared global one is used by many gtest files while `shutdown` is one-shot. Co-Authored-By: Claude Opus 5 <[email protected]>
`CtorThrowsInsteadOfAbortOnSpawnFailure` sets the fault probability to 1.0, so the very first spawn fails while `threads` is still empty and the constructor's `join()` teardown has nothing to join. Removing that `join()` call leaves the test passing, even though a failure on a later worker or on the delayed thread would abort during unwinding, which is the failure mode the teardown exists to prevent. Add a case that fails some spawns *after* at least one worker has started, so the teardown is exercised. Without the `join()` call this new case aborts the test binary rather than merely failing it. Co-Authored-By: Claude Opus 5 <[email protected]>
The motivation and the failure mechanism belong in the commit messages and the PR description, not repeated in the source. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review - adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 rounds, $28.94 total). Round 1 (commit
Round 2 (commit Round 3 (commit Session id: cron:clickhouse-premium-slot-26:20260727-092000 |
Three conflicts, all in schedule pool consumers, all resolved by keeping master's content and re-applying only this PR's accessor change (BackgroundSchedulePool & -> BackgroundSchedulePoolPtr, so . -> ->): - src/Disks/DiskLocalCheckThread.cpp: master rewrote the constructor (adds check_period.setConfiguration, task->deactivate() and a new destructor). Kept all of it. - src/Storages/NATS/StorageNATS.cpp and src/Storages/RabbitMQ/StorageRabbitMQ.cpp: master renamed the streaming callback streamingToViewsFunc -> threadFunc. Kept the new name; the old one no longer exists in either translation unit. Verified after the merge: the six pool members still carry TSA_GUARDED_BY(mutex), the constructor catch block still joins the already spawned workers before rethrowing, and every pool getter call site in src/ and programs/ uses the pointer form (per-file call counts match master exactly). Co-Authored-By: Claude Fable 5 <[email protected]>
The test only observed IcebergSchedulePoolSize, so reverting any of the other five accessors to a creating getter left it passing. Measured against a pristine master build, reading the table force-creates all six pools, and the general one alone spawns 512 threads. Snapshot every *SchedulePoolSize metric before and after the read instead. Verified by mutation: with getSchedulePoolIfExists() reverted to getSchedulePool(), the old test still passed while BackgroundSchedulePoolSize leaked to 512, and the new one fails on exactly that line. Co-Authored-By: Claude Fable 5 <[email protected]>
Plain clickhouse-local calls DatabaseCatalog::createBackgroundTasks for the DDL drop and reload tasks, which creates the general schedule pool, so the metric was already 512 before the query and the previous commit's assertion could not hold. Only a --path plus --only-system-tables run skips that. Use a fresh per-process path under CLICKHOUSE_TMP so the test stays safe to run in parallel with itself. Each of the six accessors was reverted to its creating getter in turn: every one is now caught. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Merged master (the branch had conflicted) and strengthened the regression test. Merge. Three conflicts, all in schedule pool consumers, all resolved by keeping master's content and re-applying only this PR's accessor change:
Verified after the merge: the six pool members still carry Test fix. The test only observed
It now snapshots every One class of residual paths, disclosed rather than fixed here. Besides the queued-worker teardown item I raised earlier, my own review of this merge found two more callers that hold an unmanaged resource across a lazy pool getter, so a rethrow would unwind past their cleanup: Neither is reachable, and neither is a regression: both use the general pool, and
Fixing these means reordering constructors in unrelated storage engines, which reads as outside the scope you set for this PR. Happy to do them here if you prefer, or in a follow-up. |
Internal second-model review adjudication (merge round: 3 + 1 + 2 findings)Gate B adjudication - merge round (HEAD 1e11034, master 4707138)Gate B: 3 findings, engine=codex, cost $17.94. 1.
|
| pool metric | fix (this branch) | pristine master (control) |
|---|---|---|
| BackgroundSchedulePoolSize | 0 | 512 |
| BackgroundBufferFlushSchedulePoolSize | 0 | 16 |
| BackgroundDistributedSchedulePoolSize | 0 | 16 |
| BackgroundMessageBrokerSchedulePoolSize | 0 | 16 |
| BackgroundStreamingSchedulePoolSize | 0 | 16 |
| IcebergSchedulePoolSize | 0 | 10 |
So the bug force-creates all six pools, not just iceberg, and the general pool alone
costs 512 threads - while the test only ever observed IcebergSchedulePoolSize.
Mutation proof of the blindness (build IDs recorded):
- Mutant: revert one accessor,
getSchedulePoolIfExists()->getSchedulePool()in
StorageSystemBackgroundSchedulePool.cpp(mutant build085e734af0ae3b).
Old test: PASSES (iceberg 0 -> 0) whileBackgroundSchedulePoolSizeleaks to 512.
Strengthened test: FAILS on exactly that line (after BackgroundSchedulePoolSize 512). - Restore: rebuilt bit-identically to
e7cb63a08f4ecf; strengthened test passes on the fix.
Fix: 04545_... now snapshots every %SchedulePoolSize metric before and after the read and
asserts all twelve values are 0.
Delta re-gate (HEAD 00af1a5) - 1 finding
4. all-pool-negative-fixture (major) - AGREE, FIXED. It caught a real bug of mine.
The gate was right and my own verification was wrong. I had measured the strengthened test
with clickhouse local --path=<tmpdir>, but the test invokes plain ${CLICKHOUSE_LOCAL}.
Run the way CI runs it, BackgroundSchedulePoolSize is 512 before the read, so the
committed test would have failed in CI on correct code.
Cause: LocalServer.cpp:1690-1694 / 1712-1723 calls
DatabaseCatalog::createBackgroundTasks() on the no---path and --no-system-tables
branches, and that unconditionally does getContext()->getSchedulePool()->createTask(...)
(DatabaseCatalog.cpp:267-270) for the DDL drop/reload tasks. Only the --path +
--only-system-tables combination takes the branch that skips it.
Measured (all runs on the fix binary e7cb63a08f4ecf):
| fixture | BackgroundSchedulePoolSize before |
|---|---|
plain clickhouse local (as CI runs it) |
512 |
--only-system-tables alone |
512 |
--path=<fresh> alone |
0 |
--path=<fresh> --only-system-tables |
0 |
Fix: the test now uses a fresh $CLICKHOUSE_TMP/04545_local_$$ path plus
--only-system-tables, and removes it on both ends. That keeps it parallel-safe
(@Avogar's rule) with no no-parallel tag: the path is unique per process.
Per-accessor mutation matrix - each of the six accessors reverted individually to its
creating getter, rebuilt, test run:
| mutated accessor | verdict |
|---|---|
getSchedulePool |
CAUGHT |
getBufferFlushSchedulePool |
CAUGHT |
getDistributedSchedulePool |
CAUGHT |
getMessageBrokerSchedulePool |
CAUGHT |
getStreamingSchedulePool |
CAUGHT |
getIcebergSchedulePool |
CAUGHT |
All six reverted at once (mutant 7b49f484d42e74) leaks every pool
(512/16/16/16/16/10) and is caught. Restore rebuilt bit-identically to e7cb63a08f4ecf
and the test passes.
Lesson recorded: a fixture flag I add for my own convenience (--path) can be the very
thing that makes a test look correct - always run the test through its real entry point.
Delta re-gate 2 (HEAD 47217fa) - 2 findings, both DISAGREE with evidence
Both are the same shape as findings 1 and 2: a caller that holds an unmanaged resource
across a pool getter, made theoretically observable because this PR turned the pool
constructor's abort() into a throw. Both are unreachable, and the reason is measurable.
5. filelog-inotify-fd-leak (blocker) - DISAGREE: unreachable, and master is not better
DirectoryWatcherBase opens inotify_fd at :62 and calls getSchedulePool() at :67,
closing the fd only in ~DirectoryWatcherBase (:584-590). The ordering is real.
It cannot fire:
- The getter it calls is the general pool, and
Server.cpp:3395
database_catalog.createBackgroundTasks()runs unconditionally during startup, before any
user table exists;DatabaseCatalog.cpp:267then does
getContext()->getSchedulePool()->createTask(... "DatabaseCatalogDropTableTask" ...).
So by the time anyFileLogtable can be created, the general pool is already constructed
and thecallOncelambda never runs again - the getter is a locked read that cannot throw
CANNOT_SCHEDULE_TASK. - Measured on a fresh server with zero user tables:
BackgroundSchedulePoolSize= 512
(all five non-Iceberg pools already up: 512/16/16/16/16, Iceberg 0), and
system.background_schedule_poolalready reports['streaming','schedule']. - If the general pool ever did fail, it fails during startup at
Server.cpp:3395, i.e. the
server does not come up at all - noFileLogtable creation is reachable. - On master the same failure calls
abort()inside the pool constructor, so the fd is not
closed there either; the process just dies one frame earlier. This PR does not regress it.
This PR's only change to the file is . -> -> on one line.
6. message-producer-start-failure-hang (blocker) - DISAGREE: same reason
AsynchronousMessageProducer::start acquires the pool at IMessageProducer.cpp:27 outside
its try (whose catch covers only initialize()), and finish() waits scheduled.wait(false)
at :39-56, which only :31-32 can signal. The reasoning about ExceptionKeepingTransform
routing cleanup to producer->finish is correct as written.
Unreachable for exactly the reason above: it is the general pool, already created at
server startup long before any NATS/RabbitMQ sink runs, so the getter cannot throw. This PR's
only change to the file is . -> -> on one line.
Class disposition
Findings 2, 5 and 6 are one pre-existing class: callers that hold an unmanaged resource
(a joinable thread, an fd, an unsignalled condition) across a lazy pool getter. None of them
is reachable today, none is introduced by this PR, and every one of them ends the process on
master too. Fixing them means editing constructors in unrelated storage engines, which the
task's own merge instruction forbids ("do not widen scope during a merge") and which is
outside @Algunenano's scope ruling (that ruling is about the pool accessor API and its
callers, all of which this PR does convert).
Disclosing the class to the reviewer alongside finding 1 rather than acting on it.
Both comments explained context that belongs here in the commit message rather than in the source. The header comment stated that BackgroundSchedulePoolPtr is declared in BackgroundSchedulePoolTaskHolder.h (rather than only in BackgroundSchedulePool.h) so that headers which hold a pool can do so without pulling in the full BackgroundSchedulePool definition. That is why the alias lives in this header; DNSCacheUpdater.h, StorageBuffer.h and DistributedAsyncInsertDirectoryQueue.h all already include it. The Context.cpp comment described the contract of the six ...IfExists accessors: they return the pool only if it has already been created and null otherwise, for callers that must observe the pools without creating them (the read-only system.background_schedule_pool table). They read under shared->mutex, which shutdown also holds while clearing the members, and they return a shared_ptr so the pool cannot be destroyed while the caller uses it. The TSA_GUARDED_BY(mutex) annotation on the six members is what enforces the locking part; it is checked by the compiler, so the comment added nothing a reader cannot get from the code. No logic changed: the diff is six deleted comment lines. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal review log for 271361f (comment removal round)Second-model review of the delta Verification on this head:
Pre-push gate PASS, 0 warnings. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 332/370 (89.73%) · Uncovered code |
CI finish ledger - 271361fCI is fully finished on this head and there is nothing to own: 174 check-runs, all completed, 0 This covers the head produced by the master merge plus the strengthened regression test, and the Session id: cron:our-pr-ci-monitor:20260728-223000 |
Algunenano
left a comment
There was a problem hiding this comment.
The code is good, but I'm in the process of adjusting the sync PR
Algunenano
left a comment
There was a problem hiding this comment.
@groeneai one concern about the locking in the schedule-pool accessors.
getSchedulePool() (and the other five get*SchedulePool() accessors) now acquire shared->mutex via SharedLockGuard before returning the pool:
BackgroundSchedulePoolPtr Context::getSchedulePool() const
{
...
SharedLockGuard lock(shared->mutex);
return shared->schedule_pool;
}This file already has around a hundred places that take shared->mutex exclusively (std::lock_guard/std::unique_lock) for unrelated bookkeeping, e.g. setExternalAuthenticatorsConfig. If any such call chain ever transitively reaches one of these six getters, the calling thread deadlocks, since SharedMutex isn't recursive.
This PR itself adds several new call sites that reach getSchedulePool()->createTask(...) from fairly deep in the call stack (ZooKeeper::init, NamedCollectionFactory::loadIfNot, ReplicasReconnector). Worth double-checking that none of their current or future callers ever hold shared->mutex at that point — it's an easy invariant to violate later without noticing.
Suggestion: give the six schedule-pool pointers (and their clearing in shutdown()) a dedicated mutex instead of reusing shared->mutex. That keeps this subsystem self-contained and removes the possibility of any caller holding the broader context mutex ever deadlocking against a nested schedule-pool lookup.
…mutex The six get*SchedulePool accessors took shared->mutex to publish and read the pool pointers. Context.cpp has around a hundred places that take that mutex exclusively for unrelated bookkeeping, and SharedMutex is not recursive, so any call chain that reached a getter while already holding it would deadlock. The accessors are reached from deep call stacks (ZooKeeper::init, NamedCollectionFactory::loadIfNot, ReplicasReconnector), which makes that an easy invariant to violate later without noticing. A dedicated schedule_pools_mutex keeps the subsystem self-contained and removes the possibility entirely rather than relying on no caller ever nesting the two. The clearing in shutdown moves to its own block under the new mutex. The TSA_GUARDED_BY annotations follow, so the lock discipline is checked at compile time.
|
Adopted the dedicated mutex: c0b6d97. On reachability today, since you asked to double-check the callers: I could not
Verified: server start, |
CI finish ledger - c0b6d97Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Gates: 175 check-runs, 0 queued or in progress; Not PR-caused, and no master merge is warranted to clear it: merging master would move the merge Session id: cron:our-pr-ci-monitor:20260803-180000 |
|
I'm fixing conflicts in private. Will merge once things are ok |
CI finish ledger - c33f691Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not PR-caused. This diff stops Session id: cron:our-pr-ci-monitor:20260804-160000 Edited to correct the commit hash in the heading. The hash first published here did not exist in the repository: the first 12 characters were right but the remainder was wrong, so the line named no commit at all ( Two follow-ups on the owners named above, both now out of date:
|
a179699
|
Could this PR get In a three-way merge of this PR onto the 26.7 tip, 47 of the 48 modified files apply cleanly. The only conflict is in 26.3 has the same lazy getters and the same constructor |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Failing to start a background schedule pool (for example the
icebergpool, under global thread pool exhaustion) no longer aborts the server: the error is now a recoverable exception. Readingsystem.background_schedule_poolalso no longer creates those pools as a side effect.Description
Two related fixes for a server abort reachable when a background schedule pool cannot spawn its initial threads (global thread pool saturated under stress). Report (arm_asan_ubsan, s3 stress, STID 4860-437b): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111172&sha=12f6f37961f2de0a8877131cac110ed7906b053d&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29
BackgroundSchedulePool's constructor caught any failure to spawn its initial threads and calledabort(), killing the whole server. Aborting is only appropriate when the server cannot safely continue, which is not the case for a schedule pool. The constructor now tears down any partially-spawned threads and rethrows, so the caller gets a recoverable exception. This covers every path that creates a pool, including the normalIcebergMetadatapath viagetIcebergSchedulePool(). Teardown reusesjoin()(made null-safe for the partial-construction case);~ThreadFromGlobalPoolImplaborts on a still-joinable thread, so the join must run before the throw.StorageSystemBackgroundSchedulePool::fillDatacalled everyContext::getXxxSchedulePool()getter, and each getter creates its pool lazily on first access, so a read-onlySELECT FROM system.background_schedule_poolforce-created any not-yet-created pool (notablyiceberg, added tofillDatain Document streaming pool in system.background_schedule_pool #110172). The system table now reports a pool only if it already exists via newContext::getXxxSchedulePoolIfExists()accessors (returningnullptruntil the pool is created), and never creates one.