Repository navigation
ThreadPool: wake most recently idle worker thread (LIFO) when scheduling a job to reduce memory fragmentation - #100177
Conversation
When a new job is scheduled, the thread pool now wakes the most recently idle thread (LIFO order) instead of an OS-determined arbitrary thread. This concentrates work on fewer OS threads, which: 1. Reduces memory fragmentation from jemalloc per-thread caches (tcache). Previously, work spread across many threads caused each to accumulate its own allocator cache, leading to excessive memory retention (e.g. 26 GiB instead of 4-5 GiB for two-level GROUP BY queries). 2. Improves CPU cache locality, as recently-active threads have warmer caches. 3. Allows excess idle threads to be naturally freed by the existing `max_free_threads` mechanism, releasing their allocator caches. Implementation: each worker thread now has a per-thread condition variable. Idle threads push themselves onto a LIFO stack and wait on their individual CV. The scheduler pops the most recently idle thread and signals it directly. The shared `new_job_or_shutdown` condition variable is removed. #10818 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Workflow [PR], commit [6555f83] Summary: ✅
AI ReviewSummaryThis PR changes Final VerdictStatus: ✅ Approve No required actions. |
|
Surprisingly, it shows benefits (more than 2x) in at least one test... |
|
It is also faster on at least one test. |
…CATIONS_IN_SCOPE` The worker function runs under `DENY_ALLOCATIONS_IN_SCOPE`, but `idle_thread_stack.push_back(this)` can trigger a `std::vector` reallocation. Fix by pre-reserving capacity to `max_threads` in the constructor and in `setMaxThreads` when it increases. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…CATIONS_IN_SCOPE` The worker function runs under `DENY_ALLOCATIONS_IN_SCOPE`, but `idle_thread_stack.push_back(this)` can trigger a `std::vector` reallocation. Fix by pre-reserving capacity to `max_threads` in the constructor and in `setMaxThreads` when it increases. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…eads)` The `idle_thread_stack.reserve(max_threads)` call in the `ThreadPoolImpl` constructor caused a ~24 GiB memory tracker drift during server startup. The 80 KB allocation (10000 pointers for the GlobalThreadPool) triggered a jemalloc allocation path change that caused subsequent allocations to be tracked without corresponding frees being tracked, leading to `MEMORY_LIMIT_EXCEEDED` errors in CI before the MemoryWorker could correct the tracker. Fix: remove the pre-reserve calls and instead use `ALLOW_ALLOCATIONS_IN_SCOPE` around the `push_back` in the worker function. The vector will grow naturally with amortized O(1) push_back, and the rare reallocations are explicitly allowed. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…eads)` The `idle_thread_stack.reserve(max_threads)` call in the `ThreadPoolImpl` constructor caused a ~24 GiB memory tracker drift during server startup. The 80 KB allocation (10000 pointers for the GlobalThreadPool) triggered a jemalloc allocation path change that caused subsequent allocations to be tracked without corresponding frees being tracked, leading to `MEMORY_LIMIT_EXCEEDED` errors in CI before the MemoryWorker could correct the tracker. Fix: remove the pre-reserve calls and instead use `ALLOW_ALLOCATIONS_IN_SCOPE` around the `push_back` in the worker function. The vector will grow naturally with amortized O(1) push_back, and the rare reallocations are explicitly allowed. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The targeted CI job re-runs previously failed tests with `--count 10`. These tests were not idempotent: - `test_replication_credentials`: data accumulated across re-runs because tables were never truncated. Add `TRUNCATE TABLE` at the start of each test function. - `test_block_structure_mismatch`: same issue — duplicate rows from repeated inserts. Add `TRUNCATE TABLE` before inserting. - `test_version_update`: `CREATE TABLE test` failed with "Table already exists" on the second run. Add `DROP TABLE IF EXISTS` before creating. - `test_group_array_element_size`: same — `tab3` and `tab4` not dropped between runs. Add `DROP TABLE IF EXISTS` before creating. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The targeted CI job re-runs previously failed tests with `--count 10`. These tests were not idempotent: - `test_replication_credentials`: data accumulated across re-runs because tables were never truncated. Add `TRUNCATE TABLE` at the start of each test function. - `test_block_structure_mismatch`: same issue — duplicate rows from repeated inserts. Add `TRUNCATE TABLE` before inserting. - `test_version_update`: `CREATE TABLE test` failed with "Table already exists" on the second run. Add `DROP TABLE IF EXISTS` before creating. - `test_group_array_element_size`: same — `tab3` and `tab4` not dropped between runs. Add `DROP TABLE IF EXISTS` before creating. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The initial cleanup (TRUNCATE/DROP) was insufficient because tests also
modify config files and server state that persists across re-runs:
- `test_replication_credentials`: `test_different_credentials` and
`test_credentials_and_no_credentials` modify `credentials1.xml` via
`replace_config`. On re-run the modified config persists, changing
replication behavior. Fix: restore original credentials config and
`SYSTEM RELOAD CONFIG` at the start of each test. Also use
`CREATE DATABASE/TABLE IF NOT EXISTS` in `_fill_nodes`.
- `test_group_array_element_size`: `test_max_exement_size` ends with
config at `11` instead of `10`, so on re-run `replace_in_config("10",
"11")` is a no-op and assertions fail. Fix: restore original config
via `replace_config` + `restart_clickhouse` at test start.
- `test_version_update`: use `DROP TABLE IF EXISTS test SYNC` to ensure
ZooKeeper metadata is cleaned up for the `ReplicatedReplacingMergeTree`.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The initial cleanup (TRUNCATE/DROP) was insufficient because tests also
modify config files and server state that persists across re-runs:
- `test_replication_credentials`: `test_different_credentials` and
`test_credentials_and_no_credentials` modify `credentials1.xml` via
`replace_config`. On re-run the modified config persists, changing
replication behavior. Fix: restore original credentials config and
`SYSTEM RELOAD CONFIG` at the start of each test. Also use
`CREATE DATABASE/TABLE IF NOT EXISTS` in `_fill_nodes`.
- `test_group_array_element_size`: `test_max_exement_size` ends with
config at `11` instead of `10`, so on re-run `replace_in_config("10",
"11")` is a no-op and assertions fail. Fix: restore original config
via `replace_config` + `restart_clickhouse` at test start.
- `test_version_update`: use `DROP TABLE IF EXISTS test SYNC` to ensure
ZooKeeper metadata is cleaned up for the `ReplicatedReplacingMergeTree`.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- `test_concurrent_ttl_merges`: Add `DROP TABLE IF EXISTS ... SYNC`, `SYSTEM DROP REPLICA ... FROM ZKPATH`, and `SYSTEM START TTL MERGES` at the start of each test to clean up state from previous runs - `test_cluster_discovery/test_auxiliary_keeper`: Restart nodes that may have been left stopped, and drop `tbl` table on all nodes before re-run - `test_keeper_remove_rejoin_leader`: Increase `wait_until_connected` timeout from 30s to 60s after leadership transfer (ASan builds are slow) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- `test_concurrent_ttl_merges`: Add `DROP TABLE IF EXISTS ... SYNC`, `SYSTEM DROP REPLICA ... FROM ZKPATH`, and `SYSTEM START TTL MERGES` at the start of each test to clean up state from previous runs - `test_cluster_discovery/test_auxiliary_keeper`: Restart nodes that may have been left stopped, and drop `tbl` table on all nodes before re-run - `test_keeper_remove_rejoin_leader`: Increase `wait_until_connected` timeout from 30s to 60s after leadership transfer (ASan builds are slow) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
This improves performance among many tests with almost no degradation. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The code LGTM
Performance comparison analysis (SHA
|
| Mag | Query | Master slower/total |
|---|---|---|
| 1.21× | insert_parallel #0 — INSERT INTO t SELECT * FROM numbers_mt(1e9) |
0/584 |
| 1.10× | memory_cache_friendliness #0 |
0/584 |
| 1.10× | parallel_final #25 |
0/229 |
| 1.11× | apply_patch_parts_merge #2 |
0/583 |
ARM (Graviton 4)
| Mag | Query | Master slower/total |
|---|---|---|
| 1.40× | group_by_fixed_keys #13 |
0/839 (6 unstable) |
| 1.40× | group_by_fixed_keys #7 |
0/816 (8 unstable) |
| 1.24× | vectorize_aggregation_combinators #0 — countMerge over countState() FROM zeros(1e9) |
0/1169 |
| 1.16× | min_max_index_with_cast #0 |
0/823 |
| 1.10× | aggregation_by_partitions #8 |
0/696 |
Interpretation
All genuine regressions share one trait: they are maximally-parallel aggregation / parallel-insert queries. That is exactly the workload the LIFO change trades against — concentrating jobs on the most-recently-used worker threads reduces the number of concurrently active threads, which is the very mechanism that reduces per-thread allocator fragmentation. So these look like the inherent CPU-parallelism cost of LIFO concentration, not a defect — the flip side of the memory wins this PR targets (#10818).
The wins are large and also new in this PR: classification +8.15× / +3.12×, grace_hash_join +2.59×, order_by_single_column +1.75×, plus many order_with_limit, group_array_moving_sum, and (on AMD) group_by_fixed_keys / hash_table_sizes_stats_small improvements.
Suggestion
Either accept these as the documented parallelism-vs-locality trade-off, or consider preferring the most-recently-idle thread only when the pool isn't already saturated, so wide aggregations still fan out across cores while bursty/short work concentrates.
🤖 Generated with Claude Code
Trace-log deep-dive of the two genuine regressionsDownloaded
|
| metric | master | PR | ratio |
|---|---|---|---|
| client_time (wall) | 0.260 s | 0.315 s | +21% |
| OSCPUVirtualTime (total CPU) | 1.96 M µs | 2.15 M µs | +9.6% |
| InsertedRows | 1e9 | 1e9 | same |
- Distinct worker threads with CPU samples: master 129 → PR 14 (despite the PR trace capturing more runs). The parallel
INSERT … numbers_mt(1e9)that master fans out across ~60+ pool threads/run is concentrated onto ~3-4 threads/run. - Same hotspots on both binaries —
memcpy←DB::Squashing::squash(INSERT block assembly) andNumbersRangedSource::generate. No new or changed hot function. - Wall +21% with only +9.6% more CPU, and CPU/wall efficiency dropping 0.55→0.49 → classic under-parallelization, not extra algorithmic work.
vectorize_aggregation_combinators #0 (ARM, 1.24×) — overhead-dominated micro-benchmark
| metric | master | PR | ratio |
|---|---|---|---|
| client_time (wall) | 0.0455 s | 0.0563 s | +24% |
| OSCPUVirtualTime | 45 k µs | 56 k µs | +24% |
| UserTime | 44.6 k µs | 55.6 k µs | +25% |
| memory_usage | 243632 | 243632 | same |
- Here CPU ≈ wall (both +24%) and concurrency is ~2 threads on both sides (RealTime/wall ≈ 2), so this is not parallelism loss.
- The query is
countMerge(countState() FROM zeros(1e9))— the aggregation itself is trivial; CPU is dominated by pipeline-executor scheduling (DB::ExecutingGraph::updateNode,devector<Node*>, progress/trace callbacks), notAggregator. The PR's CPU shifts towardExecutingGraph::updateNode(top leaf, ~7.4% vs 5.9%). - It's an overhead-dominated micro-benchmark (≈11 ms absolute delta) that is sensitive to processor-scheduling order, which the LIFO worker-wake change perturbs. No algorithmic regression in the aggregation path.
Bottom line
Neither genuine regression is a code-path/algorithmic regression — in both, the hot functions are unchanged. insert_parallel is straightforward parallelism loss from concentrating a wide INSERT onto far fewer worker threads (129→14); vectorize_aggregation_combinators is a tiny overhead-dominated query whose pipeline-scheduling cost shifts with the new wake order. Both are consistent with the LIFO concentration trade-off rather than a defect.
🤖 Generated with Claude Code
|
Merged the latest Verified after the merge:
The previous red CI was unrelated to this change:
|
|
CI triage for the current head (
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100177&sha=51105504140ccb6beebe8924eb88823f120bda7f&name_0=PR&name_1=Stress%20test%20%28arm_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. (I found no existing open issue for |
|
@alexey-milovidov Thanks. The Root cause: PR #106020 (multistage distributed queries, merged 2026-06-09 15:25Z). Worker-side distributed-plan deserialization ( Fix: PR #106944 "Fix logical error when table is dropped before distributed plan task deserialization", merged 2026-06-10 14:56:05Z, which closed the auto-generated issue #106906 ( Verification (CIDB): master-only ( Performance Comparison (amd_release): agreed, not attributable to this PR. The entries fail as both Session: cron:clickhouse-worker-slot-4:20260612-001500 |
|
Merged |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 232/233 (99.57%) | Lost baseline coverage: none · Uncovered code |
…uest`
`ResourceGuard::Request` is reused per thread via the `Request::local()`
thread-local instance. Its `exception` member is set by `failed()` but was
never cleared on reuse, so a thread that had previously run a failed resource
request kept a stale `exception`. A subsequent request scheduled on that thread
could be granted via `execute()` (no exception set), yet `Request::wait()` would
still observe the stale `exception` and throw `RESOURCE_ACCESS_DENIED`
("Resource request failed: ... Scheduler queue with resource request is about to
be destructed"), even though that request had actually been granted.
This can surface to users as a query spuriously failing with
`RESOURCE_ACCESS_DENIED` when a workload's queue is restructured/dropped (e.g.
`CREATE WORKLOAD`/`ALTER`/`DROP`) fails one request and the same worker thread
is then reused for another request that is in fact granted.
Clear `exception` in `Request::enqueue()` (the reuse reset point) so a granted
request can never observe a previous request's failure. Genuinely failed
requests still throw: `failed()` sets `exception` and `wait()` throws as before;
the value is only reset when the request is reused for a new enqueue.
Related: ClickHouse#100177
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rowsOnZeroChecksum The test deliberately exercises the zero-checksum guard in `getBackupDataFileName`, which throws `DB::Exception(LOGICAL_ERROR, ...)`. On non-debug, non-sanitizer builds (e.g. `Unit tests (amd_llvm_coverage)`) the test passes, but `Exception::~Exception()` then logs the exception through `ForcedCriticalErrorsLogger` because `LOGICAL_ERROR` is treated as an "important" error code unless `markAsLogged` has been called. The resulting `Code: 49. DB::Exception: Backup checksum should not be zero (test.bin). (LOGICAL_ERROR)` line plus its full stack trace ends up on the gtest binary's stderr after the test's `[ OK ]` line. When an unrelated test in the same `unit_tests_dbms` binary later hangs (e.g. `SchedulerWorkloadResourceManager.DropNotEmptyQueueLong` per the report linked below), the wrapping `gdb -batch ... -ex run` runner times out, kills the binary mid-suite, and `gtest.json` is never written. The Praktika `from_gtest` parser then has nothing to parse and falls back to log-scraping, which surfaces the leaked `Backup checksum should not be zero` stack trace as a fake `-FunctionsStress` failure in CIDB. Sixteen hits across `Unit tests (amd_llvm_coverage)` on PRs ClickHouse#100177, ClickHouse#105784, ClickHouse#96100 over the past 60 days follow this pattern; the underlying contributor is the chronic `SchedulerWorkloadResourceManager` / `FunctionsStress` family hang, not the backup test. Replace `EXPECT_THROW(..., Exception)` with an equivalent `try` block that calls `markAsLogged` on the caught exception, mirroring the pattern already used in `executeQuery.cpp` (commit 64a4caa "Mark fuzzer exceptions as logged to prevent ForcedCriticalErrorsLogger") to suppress the stray stack trace. Verified locally: built `unit_tests_dbms` in release mode (`-O3 -DNDEBUG`, `ENABLE_TESTS=1`, no sanitizer) and confirmed the pre-fix binary prints a 17-frame stack trace to stderr on this test, while the post-fix binary runs the test silently with `[ OK ]` and no trace. Related: ClickHouse#100177 Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rowsOnZeroChecksum The test deliberately exercises the zero-checksum guard in `getBackupDataFileName`, which throws `DB::Exception(LOGICAL_ERROR, ...)`. On non-debug, non-sanitizer builds (e.g. `Unit tests (amd_llvm_coverage)`) the test passes, but `Exception::~Exception()` then logs the exception through `ForcedCriticalErrorsLogger` because `LOGICAL_ERROR` is treated as an "important" error code unless `markAsLogged` has been called. The resulting `Code: 49. DB::Exception: Backup checksum should not be zero (test.bin). (LOGICAL_ERROR)` line plus its full stack trace ends up on the gtest binary's stderr after the test's `[ OK ]` line. When an unrelated test in the same `unit_tests_dbms` binary later hangs (e.g. `SchedulerWorkloadResourceManager.DropNotEmptyQueueLong` per the report linked below), the wrapping `gdb -batch ... -ex run` runner times out, kills the binary mid-suite, and `gtest.json` is never written. The Praktika `from_gtest` parser then has nothing to parse and falls back to log-scraping, which surfaces the leaked `Backup checksum should not be zero` stack trace as a fake `-FunctionsStress` failure in CIDB. Sixteen hits across `Unit tests (amd_llvm_coverage)` on PRs ClickHouse#100177, ClickHouse#105784, ClickHouse#96100 over the past 60 days follow this pattern; the underlying contributor is the chronic `SchedulerWorkloadResourceManager` / `FunctionsStress` family hang, not the backup test. Replace `EXPECT_THROW(..., Exception)` with an equivalent `try` block that calls `markAsLogged` on the caught exception, mirroring the pattern already used in `executeQuery.cpp` (commit 64a4caa "Mark fuzzer exceptions as logged to prevent ForcedCriticalErrorsLogger") to suppress the stray stack trace. Verified locally: built `unit_tests_dbms` in release mode (`-O3 -DNDEBUG`, `ENABLE_TESTS=1`, no sanitizer) and confirmed the pre-fix binary prints a 17-frame stack trace to stderr on this test, while the post-fix binary runs the test silently with `[ OK ]` and no trace. Related: ClickHouse#100177 Co-Authored-By: Claude Opus 4.8 <[email protected]>








When a new job is scheduled, the thread pool now wakes the most recently idle thread (LIFO order) instead of an OS-determined arbitrary thread. This concentrates work on fewer OS threads, which:
Reduces memory fragmentation from jemalloc per-thread caches (tcache). Previously, work spread across many threads caused each to accumulate its own allocator cache, leading to excessive memory retention (e.g. 26 GiB instead of 4-5 GiB for two-level GROUP BY queries).
Improves CPU cache locality, as recently-active threads have warmer caches.
Allows excess idle threads to be naturally freed by the existing
max_free_threadsmechanism, releasing their allocator caches.Implementation: each worker thread now has a per-thread condition variable. Idle threads push themselves onto a LIFO stack and wait on their individual CV. The scheduler pops the most recently idle thread and signals it directly. The shared
new_job_or_shutdowncondition variable is removed.Note: this changes only which worker thread is woken to run a job; the job queue order is unchanged (jobs are still served in priority/FIFO order).
#10818
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
When a new job is scheduled in
ThreadPool, wake the most recently idle worker thread (LIFO) instead of an arbitrary one. This reduces memory fragmentation from per-thread allocator caches. The order in which jobs are processed is not changed.Note: I found the reasoning doubtful, so I set it as a draft for now.
Update: this is actually very good.
Version info
26.6.1.759