Repository navigation
Spawn background schedule pool threads lazily - #105066
Conversation
Previously, BackgroundSchedulePool eagerly created `background_schedule_pool_size` real OS threads at first access (default 512), each parked on a condition variable for the lifetime of the server. With the lazy growth, the pool starts with `background_schedule_pool_initial_size` workers (default 16) and spawns additional ones — up to the cap — when a task is scheduled and no worker is currently parked. The cap-only setting `background_schedule_pool_size` keeps its semantics for users who tuned it; what changes is that the cap now describes the maximum number of concurrently runnable tasks, not the number of pre-allocated threads. The same lazy-growth applies to all five schedule pools wired through `Context`: the main, buffer-flush, distributed, message-broker, and Iceberg pools. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Workflow [PR], commit [f9aaa44] Summary: ✅
AI ReviewSummaryThis PR changes Findings
Tests
Final VerdictStatus: Minimum required action: prevent the zero-initial first-spawn exception from escaping |
The previous lazy-spawning change accidentally repurposed the `CurrentMetrics::BackgroundSchedulePoolSize` family of metrics from the configured cap to the currently spawned worker count, which is read by `ServerSettings::dumpToSystemServerSettingsColumns` to populate `system.server_settings`. After the change, that table reported the runtime worker count (e.g. `16`) instead of the configured cap (e.g. `512`) on lightly loaded servers, breaking the `IncreaseOnly`-typed setting introspection. Restore the cap semantics: the metric is initialised to the configured size on construction, is no longer touched by lazy `spawnThreadLocked`, and is bumped to the new cap on `increaseThreadsCount`. The active worker count is still available internally via `threads.size()`. Also, the `test_replicated_merge_tree_thread_schedule_timeouts` integration test relied on `BackgroundSchedulePool` eagerly occupying `background_schedule_pool_size` slots in the global thread pool at startup, which made it cheap to saturate `max_thread_pool_size=300` with concurrent queries and observe `Cannot schedule a task` exceptions. With lazy spawning that pre-allocation is gone, so the test no longer sees any errors. Set `background_schedule_pool_initial_size` equal to the configured pool size in the test config to keep the test exercising its intended behaviour. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three fixes for the lazy `BackgroundSchedulePool` worker spawn introduced in this PR: 1. Fix a deadlock in `scheduleTask` when several tasks are enqueued in quick succession: the previous check `idle_threads == 0` could observe a parked worker that was already "claimed" by a prior `notify_one` (it had not yet acquired `tasks_mutex` to decrement `idle_threads`), so no extra worker was spawned for the new task and it sat in the queue. Compare against `runnable_task_types.size() > idle_threads` instead, which correctly accounts for the parked-but-claimed workers. This was the cause of the `BackgroundSchedulePool.LazyGrow` unit-test hang seen on `msan`. 2. In the spawn-fail catch handler, fail closed when `threads.empty()`. If `background_schedule_pool_initial_size = 0` and the very first `spawnThreadLocked` throws, there is nobody to wake; rethrow so the caller learns about the failure rather than orphaning the task. 3. Add `background_schedule_pool_initial_size` to `settings_from_profile_allowlist` in `ServerSettingsImpl::loadSettingsFromConfig` for consistency with the sibling schedule-pool settings. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When `scheduleTask` cannot spawn the very first worker thread (`background_schedule_pool_initial_size = 0` and `GlobalThreadPool` is saturated, for example), it now removes the task from `group.tasks` and, if the group has no other queued tasks, also drops the just-added entry from `runnable_task_types` before rethrowing. `scheduleImpl` resets `scheduled = false` in its `catch` so the early-return guard at the top of the function does not short-circuit a follow-up `schedule()` call. Together these make the throw path fully retryable: state is clean and the caller's next `schedule()` call will go through `scheduleImpl` normally instead of silently returning `true` while leaving the task orphaned in the queue with no worker to drain it.
Addresses review feedback on the lazy worker-spawn logic. `scheduleTask` decided whether to spawn an extra worker by comparing `runnable_task_types.size()` (the number of distinct runnable task *types*) against `idle_threads`. But a single task group can run up to `max_parallel_tasks_per_type` tasks concurrently, so a burst of same-type tasks — for example the same periodic task across many `ReplicatedMergeTree` tables in the main pool (where `max_parallel_tasks_per_type` is ~409), or many Kafka/`ObjectStorageQueue` consumers — kept `runnable_task_types.size()` at `1` and left the pool stuck at `background_schedule_pool_initial_size`, a regression versus the previous pre-spawned behaviour. Introduce `runnableTasksExceedLocked`, which counts runnable tasks per group (bounded by `max_parallel_tasks_per_type`) with an early exit, and drive the growth decision off it. Each `scheduleTask` still enqueues exactly one task and spawns at most one worker, so the change cannot over-spawn. Also make `increaseThreadsCount` consume already-queued demand: a saturated pool has no parked worker to wake and may see no further `scheduleTask` for a while, so a runtime cap increase previously took effect only on the next unrelated task submission. It now eagerly spawns workers for the runnable demand the old cap could not serve (best-effort, leaving lazy growth as the fallback if the global thread pool is momentarily exhausted). Add a `LazyGrowSameTaskType` gtest that schedules many tasks of one type and asserts they all run concurrently, which fails (times out) without this fix. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the three lazy-spawn corner cases raised in review (all in ac49623):
Built CI failures are unrelated: |
|
📊 Cloud Performance Report ✅ AI verdict: This PR changes how background schedule pools spawn worker threads (lazy growth up to a cap instead of pre-spawning all of them at startup) plus related shutdown/exception handling. That plumbing is not on the path any ClickBench SELECT executes, so it cannot plausibly speed up query execution. Both flagged improvements (Q4 -19.23%, Q15 -10.2%) sit entirely off the changed code and read as run-to-run variance rather than a real effect of this change, so both are downgraded to not-sure. No genuine performance shift attributable to this PR. clickbenchFlagged queries (2 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
@groeneai, investigate why FunctionsStress test has failed and send a fix in a separate PR. |
|
@alexey-milovidov, the
Tracked under the FunctionsStress non-determinism umbrella Issue #104877 alongside the active sub-family workstreams (sub-family A — |
… setting The new server setting `background_schedule_pool_initial_size` was added to the default-profile allowlist in `ServerSettings.cpp` but lacked the corresponding `MAKE_DEPRECATED_BY_SERVER_CONFIG` alias in `Settings.cpp` that all sibling schedule-pool settings have. Without it, configuring the setting via `profiles.default` is rejected by `UsersConfigParser::parseSettingsProfile` (through `AccessControl::checkSettingNameIsAllowed`), which only accepts built-in `Settings`/`MergeTreeSettings` names, making the advertised profile path unusable. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
@Algunenano Thread pool survey below. Measured on master HEAD (v26.6.1.1), which is the "without this PR" baseline since #105066 is not merged yet. The "with PR" figures are derived from the diff (lazy growth from Baseline: freshly started server, 0 user tables, 0 queries (completely idle)
Per-pool status
So at steady state the idle threads live almost entirely in three places: the GlobalThreadPool free reserve (up to 1000), the five eager Effect of this PR
What this PR does not cover (the reclaim gap)
I will open a tracking issue for the general "reclaim idle threads across all pools" work covering these three points (startup eagerness, post-burst reclamation, and the global free reserve), with the constraint you noted: do not join threads immediately since reuse is valuable, only trim a persistently large idle set. Will link it here once filed. Session: cron:clickhouse-worker-slot-0:20260622-093400 |
|
Why did we add |
…etting This PR introduced `background_schedule_pool_initial_size` as a server setting and, for consistency with the sibling `background_*_pool_size` settings, also registered it as a deprecated session-level alias via `MAKE_DEPRECATED_BY_SERVER_CONFIG`. But unlike those siblings — which are deprecated because they used to be real session settings before being moved to the server config — this setting is brand new and was never a session setting, so adding it only to immediately make it obsolete serves no purpose. Drop the deprecated session alias in `Settings.cpp`, its entry in the `settings_from_profile_allowlist` in `ServerSettings.cpp`, and the `SettingsChangesHistory.cpp` registration. The real server setting in `ServerSettings.cpp` is unchanged, and the integration test config that sets it at the top level (a server setting) keeps working. Address review: #105066 (comment) Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Agreed — there is no reason to add a brand-new setting only to immediately deprecate it. The sibling Removed in f46ce72:
The real server setting in |
|
Opened the idle-thread reclamation tracking issue: #108516 (covers all pools, with the master baseline numbers and the three concrete problems from the survey above). cc @Algunenano |
# Conflicts: # src/Core/BackgroundSchedulePool.h
|
@groeneai, there are some degradations reported by performance tests. Let's check and investigate each one. |
|
@alexey-milovidov Checked each flagged query on head 8e761e8. None is a real regression from this PR. The 4 failed perf jobs all fail at "Check Results", but each shard's aggregate Total ratio is ~1.00x and each reports exactly one "changed perf" query. The job FAIL itself comes from the report-builder Per shard, the single "changed" query:
The two slowdowns are single high-side
The lazy-spawn change adds only a bounded The memory metrics are the actual signal and match the goal: across the arm shards MemoryResident -41..-44%, VMNumMaps -51..-54%, MemoryShared -61..-65%, jemalloc.resident -36..-40% on So: 2 speedups, 2 noise flags proven by 14d variance + cross-arch divergence, 0 regressions. No code change needed. |
Addresses the two remaining review threads on `gtest_BackgroundSchedulePool.cpp` (the AI review's "minimum required actions"): 1. The zero-initial boundary was untested. `background_schedule_pool_initial_size` may be `0`, and `scheduleTask` has dedicated first-worker handling for the `threads.empty()` case, but the existing tests only exercised pools that start with at least one worker. Added `ZeroInitialSchedule` (immediate `schedule` path) and `ZeroInitialScheduleAfter` (delayed path through `delayExecutionThreadFunction`, which catches and retries a first-worker spawn failure). Both use `BackgroundSchedulePool::create(1, 0, ...)`, a bounded `wait_for`, and assert the scheduled work actually runs. 2. The `LazyGrow` wait was unbounded, so a lazy-growth regression would hang the whole unit-test binary instead of failing at the assertion. Switched it to the bounded `wait_for` pattern already used by `LazyGrowSameTaskType`, releasing the blocked tasks before asserting so `join` never deadlocks on a failure. All 8 `BackgroundSchedulePool.*` gtests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the two remaining review threads on
Built Also merged CI triage of the previous head (
|
| runnable_task_types.pop_back(); | ||
| group.runnable_list_pos.reset(); | ||
| } | ||
| throw; |
There was a problem hiding this comment.
background_schedule_pool_initial_size = 0 is now a supported cold-start mode, but this first-worker failure path can propagate through callers that cannot throw. A concrete path is ReplicatedMergeTreePartCheckThread::temporaryPause -> BackgroundSchedulePoolPausableTask::PauseHolder::~PauseHolder -> resumeImpl -> activateAndSchedule -> scheduleTask: if the global thread pool is exhausted while resuming the paused part-check task and no worker has been spawned yet, this exception leaves a noexcept destructor and terminates the server instead of failing closed.
Please make the pausable-task resume path catch/log and defer retry, or otherwise prevent the zero-initial first-spawn exception from escaping destructor/cleanup paths.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 225/261 (86.21%) · Uncovered code |
…etting This PR introduced `background_schedule_pool_initial_size` as a server setting and, for consistency with the sibling `background_*_pool_size` settings, also registered it as a deprecated session-level alias via `MAKE_DEPRECATED_BY_SERVER_CONFIG`. But unlike those siblings — which are deprecated because they used to be real session settings before being moved to the server config — this setting is brand new and was never a session setting, so adding it only to immediately make it obsolete serves no purpose. Drop the deprecated session alias in `Settings.cpp`, its entry in the `settings_from_profile_allowlist` in `ServerSettings.cpp`, and the `SettingsChangesHistory.cpp` registration. The real server setting in `ServerSettings.cpp` is unchanged, and the integration test config that sets it at the top level (a server setting) keeps working. Address review: ClickHouse#105066 (comment) Co-Authored-By: Claude Opus 4.8 <[email protected]>
…schedule-pool Spawn background schedule pool threads lazily

Closes #85265.
The
BackgroundSchedulePoolpreviously createdbackground_schedule_pool_sizereal OS threads (default 512) at first access ofContext::getSchedulePool. Each one was parked on a condition variable for the lifetime of the server, reserving aGlobalThreadPoolslot, afutex, a stack VMA, and a kernel TID — regardless of actual background load. A typical server uses only a handful concurrently.This PR makes worker creation lazy: the pool starts with
background_schedule_pool_initial_sizethreads (default16) and spawns additional workers — up to the existing cap — whenscheduleTaskfinds no worker parked incv.waitand there is headroom. The same path applies to all five schedule pools wired throughContext(main, buffer-flush, distributed, message-broker, and Iceberg).The cap setting
background_schedule_pool_sizekeeps its name and default, but its semantic shifts from "number of pre-allocated threads" to "maximum number of concurrent runnable tasks". This is observable only as a reduction in resident thread count andGlobalThreadPoolslot reservation on under-loaded servers; theBackgroundSchedulePoolSizemetric intentionally continues to report the configured cap (sosystem.server_settingsstays consistent with the user-facing setting), and behaviour at saturation is unchanged.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Threads in
BackgroundSchedulePoolare now created lazily on demand instead of all at once at server startup. A new server settingbackground_schedule_pool_initial_size(default16) controls how many workers are pre-spawned; the pool grows up tobackground_schedule_pool_sizewhen needed. Reduces idle thread count andGlobalThreadPoolslot reservation on lightly-loaded servers. Closes #85265.Documentation entry for user-facing changes
Note
Medium Risk
Changes thread-pool concurrency behavior by lazily spawning workers and adjusting scheduling/join paths, which can affect background task throughput and failure modes under load. Adds a new server setting and alters the semantics of existing pool-size settings, so misconfiguration could impact performance or startup latency.
Overview
Background schedule pools no longer pre-spawn all workers up to their configured size.
BackgroundSchedulePoolnow starts with aninitial_sizeand grows lazily up to amax_sizecap when runnable work exceeds parked (idle) workers.This adds a new server setting
background_schedule_pool_initial_size(default16) and wires it throughContextfor all schedule pools (main, buffer flush, distributed, message broker, Iceberg). The existingbackground_*_schedule_pool_sizesettings are clarified as a cap (and the reported metric continues to reflect the cap), and tests are updated/expanded (including a newLazyGrowgtest) plus an integration config tweak to pre-spawn for saturation testing.It also hardens scheduling and shutdown:
scheduleImplnow resetsscheduledonscheduleTaskexceptions to allow retry,scheduleTaskcan roll back enqueues if worker spawn fails with an empty pool, andjoin()steals the thread list for joining without holdingtasks_mutex.Reviewed by Cursor Bugbot for commit 1c892d8. Bugbot is set up for automated code reviews on this repo. Configure here.
Version info
26.7.1.286(included in26.7and later)