Skip to content

Do not create background schedule pools when reading system.background_schedule_pool - #111209

Merged
Algunenano merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-system-background-schedule-pool-side-effect
Aug 7, 2026
Merged

Algunenano merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-system-background-schedule-pool-side-effect

Conversation

@groeneai

@groeneai groeneai commented Jul 21, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Failing to start a background schedule pool (for example the iceberg pool, under global thread pool exhaustion) no longer aborts the server: the error is now a recoverable exception. Reading system.background_schedule_pool also 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

  1. BackgroundSchedulePool's constructor caught any failure to spawn its initial threads and called abort(), 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 normal IcebergMetadata path via getIcebergSchedulePool(). Teardown reuses join() (made null-safe for the partial-construction case); ~ThreadFromGlobalPoolImpl aborts on a still-joinable thread, so the join must run before the throw.

  2. StorageSystemBackgroundSchedulePool::fillData called every Context::getXxxSchedulePool() getter, and each getter creates its pool lazily on first access, so a read-only SELECT FROM system.background_schedule_pool force-created any not-yet-created pool (notably iceberg, added to fillData in Document streaming pool in system.background_schedule_pool #110172). The system table now reports a pool only if it already exists via new Context::getXxxSchedulePoolIfExists() accessors (returning nullptr until the pool is created), and never creates one.

…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]>
@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; 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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local with no Iceberg tables: SELECT value FROM system.metrics WHERE metric='IcebergSchedulePoolSize' = 0, then SELECT FROM system.background_schedule_pool, then the metric again = 10 on unfixed master (10 == the fatal.log "Couldn't get 10 threads"), = 0 with the fix. Every run.
b Root cause explained? Yes. fillData calls all six getXxxSchedulePool() getters; each creates its pool lazily via callOnce. So a read-only SELECT force-creates any not-yet-created pool. Under a saturated global thread pool the BackgroundSchedulePool ctor cannot spawn its initial threads and abort()s (BackgroundSchedulePool.cpp:321) — server death. The iceberg pool is exposed because it is created only by an active Iceberg table; #110172 added it to fillData.
c Fix matches root cause? Yes. Removes the side-effect at the source: the system table now reports pools only if they already exist (getXxxSchedulePoolIfExists() → nullptr until created). Not a guard on the ctor abort (which is a legitimate fail-fast for pools that must exist).
d Test intent preserved / new tests added? Yes. New test 04545_... asserts the read does not create the iceberg pool. Existing 03745_... still passes (created pools are still reported). No test weakened.
e Both directions demonstrated? Yes. New test FAILS on the unfixed binary (iceberg_pool_after 10 != reference 0) and PASSES with the fix (clickhouse-test runner [ OK ]; 50/50 deterministic).
f Fix is general across code paths? Yes. Fixes the whole class: all six pools (schedule/buffer_flush/distributed/message_broker/streaming/iceberg) route through fill_if_exists over non-creating accessors, not just iceberg. The other five had the identical latent defect.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A (no columns/types/wrappers involved). The relevant input set — the six pools — is fully covered.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default, on-disk/wire/metadata format, or new data validation changed. Pure read-path: same rows for pools that exist; not-yet-created pools (which had 0 tasks → 0 rows) are simply omitted. No user-visible output change for real workloads.
i Invariants and contracts preserved? Yes. The non-creating accessor reads the pool pointer under an acquire load paired with a release store inside the existing callOnce initializer (happens-before honored, no torn read). No new lock; deliberately does NOT route through shared->mutex (non-recursive ContextSharedMutex, never taken on the create path, 47+ getSchedulePool callers → deadlock risk). Returned raw pointer follows the existing convention (the five sibling getters already return raw refs and fillData already derefs them without a shared_ptr copy). Pool-vs-shutdown lifetime is the same pre-existing accepted condition.

Session id: cron:clickhouse-author-slot-1:20260721-091000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @antaljanosbenjamin — could you review this? Reading system.background_schedule_pool currently force-creates any lazily-initialized pool (the iceberg one in particular) as a side effect, which under thread-pool exhaustion aborts the server in the pool constructor. This makes the table report pools only if they already exist, via non-creating getXxxSchedulePoolIfExists() accessors for all six pools.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c33f691]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: ColumnBLOB should be converted to a regular column before usage (STID: 3059-3284) FAIL cidb

AI Review

Summary

This PR removes the system.background_schedule_pool side effect and fixes the accessor lifetime race by returning BackgroundSchedulePoolPtrs, but it still does not fully deliver the promised "recoverable exception instead of abort" behavior for BackgroundSchedulePool construction. Under supported global-thread-pool queue settings, the cleanup path can still block instead of surfacing CANNOT_SCHEDULE_TASK, so I would not merge it as-is.

Findings

❌ Blockers

  • [src/Core/BackgroundSchedulePool.cpp:342] [dismissed by author -- https://github.com/Do not create background schedule pools when reading system.background_schedule_pool #111209#discussion_r3666946389] The constructor still routes spawn failures through join, but ThreadFromGlobalPoolImpl::join waits on state->event (src/Common/ThreadPool.h:390-400) and that event is only signalled from the queued job body after the worker actually starts (src/Common/ThreadPool.cpp:1269-1279). With thread_pool_queue_size > max_thread_pool_size (or 0), one earlier worker can be only enqueued when a later spawnThreadLocked throws, so this "recoverable exception" path can still hang indefinitely under saturation instead of returning CANNOT_SCHEDULE_TASK. Suggested fix: the teardown needs a way to cancel or distinguish never-started global-pool jobs before waiting on them; otherwise the PR still violates its main contract on supported settings.
Final Verdict

Changes requested: the system.background_schedule_pool fix looks correct, but the constructor change still leaves a supported configuration where the promised recoverable failure path blocks instead of throwing.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.80% -0.10%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 353/386 (91.45%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 21, 2026
@Algunenano Algunenano self-assigned this Jul 21, 2026

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

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed on both points. Pushed a follow-up commit that fixes the root cause: the BackgroundSchedulePool constructor no longer calls abort() when it cannot spawn its initial threads. It now tears down any partially-spawned threads and rethrows, so the failure is a recoverable CANNOT_SCHEDULE_TASK exception instead of server death. This covers the normal IcebergMetadata path (and any other lazy pool getter), not just the system table.

One subtlety: ~ThreadFromGlobalPoolImpl aborts on a still-joinable thread, so a naive throw would just abort during unwinding. The teardown (reusing join(), made null-safe for the case where a worker spawn throws before the delayed thread is constructed) runs before the throw.

Regression test (gtest_BackgroundSchedulePool) uses CannotAllocateThreadFaultInjector to force the spawn failure: on the old code it SIGABRTs the test runner, with the fix it throws CANNOT_SCHEDULE_TASK. The system-table side-effect guard from the first commit is kept.

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.

@groeneai

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

Independent diff review before pushing. Findings triaged and adjudicated:

💡 Nits

  • stale-abort-comments (consistency): AGREE. This PR changes the ctor from abort() to cleanup+rethrow, so the first-commit comments in StorageSystemBackgroundSchedulePool.cpp and the .sh test that described the ctor as "aborts the server" were stale present-tense rationale. Rephrased both to state the invariant (reads must not create lazy pools) without the stale abort claim, and shortened the gtest comment. Comment-only; all 9 BackgroundSchedulePool gtests and the .sh test still pass. Delta recheck: 0 findings.

No blockers or majors.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CannotAllocateThreadFaultInjector::setFaultProbability(1.0) forces the initial-thread spawn to throw CANNOT_SCHEDULE_TASK on demand. New gtest BackgroundSchedulePool.CtorThrowsInsteadOfAbortOnSpawnFailure: on the unfixed ctor it SIGABRTs the runner (exit 134), same LOG_FATAL message as the CI stress crash.
b Root cause explained? Yes. The BackgroundSchedulePool ctor caught any initial-thread spawn failure and did LOG_FATAL; abort(). A transient, recoverable CANNOT_SCHEDULE_TASK (global thread pool momentarily saturated under stress) therefore killed the whole server. This is reachable from every lazy pool getter, e.g. IcebergMetadata::IcebergMetadata -> getIcebergSchedulePool(), and (before #111209's guard) a read-only SELECT FROM system.background_schedule_pool.
c Fix matches root cause? Yes. The ctor no longer aborts: it tears down any partially-spawned threads and rethrows, so the caller receives a normal exception. Single point, covers all 6 pools and every trigger (system table AND normal path).
d Test intent preserved / new tests added? Yes. New gtest asserts throw-not-abort. All 8 existing BackgroundSchedulePool.* gtests still pass (the join() null-guard did not change success-path behavior). #111209's .sh side-effect test is kept and still passes (0->0).
e Demonstrated both directions? Yes. Baseline ctor: SIGABRT (exit 134). Fixed ctor: [ OK ], throws CANNOT_SCHEDULE_TASK. 50/50 repeat with --gtest_break_on_failure, none aborted. Build IDs recorded (.scratch/5050.log).
f Fix general, not a narrow patch? Yes. The fix is at the ctor (the shared failure point of all 6 schedule pools), not at one caller. Codebase grep confirms BackgroundSchedulePool is the only pool with this ctor-abort-on-creation pattern; no sibling site left unfixed.
g Generalizes across inputs/types? N/A. This is a control-flow/lifetime fix on the ctor failure path; no datatype/type-wrapper/argument matrix applies. Exercised for both initial_size>0 (worker spawn throws first, threads empty, delayed_thread null) via the fault injector.
h Backward compatible? Yes. No setting default, on-disk/wire/replication format, or metadata change. Behavior change is strictly: a non-critical schedule pool init failure now throws a catchable error instead of aborting the server (recoverable, strictly safer). No SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. Teardown reuses the existing, tested join() (set shutdown, notify, join+clear threads, join+reset delayed_thread), made null-safe for the partial-construction case. Post-state (shutdown==true, delayed_thread==null, threads.empty()) exactly satisfies the ~BackgroundSchedulePool chasserts, so the half-built object is cleanly destructible. callOnce does not set its flag when the lambda throws (retry-able); the _created flag stays false and the shared_ptr stays null, and the exception propagates out of callOnce before the getter's return *ptr deref.

Session id: cron:clickhouse-author-slot-0:20260721-122200

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9292274

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / "Got read request from replica for unknown stream" (STID 5217-5b3d) + Server died Chronic trunk parallel-replicas coordinator logical error. Not caused by this PR (diff is background-schedule-pool only). 39 hits across 38 unrelated PRs + master in the last 30 days. A full-effort fix task tracks this (escalated); upstream tracker #110518
Mergeable Check / PR Derivative aggregators reflecting the coverage-job failure above Same owner
CH Inc sync - CH Inc sync (private, not actionable)

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111209&sha=929227464f9736b3c0ed45adca0a72a20ab6d501&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29

Session id: cron:our-pr-ci-monitor:20260721-233000

@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

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
  • StressHouse run: 382d2fef-9093-41e4-922d-8ec028fd4afe
  • MIRAI run: dea832af-3687-43b4-96c4-0728151f5664
  • PR check IDs:
    • clickbench_34667_1786023910
    • clickbench_34673_1786023911
    • clickbench_34690_1786023910
    • tpch_adapted_1_official_34697_1786023910
    • tpch_adapted_1_official_34723_1786023910
    • tpch_adapted_1_official_34737_1786023911

Comment thread src/Interpreters/Context.cpp Resolved
groeneai and others added 3 commits July 27, 2026 11:48
…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]>
@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; 3 rounds, $28.94 total).

Round 1 (commit f68cef2, 46 files +169/-154): 4 findings - 1 AGREE (fixed), 3 DISAGREE with recorded evidence.

  • partial-spawn-test-liveness (major) - AGREE, fixed. The existing constructor test used fault probability 1.0, so the first spawn failed with threads still empty and the join() teardown was never exercised. Confirmed by mutation: deleting join() left that test passing. Added CtorJoinsPartiallySpawnedThreadsOnFailure; on the mutant it aborts (RC=134) while the old test still passes, which is the control proving the gap.
  • pool-publish-after-shutdown (blocker) - DISAGREE. Real mechanism, but byte-identical on master: extracting every Context::getXxxSchedulePool() const body and grepping for shutdown_called gives 0 hits at the merge base and 0 at HEAD. This change alters where the pointer is read, not when construction is allowed.
  • iceberg-positive-direction (major) - DISAGREE. Measured: stubbing the peek accessors to return null makes system.background_schedule_pool report no pools at all, so the existing 03745 test already fails on that implementation. The proposed Iceberg-specific phase needs object storage and is not implementable as a stateless test.
  • critical-category (nit) - DISAGREE. The abort() behind the original signal 6 was already removed by an earlier round of this PR; Critical Bug Fix is not selected proactively.

Round 2 (commit ea2ceef, test only): 0 findings.

Round 3 (commit 1230a9f, comment trim): 1 finding - queued-worker-join-deadlock (blocker), AGREE on the mechanism, deferred. Reported in the review thread rather than fixed silently: it concerns the previously reviewed join()-before-throw design, not this commit, and the remedy is a design question (no API exists to cancel an already-queued global job). Not reproducible with default settings, and a gtest cannot shrink GlobalThreadPool.

Session id: cron:clickhouse-premium-slot-26:20260727-092000

groeneai and others added 3 commits July 28, 2026 13:18
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

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:

  • DiskLocalCheckThread.cpp: master rewrote the constructor (adds check_period.setConfiguration, task->deactivate(), a new destructor). Kept all of it.
  • StorageNATS.cpp, StorageRabbitMQ.cpp: master renamed the streaming callback streamingToViewsFunc -> threadFunc. Kept the new name.

Verified after the merge: the six pool members still carry TSA_GUARDED_BY(mutex) (removing a lock from one accessor still fails the build with -Wthread-safety-analysis), the constructor catch still joins 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). No submodule pin drift.

Test fix. The test only observed IcebergSchedulePoolSize, so it was blind to five of the six accessors. Against a pristine master build, reading the table force-creates all six pools, and the general one alone spawns 512 threads:

metric this branch master
BackgroundSchedulePoolSize 0 512
BackgroundBufferFlushSchedulePoolSize 0 16
BackgroundDistributedSchedulePoolSize 0 16
BackgroundMessageBrokerSchedulePoolSize 0 16
BackgroundStreamingSchedulePoolSize 0 16
IcebergSchedulePoolSize 0 10

It now snapshots every %SchedulePoolSize metric before and after the read. It also needed a fresh --path plus --only-system-tables: otherwise LocalServer calls DatabaseCatalog::createBackgroundTasks(), which creates the general pool itself for the DDL drop/reload tasks, so the metric was already 512 before the query. Each of the six accessors was reverted to its creating getter in turn and every one is now caught.

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: DirectoryWatcherBase opens inotify_fd (:62) before calling the getter (:67) and closes it only in its destructor, and AsynchronousMessageProducer::start acquires the pool outside its try (IMessageProducer.cpp:27) while finish() waits on a scheduled flag that only the task body signals.

Neither is reachable, and neither is a regression: both use the general pool, and Server.cpp:3395 calls createBackgroundTasks() unconditionally at startup, which creates it via DatabaseCatalog.cpp:267 before any user table can exist. On a fresh server with no user tables I measured BackgroundSchedulePoolSize = 512 and all five non-Iceberg pools already up, so by the time a FileLog table or a message-queue sink runs, that callOnce lambda cannot run again. If the general pool ever did fail to start, it fails at Server.cpp:3395 and the server never comes up. On master the same failures call abort() inside the pool constructor, so nothing is cleaned up there either.

StorageNATS has the same shape one level up (its event_loop_thread starts at :141, before the pool at :158, and ~ThreadFromGlobalPoolImpl aborts on a joinable thread); StorageKafka already has the safe order (pool at :216, thread at :225).

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author
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.
GATE_B_DIFFSTAT: 50 files changed, +287/-113 == the PR change set (correct base).

1. queued-worker-join-deadlock (blocker) - DEFER, terminal, already public

Not a new finding. Identical id to the r3 finding on head 1230a9fd16c61a
(.scratch/gate-b-findings-1230a9fd16c61a.json holds exactly this id, and the JSON carries
prior_id: queued-worker-join-deadlock). Mechanism was verified in that round and
publicly disclosed to @Algunenano in reply discussion_r3657118125 with an explicit offer
to fix here or as a follow-up.

Status unchanged by this merge: needs thread_pool_queue_size > max_thread_pool_size
(defaults are equal, 10000/10000) so it has no repro, and the remedy is a design question
(there is no API to cancel a queued global job; a bounded wait would trade the hang for a
leaked joinable thread, i.e. reintroduce the abort this PR removes).

Awaiting the reviewer's call. Re-litigating it in a merge round would also violate the
task's own standing instruction not to widen scope during the merge.

2. nats-partial-construction-abort (blocker) - DISAGREE on severity, DEFER on scope

The mechanism is real: StorageNATS::StorageNATS starts event_loop_thread
(StorageNATS.cpp:141) before it requests the message-broker pool (:158), and
~ThreadFromGlobalPoolImpl aborts on a still-joinable thread (ThreadPool.h:384-388),
so a pool-create failure at :158 unwinds through that destructor.

But it is NOT a regression introduced by this PR, and not a blocker for it:

  • On origin/master the very same failure kills the process too, one frame earlier: the
    pool constructor's catch block is LOG_FATAL(...); abort();
    (origin/master:src/Core/BackgroundSchedulePool.cpp:310-321) and never returns to the
    NATS constructor at all. Both trees die; this PR does not make the NATS path worse.
  • The constructor ordering is entirely pre-existing - master has the identical sequence
    (git show origin/master:src/Storages/NATS/StorageNATS.cpp, lines 141 / 158-161). This
    PR's only change to that file is . -> -> on two getter calls.
  • The sibling engine already has the safe ordering: StorageKafka acquires the pool at
    StorageKafka.cpp:216 and starts cleanup_thread at :225, so NATS is the sole
    instance of the hazardous order and there is no class to sweep.

Fixing it means reordering a constructor in an unrelated storage engine. @Algunenano's
scope ruling of 2026-07-27 was "one PR which fixes all places ... focus on having the right
API and fixing all callers" - that is about the pool accessor API and its callers, which this
PR does convert. A NATS construction-ordering repair is a different defect that predates
this PR and survives it unchanged. Deferring, and disclosing it to the reviewer next to
finding 1 (same class: residual paths where a non-fatal pool failure still ends the process).

3. all-pool-negative-liveness (major) - AGREE, FIXED

Confirmed, and the real exposure is wider than the finding states.

Measured on the merged tree with clickhouse local, all six *SchedulePoolSize metrics
before/after reading the table:

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 build 085e734af0ae3b).
    Old test: PASSES (iceberg 0 -> 0) while BackgroundSchedulePoolSize leaks 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:267 then does
    getContext()->getSchedulePool()->createTask(... "DatabaseCatalogDropTableTask" ...).
    So by the time any FileLog table can be created, the general pool is already constructed
    and the callOnce lambda 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_pool already 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 - no FileLog table 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.

Comment thread src/Interpreters/Context.cpp Resolved
Comment thread src/Core/BackgroundSchedulePool.cpp Resolved
Comment thread src/Storages/NATS/StorageNATS.cpp Resolved
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal review log for 271361f (comment removal round)

Second-model review of the delta 47217fa..271361f: 0 findings (focus diffstat 2 files, 6 deletions; matches the intended change exactly).

Verification on this head:

  • Diff is six deleted comment lines, no logic. git diff shows only /// lines removed.
  • Rebuilt: Build ID e7cb63a08f4ecf to 93f1bf2650548.
  • The TSA_GUARDED_BY(mutex) guard is still load-bearing after the removal: dropping the lock from getIcebergSchedulePoolIfExists fails the build with Context.cpp:5490:20: error: reading variable 'iceberg_schedule_pool' requires holding mutex 'shared->mutex' [-Werror,-Wthread-safety-analysis]. Restore rebuilt to the same Build ID.
  • The constructor still logs, joins and rethrows; 0 abort calls remain in BackgroundSchedulePool.cpp.
  • 04545, 03745 and 03746 all pass on the Build-ID-verified binary.

Pre-push gate PASS, 0 warnings.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 78.40% 78.50% +0.10%

Changed lines: Changed C/C++ lines covered: 332/370 (89.73%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 271361f

CI is fully finished on this head and there is nothing to own: 174 check-runs, all completed, 0
failures
(156 success, 18 skipped), with both Config Workflow and Finish Workflow green. CIDB
returns no FAIL/ERROR row for this commit either.

This covers the head produced by the master merge plus the strengthened regression test, and the
subsequent comment-removal round.

Session id: cron:our-pr-ci-monitor:20260728-223000

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

The code is good, but I'm in the process of adjusting the sync PR

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

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

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Adopted the dedicated mutex: c0b6d97.

On reachability today, since you asked to double-check the callers: I could not
construct a live chain that holds shared->mutex and then reaches a getter. The
three sites reach them from config/startup or from a keeper callback, none of
which is under that lock; setExternalAuthenticatorsConfig and setUsersConfig
call into AccessControl, which does not touch a schedule pool. But your "easy
invariant to violate later" point stands regardless, and it is not a property I
can keep true by inspection: 108 exclusive acquisitions of shared->mutex in
this file against 64 call sites of the six getters across 39 files, and nothing
mechanical connecting the two. Removing the class is better than re-auditing it,
so I did not argue reachability.

schedule_pools_mutex now guards the six pointers, the publish inside each
callOnce, and the clearing in shutdown, which moved to its own block after
the shared->mutex section. No place takes both, so there is no ordering to get
wrong. TSA_GUARDED_BY follows the new mutex, so the discipline is checked at
compile time rather than by convention.

Verified: server start, SELECT FROM system.background_schedule_pool (still 3
pools, iceberg uncreated), 12 concurrent reads interleaved with 12
SYSTEM RELOAD CONFIG calls with no stall, clean shutdown, no exception in the
error log. The stateless test still matches its reference.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c0b6d97

Every failure below has an owner: a fixing PR (ours 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
Bugfix validation (unit tests) / (job-level, no test row) harness abort, not a test result: the job declines to produce a verdict with submodule state differs between the merge-base and the checkout across 11 paths (.gitmodules, contrib/{MeCab,StringZilla,aws-c-http,jwt-cpp,libarchive,libcotp,openssl,orc,sqlite-amalgamation,thrift}), and reports itself red. Base-branch motion, not this PR: every named gitlink is byte-identical at the merge base 47071389e917 and at this head, differing only from current master, and the merge-base..head compare is 50 files with zero contrib/ paths a fix task owns it (investigating at full effort - fixing-PR link to follow here)

Gates: 175 check-runs, 0 queued or in progress; Config Workflow and Finish Workflow both
completed successfully; the other two Bugfix validation halves (functional tests, amd64 and
aarch64) pass on this head.

Not PR-caused, and no master merge is warranted to clear it: merging master would move the merge
base and can re-trigger the same harness abort.

Session id: cron:our-pr-ci-monitor:20260803-180000

@Algunenano

Copy link
Copy Markdown
Member

I'm fixing conflicts in private. Will merge once things are ok

@groeneai

groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c33f691

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 (amd_tsan) / ColumnBLOB should be converted to a regular column before usage (STID 3059-3284) trunk logical error, 171 rows / 105 unrelated PRs / 16 master in 14d #111997 (mine, open)
Build (arm_release) / Post Hooks build-profile telemetry INSERT fails against the internal LogCluster endpoint; the check itself is success and non-gating #113009 (mine, open)

Not PR-caused. This diff stops system.background_schedule_pool from constructing the pools it
reads; the ColumnBLOB abort is the trunk block-marshalling unwrap gap and no frame of this change
appears in its stack.

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 (c33f691fd14e5c6ae4a0e39fbeff85d5aa38b8f9 returns HTTP 422 "No commit found for SHA"). The hash now shown is the head this ledger was actually measured against. No finding changes.

Two follow-ups on the owners named above, both now out of date:

@Algunenano
Algunenano added this pull request to the merge queue Aug 6, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Aug 6, 2026
@Algunenano
Algunenano added this pull request to the merge queue Aug 7, 2026
Merged via the queue into ClickHouse:master with commit a179699 Aug 7, 2026
177 of 179 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 7, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Could this PR get v26.7-must-backport? 26.7 branched off master on 2026-07-22, before this merged, and it still aborts the server when system.background_schedule_pool is read: Stress test (arm_debug) on 0a6ea43a, abort() in the BackgroundSchedulePool constructor, reached from StorageSystemBackgroundSchedulePool::fillData -> Context::getIcebergSchedulePool. 26.8 and newer already have the fix.

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 src/Core/tests/gtest_BackgroundSchedulePool.cpp: the neighbouring test ScheduleAfterHugeDelayDoesNotFire came from a later master change and is not on 26.7, so the resolution is to keep the two new tests and drop that one. The only 26.7 caller of the six pool getters outside this diff, StorageDistributed.cpp, passes the result straight to the queue constructor whose parameter this PR changes, so it needs no edit.

26.3 has the same lazy getters and the same constructor abort(), but CIDB has no occurrence of this signature there in the last 180 days, so I am only asking for 26.7.

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

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default 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