Skip to content

Spawn background schedule pool threads lazily - #105066

Merged
alexey-milovidov merged 27 commits into
masterfrom
lazy-background-schedule-pool
Jun 30, 2026
Merged

alexey-milovidov merged 27 commits into
masterfrom
lazy-background-schedule-pool

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 15, 2026 •

Copy link
Copy Markdown
Member

Closes #85265.

The BackgroundSchedulePool previously created background_schedule_pool_size real OS threads (default 512) at first access of Context::getSchedulePool. Each one was parked on a condition variable for the lifetime of the server, reserving a GlobalThreadPool slot, a futex, 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_size threads (default 16) and spawns additional workers — up to the existing cap — when scheduleTask finds no worker parked in cv.wait and there is headroom. The same path applies to all five schedule pools wired through Context (main, buffer-flush, distributed, message-broker, and Iceberg).

The cap setting background_schedule_pool_size keeps 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 and GlobalThreadPool slot reservation on under-loaded servers; the BackgroundSchedulePoolSize metric intentionally continues to report the configured cap (so system.server_settings stays consistent with the user-facing setting), and behaviour at saturation is unchanged.

Changelog category (leave one):

  • Improvement

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

Threads in BackgroundSchedulePool are now created lazily on demand instead of all at once at server startup. A new server setting background_schedule_pool_initial_size (default 16) controls how many workers are pre-spawned; the pool grows up to background_schedule_pool_size when needed. Reduces idle thread count and GlobalThreadPool slot reservation on lightly-loaded servers. Closes #85265.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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. BackgroundSchedulePool now starts with an initial_size and grows lazily up to a max_size cap when runnable work exceeds parked (idle) workers.

This adds a new server setting background_schedule_pool_initial_size (default 16) and wires it through Context for all schedule pools (main, buffer flush, distributed, message broker, Iceberg). The existing background_*_schedule_pool_size settings are clarified as a cap (and the reported metric continues to reflect the cap), and tests are updated/expanded (including a new LazyGrow gtest) plus an integration config tweak to pre-spawn for saturation testing.

It also hardens scheduling and shutdown: scheduleImpl now resets scheduled on scheduleTask exceptions to allow retry, scheduleTask can roll back enqueues if worker spawn fails with an empty pool, and join() steals the thread list for joining without holding tasks_mutex.

Reviewed by Cursor Bugbot for commit 1c892d8. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.7.1.286 (included in 26.7 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f9aaa44]

Summary: ✅


AI Review

Summary

This PR changes BackgroundSchedulePool to pre-spawn only background_schedule_pool_initial_size workers and grow lazily up to the existing schedule-pool caps, with regression coverage for lazy growth and zero-initial cold start. The remaining issue is in the zero-initial failure path: the new first-worker spawn exception can still escape a destructor-based resume path.

Findings

⚠️ Majors

  • [src/Core/BackgroundSchedulePool.cpp:521] background_schedule_pool_initial_size = 0 is now a supported cold-start mode, but the 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.
    Suggested fix: 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.
Tests

⚠️ Add the smallest focused regression test that covers a zero-initial pausable task resume when the first worker spawn fails, or add an equivalent injection point around spawnThreadLocked so the destructor/cleanup path is proven not to terminate.

Final Verdict

Status: ⚠️ Request changes

Minimum required action: prevent the zero-initial first-spawn exception from escaping PauseHolder destructor cleanup, and cover that failure path if feasible.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 15, 2026
@alexey-milovidov alexey-milovidov added the memory When memory usage is higher than expected label May 15, 2026
Comment thread src/Core/BackgroundSchedulePool.cpp Resolved
alexey-milovidov and others added 2 commits May 16, 2026 22:36
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]>
Comment thread src/Core/BackgroundSchedulePool.cpp Resolved
Comment thread src/Core/ServerSettings.cpp Resolved
alexey-milovidov and others added 5 commits May 19, 2026 16:50
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.
Comment thread src/Core/BackgroundSchedulePool.cpp Resolved
Comment thread src/Core/BackgroundSchedulePool.cpp Resolved
Comment thread src/Core/BackgroundSchedulePool.cpp Resolved
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the three lazy-spawn corner cases raised in review (all in ac49623):

  1. Same-type burst growth (was line 442) — lazy growth used the count of distinct runnable task types, so a burst of same-type tasks (e.g. the same periodic task across many ReplicatedMergeTree tables, or many Kafka/ObjectStorageQueue consumers) stayed stuck at background_schedule_pool_initial_size. Growth is now driven by runnableTasksExceedLocked, which counts runnable tasks per group bounded by max_parallel_tasks_per_type. New LazyGrowSameTaskType gtest guards it.
  2. Cap increase does not drain queued demand (was line 346) — increaseThreadsCount now eagerly spawns workers for the runnable demand the old cap could not serve (best-effort), so a saturated pool starts using a raised cap immediately instead of on the next unrelated scheduleTask.
  3. Delayed thread survival (was line 469) — delayExecutionThreadFunction now catches a worker-spawn failure (only reachable with background_schedule_pool_initial_size = 0 and an exhausted global thread pool) and retries the task with a small backoff instead of letting the exception terminate the delayed thread, which would have stalled all future scheduleAfter tasks in that pool.

Built unit_tests_dbms and ran the BackgroundSchedulePool.* suite — all 6 tests pass (the new LazyGrowSameTaskType confirms all same-type tasks run concurrently).

CI failures are unrelated: FunctionsStress msan (key0->size() > i in FunctionsHashing.h) is the known flaky tracked by #104877; the perf-comparison entries (encrypt_decrypt_empty_string, hash_table_sizes_stats_small) flag both ::old and ::new, i.e. measurement noise.

Comment thread src/Core/ServerSettings.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 260 210 -19.2% <0.0001 PR only changes background schedule-pool thread spawning; Q4 aggregation hot path is untouched. -19% is run-to-run varia
⚠️ 15 not_sure 230 207 -10.2% <0.0001 Same off-path flag: lazy schedule-pool growth can't speed a SELECT/GROUP BY. -10% delta is noise, not a PR effect.

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
  • StressHouse run: 7f1c6ebd-fda9-4597-b816-99a4cacd3e50
  • MIRAI run: 5d9439f4-a4db-483e-8992-bdbdd696a315
  • PR check IDs:
    • clickbench_468266_1782799475
    • clickbench_468272_1782799475
    • clickbench_468282_1782799475
    • tpch_adapted_1_official_468290_1782799475
    • tpch_adapted_1_official_468302_1782799475

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate why FunctionsStress test has failed and send a fix in a separate PR.

@groeneai

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov, the FunctionsStress failure is the chronic Logical error: 'key0->size() > i' shape from FunctionsHashing.h — same one that's been firing across many unrelated PRs since 2026-05-30. CIDB 30-day cross-PR distribution:

  • 39 hits across 33 distinct unrelated PRs + 3 master hits (Stress test (experimental, serverfuzz, amd_msan) + Unit tests (asan_ubsan, function_prop_fuzzer)).
  • Both hits on this PR (commits f1bce0a 2026-06-02 msan and ac49623 2026-06-07 asan_ubsan) match the exact same key0->size() > i shape.
  • PR Spawn background schedule pool threads lazily #105066's diff (BackgroundSchedulePool lazy-spawn) has no touchpoint with FunctionsHashing.h.

Tracked under the FunctionsStress non-determinism umbrella Issue #104877 alongside the active sub-family workstreams (sub-family A — caseWithExpression / String↔FixedString cross-type — was fixed by Algunenano's merged PR #104858; sub-family B — roundDown NaN/denormal + array-lookup path + this key0->size() MSan invariant — is the surviving open workstream there). The Issue #104877 umbrella has fresh "fix this" directives (nikitamikhaylov 2026-06-04, you 2026-06-07T01:36:32Z), so the fix is being driven there. I'll cross-link from the umbrella once an investigation/fix PR for the key0->size() shape is opened.

alexey-milovidov and others added 2 commits June 8, 2026 15:43
… 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]>
@groeneai

Copy link
Copy Markdown
Collaborator

@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 background_schedule_pool_initial_size, default 16).

Baseline: freshly started server, 0 user tables, 0 queries (completely idle)

  • 651 OS threads, system.metrics.GlobalThread = 638, MemoryResident = 368 MiB, MemoryVirtual = 15.7 GiB.
  • About 7.9 GiB of that virtual size is pure thread-stack reservation: 650 stack VMAs at the 12.5 MiB RLIMIT_STACK.
  • Of the 638 global-pool threads, ~560 are BackgroundSchedulePool workers and 48 are MergeTreeBackgroundExecutor workers. On an idle server they are all parked on a condition variable, doing nothing.
  • jemalloc on the same idle server: allocated 182 MiB, resident 234 MiB, metadata 62 MiB, retained 101 MiB. Every parked worker still owns its tcache and contributes to per-arena fragmentation, which is the cost you described.

Per-pool status

Pool Type Cap (setting, default) Idle threads retained at steady state Spawn
GlobalThreadPool backing OS pool max_thread_pool_size=10000 up to max_thread_pool_free_size=1000 lazy
Background schedule (main) BackgroundSchedulePool background_schedule_pool_size=512 512 (all parked) eager
Buffer flush schedule BackgroundSchedulePool background_buffer_flush_schedule_pool_size=16 16 eager
Distributed schedule BackgroundSchedulePool background_distributed_schedule_pool_size=16 16 eager
Message broker schedule BackgroundSchedulePool background_message_broker_schedule_pool_size=16 16 eager
Iceberg schedule BackgroundSchedulePool small, lazy 0 until first Iceberg use pool created lazily
MergeTree merges/mutations MergeTreeBackgroundExecutor background_pool_size=16 16 eager
MergeTree moves MergeTreeBackgroundExecutor background_move_pool_size=8 8 eager
MergeTree fetches MergeTreeBackgroundExecutor background_fetches_pool_size=16 16 eager
MergeTree common MergeTreeBackgroundExecutor background_common_pool_size=8 8 eager
12 static pools (IO, BackupsIO, parts loading/cleaning, format parsing, prefixes deserialization, ...) StaticThreadPool various 0 (server initializes them with max_free_threads=0, see programs/server/Server.cpp:1680-1746) lazy
AsyncLoader (table loaders), prefetch, load marks, writer, FS readers ThreadPool various 0 to pool_size (released down to the pool's free limit) lazy

So at steady state the idle threads live almost entirely in three places: the GlobalThreadPool free reserve (up to 1000), the five eager BackgroundSchedulePool instances (~560), and the four eager MergeTreeBackgroundExecutor instances (48). The 12 StaticThreadPool instances are not hoarders: the server gives them max_free_threads=0 so they drop to zero after their work finishes.

Effect of this PR

BackgroundSchedulePool becomes lazy: each of the five pools starts at background_schedule_pool_initial_size=16 and grows to its cap on demand. On the idle server above that takes the schedule-pool resident count from ~560 down to ~64, i.e. roughly 640 -> 140 total resident threads at startup, with a proportional cut in stack reservation and jemalloc arenas. The 48 MergeTree executor threads are unchanged.

What this PR does not cover (the reclaim gap)

  1. No pool reclaims threads after a burst. BackgroundSchedulePool only grows; once it climbs toward the cap under load it never shrinks back, so a server that saw one spike keeps the threads forever. The same is true for the lazy ThreadPool-based pools whose max_free_threads equals their pool_size.
  2. The four MergeTreeBackgroundExecutor pools are still eager (one scheduleOrThrowOnError per slot in the constructor, setMaxFreeThreads(threads_count)), so they hold all 48 threads from startup regardless of whether any table needs merges.
  3. GlobalThreadPool keeps up to 1000 idle threads by default, independent of actual demand.

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

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Why did we add background_schedule_pool_initial_size as a session setting and immediately make it obsolete?
That is pointless - if an obsolete setting is added inside this PR, better not add it.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Agreed — there is no reason to add a brand-new setting only to immediately deprecate it. The sibling background_*_pool_size settings are deprecated session aliases only because they used to be real session settings before being moved to the server config; background_schedule_pool_initial_size was never a session setting, so the alias was pointless.

Removed in f46ce72:

  • the deprecated session alias in Settings.cpp (MAKE_DEPRECATED_BY_SERVER_CONFIG),
  • its entry in the settings_from_profile_allowlist in ServerSettings.cpp,
  • the SettingsChangesHistory.cpp registration.

The real server setting in ServerSettings.cpp is unchanged, and the integration test config that sets background_schedule_pool_initial_size at the top level (i.e. as a server setting) keeps working.

@groeneai

Copy link
Copy Markdown
Collaborator

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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Proven:

Screenshot_20260627_033128

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, there are some degradations reported by performance tests. Let's check and investigate each one.

@groeneai

Copy link
Copy Markdown
Collaborator

@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 clickhouse-local hitting Code: 241 ... MergeSortingTransform (RSS 42-53 GiB vs the 53 GiB cap) while sorting the full historical comparison set. That is a harness-side condition (same error fails perf jobs on many unrelated PRs this week), not the server under test.

Per shard, the single "changed" query:

Shard Query old/new Verdict
amd 1/6 group_by_consecutive_keys -1.128x speedup
arm 3/6 visit_param_extract_raw #1 153->182 ms noise (see below)
arm 4/6 clickhouse_local_startup -1.552x speedup
arm 5/6 insert_select_squashing_dynamic #1 120->133 ms noise (see below)

The two slowdowns are single high-side ::new outliers:

  • visit_param_extract_raw Repair subtree2 #1: 14d p50 old=new=147 ms, p10-p90 [142,158]. This run new=182 sits above p90 while old=153 is in band, and the identical query on amd was flat (130->129). visitParamExtractRaw over zeros() does no background scheduling.
  • insert_select_squashing_dynamic Repair subtree2 #1: 14d p50 old=120 / new=119 (new is median-faster), band [114,126]. This run new=133 is above p90, old=120 on the median, and the same query on amd was new-faster (120->115). It inserts into Null/Memory engines, so no MergeTree merges and no schedule-pool work.

The lazy-spawn change adds only a bounded runnableTasksExceedLocked() scan under the already-held tasks_mutex on the schedule path; neither flagged query touches that path.

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 ::new. (TrackedMemory +34% is an accounting shift, every real RSS metric drops.)

So: 2 speedups, 2 noise flags proven by 14d variance + cross-arch divergence, 0 regressions. No code change needed.

alexey-milovidov and others added 2 commits June 30, 2026 02:27
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the two remaining review threads on gtest_BackgroundSchedulePool.cpp — the AI review's "minimum required actions" (commit 2c91d0c2192):

  1. Zero-initial cold-start coverage. Added two focused bounded gtests with BackgroundSchedulePool::create(1, 0, ...):
    • ZeroInitialSchedule — schedules immediate work and asserts it runs, exercising the first-worker / threads.empty() spawn path in scheduleTask.
    • ZeroInitialScheduleAfter — reaches the same boundary through scheduleAfter, so the first scheduleTask is driven by delayExecutionThreadFunction (the path that catches and retries a first-worker spawn failure).
  2. Bounded LazyGrow wait. LazyGrow now uses the same wait_for(60s) + release-before-assert pattern as LazyGrowSameTaskType, so a lazy-growth regression fails the assertion instead of hanging the unit-test binary.

Built unit_tests_dbms (Debug) and ran the suite: all 8 BackgroundSchedulePool.* gtests pass, including the two new zero-initial tests (the log confirms Create BackgroundSchedulePool with 0 initial threads (grows lazily up to 1) for both).

Also merged master (f9aaa447bf3) to refresh the 250-commit-stale branch. The merge is clean (zero textual conflicts); the PR-specific core (BackgroundSchedulePool.cpp / .h) is byte-identical to the previous head — master never touched it.

CI triage of the previous head (b997bf1d), both reds unrelated to this PR:

  • Stress test (arm_msan) — Logical error: Not-ready Set is passed as the second argument for function 'A (STID 0250-4e52), tracked by open Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-4e52) #102803. The stack is entirely in the query pipeline (PipelineExecutor / CompletedPipelineExecutor); this PR touches only BackgroundSchedulePool. CIDB 30-day cross-PR distribution: 121 hits across 94 distinct PRs + 22 master hits (through today), i.e. a chronic master-wide flake.
  • CH Inc sync — the private upstream sync; prior runs failed only on flaky/infra private tests (none touching BackgroundSchedulePool). Re-runs against the refreshed head on this push.

runnable_task_types.pop_back();
group.runnable_list_pos.reset();
}
throw;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.50% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 225/261 (86.21%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 30, 2026
Merged via the queue into master with commit 2064bf0 Jun 30, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the lazy-background-schedule-pool branch June 30, 2026 13:55
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 30, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…schedule-pool

Spawn background schedule pool threads lazily
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

memory When memory usage is higher than expected pr-improvement Pull request with some product improvements 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.

clickhouse-local creates ~500 threads in BackgroundSchedulePool

4 participants