Repository navigation
Log live local thread pools at GlobalThreadPool shutdown - #105905
alexey-milovidov merged 12 commits into
Conversation
Adds a diagnostic that lists every live `ThreadPoolImpl<ThreadFromGlobalPool*>` instance when `GlobalThreadPool::shutdown` runs. The chronic stress-test "Hung check failed, possible deadlock found" family is caused by local thread pools whose owner never destroyed them: their workers stay parked on the local pool's `new_job_or_shutdown` condition variable, so `GlobalThreadPool::finalize` blocks forever joining the underlying `std::thread`. Today CI artifacts only expose anonymous "ThreadPool" frames in gdb.log, which is why this umbrella has been untriageable. The instrument keeps a `std::unordered_map` of live local pools keyed by `this` and named by `CurrentMetrics::getName(metric_threads)`, so the resulting log line points straight at the subsystem (for example `BackgroundFetchesPoolTaskx1, MergeTreeBackgroundExecutorThreadsx1`) without relying on `setThreadName` (which is called after a job is received and is absent for parked workers). `finalize` unregisters at the very end of the function so that a hung join leaves the leaker in the map, which is exactly the signal `shutdown` reads. The registry is intentionally leaked so it outlives function-local statics like `getIOThreadPool` whose destructors call `unregisterLocalThreadPool` after the registry would otherwise be gone.
|
Pre-PR validation gate self-review (per worker policy; session: cron:clickhouse-ci-task-worker:20260527-004500) This patch is a diagnostic instrument, not a fix, so a few gate items are reinterpreted accordingly: a) Deterministic repro? Not applicable to the instrument itself. The bug it is meant to surface (chronic "Hung check failed, possible deadlock found", ~8-10 master hits/day on master sanitizer/serverfuzz stress lanes) is non-deterministic by nature and cannot be reproduced locally in a reasonable time budget. Per the established investigation plan, the next step is to ship the instrument to CI and read leaker subsystem names from the resulting log. b) Root cause explained? Yes for the umbrella we are diagnosing: from gdb.log on PR #104228 (commit c) Fix matches root cause? This PR does not fix the deadlock. It instruments the shutdown path so CI artifacts attribute leaks to a named subsystem (e.g. d) Test intent preserved? No existing tests modified. e) Both directions demonstrated? Reinterpreted as "did the instrument compile and produce the expected log line shape?". Locally rebuilt f) Fix is general? Yes within scope. The registry captures every |
|
cc @alexey-milovidov @alesapin could you review? This is the diagnostic instrument we discussed across PRs #104228, #100399, #100276, #100377, #101143, #94517, #96844, #97254 for the chronic "Hung check failed, possible deadlock found" umbrella. Once it lands, every future hit on master / stress lanes will name the leaker subsystem in clickhouse-server.log, unblocking per-subsystem lifetime fixes. |
|
Workflow [PR], commit [60a49cb] Summary: ✅
AI ReviewSummaryThis PR adds best-effort attribution for leaked local Final VerdictStatus: ✅ Approve |
…end()` Test pools (for example `gtest_uniq_exact_parallel_merge.cpp`) construct `ThreadPool` with `CurrentMetrics::end()` as a placeholder metric. The new diagnostic registration path passed that placeholder to `CurrentMetrics::getName`, which indexes `names[event]` without bounds checking; `names` has size `END`, so the placeholder produced out-of-bounds access at construction. Guard the registration so it only runs for real metrics. The diagnostic loses nothing meaningful: tests using the placeholder do not participate in the production `GlobalThreadPool::shutdown` hang we are instrumenting. Issue raised by AI Review on ClickHouse#105905
Address the bot review on PR ClickHouse#105905 (ClickHouse#105905 (comment)): the previous design registered every `ThreadPoolImpl<ThreadFromGlobalPool*>` at construction, so long-lived shared pools that `Server.cpp` initializes via `SharedThreadPools.cpp` function-local statics (`getIOThreadPool`, `getBackupsIOThreadPool`, `getFetchPartitionThreadPool`, `getActivePartsLoadingThreadPool`, `getFormatParsingThreadPool`, ...) stayed in the registry until `GlobalThreadPool::shutdown` even when they owned no worker threads. That made the diagnostic line in `GlobalThreadPool::shutdown` noisy on healthy shutdowns and defeated the PR contract of identifying the leaker subsystem. Now the registry only counts pools that currently own at least one worker thread: `addLocalThreadPoolWorker` runs from `ThreadFromThreadPool::ThreadFromThreadPool` (after `available_threads` is bumped), and `removeLocalThreadPoolWorker` runs from `~ThreadFromThreadPool` after `join()`. The per-pool entry stores the metric name plus a `live_workers` counter; on a 0 -> 1 transition the entry is created, on a 1 -> 0 transition it is erased. Side benefits: - For a leaked pool the owner's `~ThreadPoolImpl` is never called, so `threads.clear()` in `finalize()` is never reached and the pool's workers never run their destructors. Their entries stay by construction. The unregister inside the old `finalize()` is removed; the destructor handles it for healthy shutdowns. - The snapshot reports the total number of worker threads per metric name, not just the instance count, so partial leaks are still informative. - The placeholder guard `metric_threads < CurrentMetrics::end()` from commit f88b111 is kept on both add and remove sites, so the test pools in `gtest_uniq_exact_parallel_merge.cpp` that pass `CurrentMetrics::end()` still skip the registry. Diagnostic only, no behavior change. Co-Authored-By: Claude Opus 4.7 <[email protected]>
`addLocalThreadPoolWorker` runs from `ThreadFromThreadPool::ThreadFromThreadPool` after `thread = Thread(...)` has already started a joinable `ThreadFromGlobalPoolImpl`. Its previous implementation could throw on `std::unordered_map::operator[]` bucket growth or `std::string` allocation; an escaping exception would unwind through `~ThreadFromGlobalPoolImpl`, which calls `abort()` while `state` is still initialized, terminating the process. The diagnostic instrument was thus turning a benign allocation failure into a hard process abort - a new failure mode that did not exist before this PR. Fix: 1. Make `addLocalThreadPoolWorker` and `removeLocalThreadPoolWorker` `noexcept` with a `try/catch(...)` that swallows allocation/lock-acquisition failures. The diagnostic snapshot may miss an entry, but the pool itself keeps working and the process is no longer at risk of abort. 2. Change `Entry::metric_name` from `std::string` to `std::string_view`. `CurrentMetrics::getName` returns a view into the program-lifetime `names` array (`src/Common/CurrentMetrics.cpp`), so the view is valid for as long as any pool exists. This removes the only string allocation from the `add`/`remove` paths, leaving `unordered_map` bucket growth as the sole remaining throwable operation (caught and swallowed). 3. Update the snapshot to aggregate over `std::map<std::string_view, size_t>`, so the aggregation key is also allocation-free. Address @clickhouse-gh bot review on PR ClickHouse#105905. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Addresses two bot review concerns on PR ClickHouse#105905: 1. `snapshotLocalThreadPools` is called from `GlobalThreadPool::shutdown` before `the_instance->finalize()`. If `std::map`/`std::string` allocation or `fmt::format_to` throws (e.g. under `MEMORY_LIMIT_EXCEEDED` at shutdown), the exception escapes shutdown and `finalize` is skipped, leaving background threads un-joined. Marked `noexcept` with internal `try/catch` returning `"(unavailable)"` as a fallback string. 2. The `LOG_INFO` call site itself can throw (Poco channel I/O, formatter allocation). Wrapped the call site in `try/catch` so the log path cannot skip `finalize` either. Also: rephrase the `catch (...)` annotations in `addLocalThreadPoolWorker` and `removeLocalThreadPoolWorker` to include the `Ok:` marker recognized by `ci/jobs/check_style.py::check_catch_all`. The catches are intentional diagnostic-only swallows already documented by the preceding header comments; the style check is satisfied by `Ok:` in the catch line.
Resolve conflict in src/Common/ThreadPool.cpp: keep both the diagnostic registry's <unordered_map> include and master's new <vector> include. Master generalized the global-vs-local pool discriminator from `std::is_same_v<Thread, std::thread>` to `std::is_same_v<Thread, GlobalThreadType>` (GlobalThreadType is ThreadWithStackSize on macOS, std::thread elsewhere). Update the two diagnostic registration guards (addLocalThreadPoolWorker / removeLocalThreadPoolWorker call sites) to use GlobalThreadType so the global pool is never registered into the local-pool snapshot on macOS. No-op on Linux where the two types are identical. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Merged current master into the branch to resolve the conflict (commit 6152ef6). The only conflict was in One semantic adjustment the merge required: master generalized the global-vs-local pool discriminator from Net diff vs master is unchanged otherwise (only ThreadPool.cpp, +177 lines). session cron:clickhouse-worker-slot-0:20260614-070600 |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Yes, this is reasonable.
|
@groeneai, iterate on the logs from Fast Test from the failed merge queue case. |
The shutdown diagnostic logged "shutdown(): live local ThreadPoolImpl worker threads at shutdown: [(none)]" unconditionally. This code runs at the exit of every ClickHouse binary, including short-lived client tools (clickhouse-benchmark, clickhouse-local, clickhouse-client), whose default root logger has a console channel at information level. The line could therefore reach a tool's stderr and get captured by tests that diff tool output. This was caught by the merge queue: Fast Test failed on 03636_benchmark_error_messages because the "(none)" line leaked into the captured clickhouse-benchmark output and broke the reference diff. It is intermittent (depends on logger-channel/static-destruction timing at process exit), which is why regular PR CI passed it. Only emit the line when the snapshot is not "(none)", i.e. when a local pool still owns worker threads. A healthy shutdown is now silent, so it cannot pollute any tool's output under any logging configuration. The leaker signal is preserved: a real leaker yields a non-"(none)" string, and the "(unavailable)" fallback (when the snapshot itself throws) is also still logged. The noexcept/try-catch finalize-safety guarantees are unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
The merge-queue Fast Test failure was Root cause: Fix (b78d6dd): only emit the line when the snapshot is not Verified locally: |
|
CI fully finished on head
No PR-caused failures. Nothing here is attributable to the diagnostic change. |
…end()` Test pools (for example `gtest_uniq_exact_parallel_merge.cpp`) construct `ThreadPool` with `CurrentMetrics::end()` as a placeholder metric. The new diagnostic registration path passed that placeholder to `CurrentMetrics::getName`, which indexes `names[event]` without bounds checking; `names` has size `END`, so the placeholder produced out-of-bounds access at construction. Guard the registration so it only runs for real metrics. The diagnostic loses nothing meaningful: tests using the placeholder do not participate in the production `GlobalThreadPool::shutdown` hang we are instrumenting. Issue raised by AI Review on ClickHouse#105905
Address the bot review on PR ClickHouse#105905 (ClickHouse#105905 (comment)): the previous design registered every `ThreadPoolImpl<ThreadFromGlobalPool*>` at construction, so long-lived shared pools that `Server.cpp` initializes via `SharedThreadPools.cpp` function-local statics (`getIOThreadPool`, `getBackupsIOThreadPool`, `getFetchPartitionThreadPool`, `getActivePartsLoadingThreadPool`, `getFormatParsingThreadPool`, ...) stayed in the registry until `GlobalThreadPool::shutdown` even when they owned no worker threads. That made the diagnostic line in `GlobalThreadPool::shutdown` noisy on healthy shutdowns and defeated the PR contract of identifying the leaker subsystem. Now the registry only counts pools that currently own at least one worker thread: `addLocalThreadPoolWorker` runs from `ThreadFromThreadPool::ThreadFromThreadPool` (after `available_threads` is bumped), and `removeLocalThreadPoolWorker` runs from `~ThreadFromThreadPool` after `join()`. The per-pool entry stores the metric name plus a `live_workers` counter; on a 0 -> 1 transition the entry is created, on a 1 -> 0 transition it is erased. Side benefits: - For a leaked pool the owner's `~ThreadPoolImpl` is never called, so `threads.clear()` in `finalize()` is never reached and the pool's workers never run their destructors. Their entries stay by construction. The unregister inside the old `finalize()` is removed; the destructor handles it for healthy shutdowns. - The snapshot reports the total number of worker threads per metric name, not just the instance count, so partial leaks are still informative. - The placeholder guard `metric_threads < CurrentMetrics::end()` from commit f88b111 is kept on both add and remove sites, so the test pools in `gtest_uniq_exact_parallel_merge.cpp` that pass `CurrentMetrics::end()` still skip the registry. Diagnostic only, no behavior change. Co-Authored-By: Claude Opus 4.7 <[email protected]>
`addLocalThreadPoolWorker` runs from `ThreadFromThreadPool::ThreadFromThreadPool` after `thread = Thread(...)` has already started a joinable `ThreadFromGlobalPoolImpl`. Its previous implementation could throw on `std::unordered_map::operator[]` bucket growth or `std::string` allocation; an escaping exception would unwind through `~ThreadFromGlobalPoolImpl`, which calls `abort()` while `state` is still initialized, terminating the process. The diagnostic instrument was thus turning a benign allocation failure into a hard process abort - a new failure mode that did not exist before this PR. Fix: 1. Make `addLocalThreadPoolWorker` and `removeLocalThreadPoolWorker` `noexcept` with a `try/catch(...)` that swallows allocation/lock-acquisition failures. The diagnostic snapshot may miss an entry, but the pool itself keeps working and the process is no longer at risk of abort. 2. Change `Entry::metric_name` from `std::string` to `std::string_view`. `CurrentMetrics::getName` returns a view into the program-lifetime `names` array (`src/Common/CurrentMetrics.cpp`), so the view is valid for as long as any pool exists. This removes the only string allocation from the `add`/`remove` paths, leaving `unordered_map` bucket growth as the sole remaining throwable operation (caught and swallowed). 3. Update the snapshot to aggregate over `std::map<std::string_view, size_t>`, so the aggregation key is also allocation-free. Address @clickhouse-gh bot review on PR ClickHouse#105905. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Addresses two bot review concerns on PR ClickHouse#105905: 1. `snapshotLocalThreadPools` is called from `GlobalThreadPool::shutdown` before `the_instance->finalize()`. If `std::map`/`std::string` allocation or `fmt::format_to` throws (e.g. under `MEMORY_LIMIT_EXCEEDED` at shutdown), the exception escapes shutdown and `finalize` is skipped, leaving background threads un-joined. Marked `noexcept` with internal `try/catch` returning `"(unavailable)"` as a fallback string. 2. The `LOG_INFO` call site itself can throw (Poco channel I/O, formatter allocation). Wrapped the call site in `try/catch` so the log path cannot skip `finalize` either. Also: rephrase the `catch (...)` annotations in `addLocalThreadPoolWorker` and `removeLocalThreadPoolWorker` to include the `Ok:` marker recognized by `ci/jobs/check_style.py::check_catch_all`. The catches are intentional diagnostic-only swallows already documented by the preceding header comments; the style check is satisfied by `Ok:` in the catch line.
…hung-check-leaked-threadpool Log live local thread pools at GlobalThreadPool shutdown
Adds a one-line diagnostic to
GlobalThreadPool::shutdownthat lists every liveThreadPoolImpl<ThreadFromGlobalPool*>instance, keyed by the subsystem'sCurrentMetricsname. Targets the chronic stress-test "Hung check failed, possible deadlock found" / "Possible deadlock on shutdown" family on master.Why: gdb.log from a hung stress run shows the main thread blocked inside
GlobalThreadPool::shutdown->ThreadPoolImpl<std::thread>::finalizejoining anstd::threadwhose body is an inner pool'sworkerparked on the local pool'snew_job_or_shutdowncv. That cv never fires because the local pool'sshutdownflag is stillfalse(its owner leaked it). The artifacts give us anonymous "ThreadPool" frames only, with no way to attribute the leak to a subsystem.How it works:
ThreadPoolImplregistersthisin a leaked singleton registry, keyed byCurrentMetrics::getName(metric_threads)(a stable, subsystem-specific identifier such asBackgroundFetchesPoolTask). Only theThreadFromGlobalPool*instantiations are registered, notThreadPoolImpl<std::thread>(which IS theGlobalThreadPool).finalizeunregisters at the very end, AFTER the join loop. A hungfinalizetherefore leaves the entry in the map, which is exactly the signal we want.GlobalThreadPool::shutdownreads the registry and emits oneLOG_INFOline BEFORE callingfinalize, so the message is captured in the server log even when the join hangs forever.The registry is intentionally leaked because function-local statics inside
SharedThreadPools.cpp(getIOThreadPool,getBackupsIOThreadPool, ...) wrapThreadPoolinstances whose destructors callunregisterLocalThreadPoolafter this registry would otherwise be destroyed.Expected log lines:
shutdown(): live local ThreadPoolImpl instances at shutdown: [(none)]shutdown(): live local ThreadPoolImpl instances at shutdown: [BackgroundFetchesPoolTaskx1](or similar). Once CI captures the leaker subsystem names, follow-up PRs can land per-subsystem lifetime fixes.This is intentionally diagnostic-only with no behavior change. The cost at shutdown is one snapshot of a small
std::unordered_mapunder a single mutex.Pre-PR validation:
src/Common/ThreadPool.cppand linkedlibclickhouse_common_io.acleanly with clang-21 Debug.gh prfor "GlobalThreadPool shutdown" / "ThreadPool diagnostic" / "leaked ThreadPool" / "hung_check ThreadPool" on 2026-05-27; no overlap.Related context: PR #103551 (merged 2026-04-27) preserves
hung_check.logcontent intest_context_rawbut the log only shows blocked threads in anonymousThreadPool::worker. This PR adds the missing subsystem attribution.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Version info
26.7.1.412(included in26.7and later)