Skip to content

Fix startup hang when max_thread_pool_size is too small - #112928

Open
alexey-milovidov wants to merge 118 commits into
masterfrom
fix-startup-hang-small-thread-pool
Open

alexey-milovidov wants to merge 118 commits into
masterfrom
fix-startup-hang-small-thread-pool

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

Setting max_thread_pool_size to a value that is too small made clickhouse-server hang forever at startup instead of reporting the problem.

A ThreadFromGlobalPool created while all the threads of the global thread pool are already taken by other such jobs was silently put into the pool's queue instead of getting a thread. The queue is much larger than the number of threads by default (thread_pool_queue_size is 10000 against max_thread_pool_size), so scheduling succeeded, but nothing ever picked the job up, because the threads are held by jobs that never return. Its creator got a seemingly running thread whose function was never called, and any code that then waited for that thread to make progress hung forever.

An idle server permanently occupies about 200 threads of the pool for the workers of the background pools and of the background schedule pools, and for the flush threads of the system logs, so a max_thread_pool_size below that ran out of threads while starting up:

  • With max_thread_pool_size of 128 the starved job was the loader worker of the system database, and startup hung forever right after Wait load job 'startup Atomic database system'.
  • With 100 it hung in the constructor of the merge/mutate background executor instead.
  • Values between roughly 130 and 200 appeared to start, but silently left some background threads unstarted - for example the flush threads of the system logs, so those tables never received any data.

Jobs that occupy their worker for the whole lifetime of that worker are now scheduled through ThreadPoolImpl::scheduleThreadOrThrow, which hands them one of the max_threads slots at scheduling time and throws CANNOT_SCHEDULE_TASK naming max_thread_pool_size when there is none left, rather than queueing a thread that can never start.

The workers of a local pool are scheduled the same way when the pool declares its jobs long-lived with setJobsAreLongLived (MergeTreeBackgroundExecutor, CacheDictionaryUpdateQueue, KeeperReadThreadPool). The workers of other local pools run jobs that return. They take no slot and wait in the queue, so a transient saturation does not reject them; that matters for the mandatory spawn of an AsyncLoader worker. An idle worker of a local pool that keeps free threads holds a slot while idle, and the global pool takes that slot back (the worker leaves its pool and frees its thread) when another thread needs it.

Two components started threads in their constructor and stopped them only in their destructor, so the resulting exception left those threads running while the destructor of the member thread pool blocked forever joining them. Both now stop their workers before letting the exception out, following the pattern CacheDictionaryUpdateQueue already uses:

  • MergeTreeBackgroundExecutor - this was the second hang above. Its increaseThreadsAndMaxTasksCount now starts the additional workers on a best-effort basis, so a configuration reload does not fail when the pool is saturated, and it reports the number of workers that actually started.
  • BackgroundSchedulePool - its handler used to LOG_FATAL and abort, turning a misconfiguration into signal 6 and a crash report. It now logs the same hint and rethrows, so the server exits cleanly.

Note that the hint in that handler ("Please make sure max_thread_pool_size is considerably bigger than background_schedule_pool_size") was previously unreachable, because saturating the global pool never produced CANNOT_SCHEDULE_TASK.

Behaviour change. Values of max_thread_pool_size that cannot hold the permanent threads of the server now make it refuse to start with a clear error naming the setting, where some of them used to start in a silently degraded state. This looks like the intended contract: max_thread_pool_size is documented as the maximum number of threads in the pool, and the documentation of thread_pool_queue_size already recommends keeping it equal to max_thread_pool_size, which makes saturation an error today. The requirement is now documented on the setting itself. No test configuration is affected: tests/casa_del_dolor/properties.py randomises max_thread_pool_size only down to 700.

Tested by starting a server with values of 16, 32, 64, 100, 128 and 160 (all fail with the error, no abort, no crash report) and 192, 256 and the default (all start normally), plus a check for slot accounting leaks under concurrent load with max_thread_pool_size of 400. The full unit_tests_dbms suite passes, including FunctionsStress.

The pre-existing ThreadPool.GlobalFull1 and ThreadPool.GlobalFull2 tests did not catch this because they give the global pool a queue as small as its thread count, which makes saturation fail on queue fullness instead. The new ThreadPool.GlobalFullLargeQueue covers the shape of the real pool, and the test_thread_pool_size_too_small integration test asserts that the server terminates with the error rather than hanging.

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):

Fixed a hang at server startup when max_thread_pool_size was set too small to hold the threads that the server occupies permanently. Such a configuration is now reported with an error naming the setting, instead of hanging forever or starting with some background threads missing.


Workflow [PR]
Sync PR [sync-upstream/pr/112928]

A `ThreadFromGlobalPool` created while all the threads of the global thread pool are already taken by
other such jobs was silently put into the pool's queue instead of getting a thread. The queue is much
larger than the number of threads by default (`thread_pool_queue_size` is 10000 against
`max_thread_pool_size`), so scheduling succeeded, but nothing ever picked the job up: the threads are
held by jobs that never return. Its creator got a seemingly running thread whose function was never
called, and any code that then waited for that thread to make progress hung forever.

An idle server permanently occupies about 200 threads of the pool for the workers of the background
pools and of the background schedule pools and for the flush threads of the system logs, so a
`max_thread_pool_size` below that ran out of threads while starting up. With 128 the starved job was
the loader worker of the `system` database, and the server hung forever at `Wait load job 'startup
Atomic database system'`. Larger values below 200 appeared to start, but silently left some background
threads unstarted - for example the flush threads of the system logs, so those tables never got any
data.

Jobs that occupy their worker for the whole lifetime of that worker are now scheduled through
`ThreadPoolImpl::scheduleThreadOrThrow`, which hands them one of the `max_threads` slots at scheduling
time and throws `CANNOT_SCHEDULE_TASK` naming `max_thread_pool_size` when there is none left, rather
than queueing a thread that can never start.

Two components started threads in their constructor and stopped them only in their destructor, so the
resulting exception left those threads running while the destructor of the member thread pool blocked
forever joining them. Both now stop their workers before letting the exception out:
- `MergeTreeBackgroundExecutor`, which was a second hang, reachable with `max_thread_pool_size` of 100.
  Its `increaseThreadsAndMaxTasksCount` now starts the additional workers on a best-effort basis, so a
  configuration reload does not fail when the pool is saturated, and reports the count that did start.
- `BackgroundSchedulePool`, whose handler used to `LOG_FATAL` and `abort`, turning a misconfiguration
  into signal 6 and a crash report. It now logs the same hint and rethrows, so the server exits cleanly.

The pre-existing `ThreadPool.GlobalFull1` and `ThreadPool.GlobalFull2` tests did not catch this because
they give the global pool a queue as small as its thread count, which makes saturation fail on queue
fullness instead. `ThreadPool.GlobalFullLargeQueue` covers the shape of the real pool, and the
`test_thread_pool_size_too_small` integration test asserts that the server terminates with the error
instead of hanging.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [49fef2b]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR reserves global-pool capacity for persistent workers and unwinds partial startup failures, so an undersized max_thread_pool_size can produce an exception instead of a hang. Three blockers remain: mandatory loader spawning can terminate the server, and two persistent-worker paths still bypass reservation accounting. Two findings were previously dismissed by the author and are retained here without reopening their threads.

Findings

❌ Blockers

  1. src/Common/ThreadPool.cpp:1467: Keeper read-ahead callbacks consume workers without reserving slots. LogEntryStorage::ensureReadAheadPoolLocked constructs readahead_pool without setJobsAreLongLived (src/Coordination/Changelog.cpp:2844), although fillTask parks indefinitely at EOF or its byte budget. With two global workers, one reserved permanent thread and one parked fill occupy both workers while the slot counter remains 1. A finite helper is then accepted into a queue that cannot progress. Reader eviction requires another reader access. Declare this pool long-lived before scheduling its tasks; its existing trySchedule rejection handling permits direct reads.

  2. src/Common/ThreadPool.cpp:782: A refused mandatory loader spawn terminates the server. [dismissed by author -- https://github.com/Fix startup hang when max_thread_pool_size is too small #112928#discussion_r4558084768] The current nested-worker check still throws when the caller is the last unreserved global worker, and AsyncLoader::spawn still calls scheduleOrThrowOnError inside NOEXCEPT_SCOPE (src/Common/AsyncLoader.cpp:941–955), which invokes std::terminate. For example, keep one of two workers permanently reserved and enqueue into an idle loader from a ReturningFailIfNoWorker thread. A gRPC CREATE DATABASE reaches this combination through GRPCServer.cpp:996 and InterpreterCreateQuery.cpp:457–463. Handle refusal by failing the affected load and restoring worker accounting, so the request receives an exception.

  3. src/Interpreters/TransactionManager.cpp:114: The transaction updater remains an unaccounted persistent worker. [dismissed by author -- https://github.com/Fix startup hang when max_thread_pool_size is too small #112928#discussion_r3805063124] The updater identified in the earlier thread now lives in TransactionManager, but still uses the default, slot-free constructor. runUpdatingThread loops until shutdown (:303–373). If reserved permanent workers occupy all other threads, the updater consumes the final worker while advertising one free slot; subsequent finite helpers queue indefinitely. Start this worker with FailIfNoWorker so it participates in the reservation contract.

Tests
  • ⚠️ Add a focused regression for an idle AsyncLoader called from the last unreserved global worker; require a reported load failure without process termination. Existing saturation tests enqueue from outside those workers.
  • ⚠️ Cover parked Keeper read-ahead workers and the transaction updater consuming the remaining capacity; further finite work must be rejected rather than stranded.
Missing context / blind spots
  • ⚠️ These findings are based on current-code execution traces. No configured ClickHouse build or test binary is available in this checkout, so the reproductions were not executed locally; focused executable regressions would close this gap.
Final Verdict

Status: ❌ Block

Handle mandatory loader-spawn refusal without terminating the process, account for the remaining persistent workers, and add focused saturation regressions.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 1, 2026
Comment thread src/Common/ThreadPool.cpp Resolved
Comment thread src/Common/ThreadPool.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 49fef2b27 with master 903285ff6 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

147 object files changed (+123.63 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/Common/ThreadPool.cpp.o 323.92 KiB 384.85 KiB +60.93 KiB (+18.81%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

414 translation units recompiled, 2566 s compile time in total, 414 of them have a recent master baseline.

Job report

alexey-milovidov and others added 3 commits August 3, 2026 23:29
…tcherOld` constructor

Starting `request_thread` or `responses_thread` may now throw `CANNOT_SCHEDULE_TASK`
synchronously when the global thread pool has no free slot for a long-running job.
Destroying a still joinable `ThreadFromGlobalPool` during the unwind would abort the
process, so mark the context as shut down, finish the queues, and join whatever
workers were started before rethrowing.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ackRunnerFast::operator()` fails to start a worker

`operator()` enqueued the callback and incremented `active_tasks` before
`startMoreThreadsIfNeeded`, but unlike `bulkSchedule` it did not roll either back
when `pool->scheduleOrThrow` throws. The caller saw `CANNOT_SCHEDULE_TASK` while the
callback stayed queued and could run later, when another worker eventually starts.
Add the same rollback as in `bulkSchedule`, plus a fault-injection unit test.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Common/ThreadPool.cpp Resolved
alexey-milovidov and others added 4 commits August 4, 2026 20:26
…inary

The bugfix-validation gate runs touched unit tests on the before-binary and
expects them to fail. Without the rollback, the failed schedule leaves the
callback in `queue` while `queue_size` is never incremented, so a subsequent
schedule strands its callback forever and the test hung at
`second_done.get_future().wait()` until the 4-hour job timeout:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112928&sha=42c61b8707873ac1a0949e0261adfae93dc407d6&name_0=PR&name_1=Bugfix%20validation%20%28unit%20tests%29
Guard the second-schedule phase on `isIdle`: if the rollback did not happen,
the failure is already recorded and we bail out via `shutdown`, which is safe
in that state.

Co-Authored-By: Claude Fable 5 <[email protected]>
…r fails to start one

`Coordination::Storage::BackgroundWork::BackgroundWork` and `Changelog::Changelog`
start multiple long-lived `ThreadFromGlobalPool`s. Now that `ThreadFromGlobalPool`
construction can throw `CANNOT_SCHEDULE_TASK` synchronously, a failure on the
second or later start would unwind and destroy already-started joinable threads,
and `~ThreadFromGlobalPoolImpl` aborts before the real error is reported.
`BackgroundWork` reuses `shutdown` in the catch; `Changelog` finishes the worker
queues and joins whatever threads were started (its `shutdown` cannot be used:
it dereferences not-yet-created thread pointers). Add a fault-injection
regression test constructing `Changelog` under `CannotAllocateThreadFaultInjector`.

Co-Authored-By: Claude Fable 5 <[email protected]>
The bugfix-validation gate runs the test on the before-binary, where it aborts
mid-test by design, leaving `./logs_ctor_unwind` behind. `ChangelogDirTest`
expects the directory to not exist, so a subsequent run in the same workspace
would fail spuriously. Remove the directory up front instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov and others added 3 commits August 5, 2026 15:14
…atcher constructor unwinds

`KeeperRequestDispatcherOld`'s constructor set `keeper_context->setShutdownCalled()` in its
catch block to make the already-started worker threads exit before rethrowing. That flag is
process-global and `KeeperDispatcher::shutdown` joins its own threads only on the first
transition of it, so consuming it during the unwind left `snapshot_thread` (started earlier by
`KeeperDispatcher::initialize`) never joined, and the process aborted on its still joinable
destructor instead of surfacing `CANNOT_SCHEDULE_TASK`.

The worker loops now also exit when their queue is finished, which keeps the constructor's
cleanup local: finish the queues, join the started workers, rethrow.

Co-Authored-By: Claude Fable 5 <[email protected]>
…n the unfixed binary

On the binary without the fix, `scheduleOrThrowOnError` silently queued `another_pool`'s
worker instead of throwing, and the pool's destructor then joined a "thread" whose function
never started - the very hang this test covers - so the Bugfix validation (unit tests) job ran
the test on the before-binary and hung for three hours until the 4-hour job timeout:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112928&sha=9feac815b044ee5dedff11339963464a4c05c606&name_0=PR&name_1=Bugfix%20validation%20%28unit%20tests%29
#112928

When the expected exception does not come, release the occupied threads and destroy the pool
that holds the global slots first, so the silently queued worker can run and both pools shut
down cleanly, then skip the rest of the test. Verified locally against master's `ThreadPool`:
the test now fails in milliseconds with a clean process exit.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112928&sha=9feac815b044ee5dedff11339963464a4c05c606&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The hung check flagged a thread stuck in ReplaceRegexpImpl::checkSubstitutions inside QueryAnalyzer::resolveFunction — an expensive constant-folded replaceRegexpAll call running during query analysis, outside the cancellation machinery. This is unrelated to this PR's thread pool changes and matches the open issue:

Related: #112203

Comment thread src/Common/ThreadPool.cpp Resolved
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

I investigated this one. The #112203 attribution does not hold for this artifact, and the actual hang is a different thing that I do not think has an owner yet.

The quoted frames are not the hung stack. In hung_check.log the thread dump spans lines 62-2011 (stacktraces: through Collecting stacktraces from system.stack_trace table). All 3 ReplaceRegexpImpl hits and all 25 resolveFunction hits are at lines 2226+, i.e. inside the Top messages not matching their format strings section that starts at line 2174. The ReplaceRegexpImpl.h:103 frame is entry #5 under the message Substitution '\{}' in replacement argument is invalid, regexp has only {} capturing groups, and its frames #0-#4 are Poco::Exception::Exception / DB::Exception::Exception constructors, so it is a thrown and handled exception being counted, not a stack. tryFoldFunctionToConstant, executeImplDryRun and processString (the frames your issue's own evidence names) appear 0 times anywhere in the file.

What actually hung. Processlist Row 1 is 04357_json_nested_prefixes_deserialization_pool.sql:

SELECT startsWith(dynamicType(data.arr), 'Array(JSON') FROM t_json_nested_pool WHERE id = 5;

elapsed: 1532.478, is_cancelled: 1, read_rows: 0, peak_threads_usage: 117. Of the 91 dumped threads, 85 sit in __lll_lock_wait: 72 on the stack-local callbacks_mutex (SerializationObject.cpp:601, entered at :604 from the safe_getter / safe_dynamic_subcolumns_callback wrappers at :605 and :611), and 13 on FileSegment::lock() from FileSegment::getInfoForLog (FileSegment.cpp:1170, :1172). The three running threads are all inside getInfoForLog or blocked on a marks future.

It was not deadlocked, it was crawling. The query emitted 20,290,878 log lines between 02:08:58.981 and 02:35:41.605, of which 20,290,743 are <Test> and 20,277,080 come from CachedOnDiskReadBufferFromFile. It was still emitting Read 50 bytes on the last line, and per-minute volume was rising (2.6M lines/min at the end vs 8k/min at the start), so there is no lost wakeup here.

The cost driver is that the read is advancing ~51 bytes at a time: 6,757,397 read events totalling 345,926,192 bytes, mean 51.2 bytes, and 1,217,090 points where the Remaining size to read counter grew again, i.e. that many separate seek/discard passes. The path is ReadBufferFromEncryptedFile::performSeekAndSetReadUntilPosition (ReadBufferFromEncryptedFile.cpp:221) -> ReadBufferFromRemoteFSGather::seek (ReadBufferFromRemoteFSGather.cpp:221), which for a short forward seek does ignore(diff) rather than a real seek, and each of those tiny reads takes the FileSegment guard again through the LOG_TEST at CachedOnDiskReadBufferFromFile.cpp:1509. MergeTreeMarksLoader ran 723 times over 708 distinct .cmrk2 files for a query that selected 2/2 granules, because the nested Array(JSON) expands to one mark stream per dynamic subpath. So: many tiny cache reads, each serialized behind a per-segment mutex, while 72 pool threads contend on one prefix-callback mutex.

Two things worth separating:

  • send_logs_level for this query was warning, but the server config for stress runs is logger_trace.xml (<level>trace</level>), and these are LOG_TEST calls. I have not established which channel actually admitted 20M <Test> lines, so I am not claiming the logging is the cause; I am claiming it is a large multiplier on an already-quadratic read, since getInfoForLog formats the whole segment description under the guard on every 51-byte read.
  • The lock convoy on callbacks_mutex is real regardless of logging. That mutex exists to serialize non-thread-safe stream callbacks across the prefix-deserialization pool, so with 117 threads and 708 mark streams it serializes essentially the whole read.

On ownership. This is not #113415 (ReadFromMerge::createChildrenPlans) or #113263 (UNDROP TABLE busy wait) - neither frame appears. It is adjacent to my open #112918, which adds cancellation checkpoints to the JSON/Object structure-prefix read, but that PR checkpoints the path-list loops in deserializeObjectStructureStatePrefix; it does not touch the per-mark cache read or the callbacks_mutex contention that dominates here, so it would not fix this. I am not going to claim it does.

I would rather not send a fix until I can reproduce the ~51-byte read pattern locally and confirm which of the two multipliers is load-bearing, because the plausible one-line fixes here (making the getInfoForLog diagnostics lazy, or raising min_bytes_for_seek on this path) are exactly the kind of change that looks right and moves nothing. I will follow up in this thread with either a PR or the measurement that says which one it is.

Separately, this artifact again lost its server-side system.stack_trace dump - the file says Cannot collect C stacktraces under ASan: debugger attach is disabled, so the 91 stacks above are the processlist ones only.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Following up on my earlier comment with the promised measurement. It identifies the load-bearing multiplier, and it turned out to be neither of the two candidates I named there. The fix already exists as an open PR of mine, so I am linking it rather than opening a second one.

Fixing PR: #112644 ("Do not read-and-discard the archive prefix when reading a packed part member").

What the multiplier is

The part in that run is in Packed storage, so every column file lives inside one data.packed archive: min_bytes_for_full_part_storage = 536870912 on the test table's CREATE (the runner randomizes it at tests/clickhouse-test:1881), and the part paths in the server log are store/8ca/.../all_1_1_0/data.packed on cached_s3_encrypted.

Two things then compound:

  1. MergeTreeMarksLoader sizes the read buffer for the virtual marks member (MergeTreeMarksLoader.cpp:179 -> adjustBufferSize(file_size), where file_size is the packed index entry, measured 47/50/54 bytes), but PackedFilesReader::readFile opens the whole archive (PackedFilesReader.cpp:125). The clamp propagates down the outer chain, so ReadBufferFromEncryptedFile gets a 47-byte buffer (DiskEncrypted.cpp:443).
  2. remote_read_min_bytes_for_seek stays at its default 4 MiB (Settings.cpp:6777; it was at default here, and the runner does not randomize it). The archive is 563,485 bytes, i.e. smaller than the threshold, so seeking to the member is judged "too short to seek" and ReadBufferFromRemoteFSGather::seek serves it with ignore(diff) instead (ReadBufferFromRemoteFSGather.cpp:251-253) - reading and discarding the whole prefix through that 47-byte buffer.

Measured on the query's own log lines and ProfileEvents:

  • 6,757,397 reads, 314,175,092 bytes, mean 51.3 B/read, for a query with SelectedMarks: 2
  • consecutive read offsets on one thread step by exactly the buffer size (54 x 12,228, 47 x 7,020, anything else x 4; monotone fraction 1.000) - a sequential prefix scan, not scattered reads
  • 563485 / 47 = 11,989 reads per open x 723 mark loads over 708 distinct .cmrk2 files (nested Array(JSON)) ~ 8.7M, matching the observed 6.76M
  • FileSegmentLockMicroseconds = 36,483,604,759; LogTest = 18,474,083; elapsed 26m43s against max_execution_time = 60

Only 1,958 seeks occur, which is why I initially read the seek path as a consequence. That inference was wrong: one ignore(diff) issues diff / buffer_size reads, so 6,757,397 / 1,958 = 3,451 reads per seek is itself the signature of an ignore-driven scan.

The two candidates I flagged earlier, both refuted

  • Making the getInfoForLog diagnostics lazy is already a no-op: LOG_IMPL short-circuits before evaluating its arguments (logger_useful.h:81), so nothing is formatted when the level is off. It would reduce a consequence (18.5M LOG_TEST lines) and leave the 6.76M reads. One nuance worth recording: chassert(..., getInfoForLog()) does evaluate in debug/ASan builds, so under ASan it is a real extra per-read cost - still a consequence, not the cause.
  • Raising min_bytes_for_seek is the wrong direction; the fix is to lower it to the effective buffer, which is what Do not read-and-discard the archive prefix when reading a packed part member #112644 does, mirroring StorageObjectStorageSource.

grep -c min_bytes_for_seek src/IO/PackedFilesReader.cpp is 0 at the failing sha and 0 on master, and 4 at #112644's head - so the fix is genuinely absent from the build that hung.

On the #112203 attribution

I could not reproduce it for this artifact. In hung_check.log the thread dump is lines 62-2011 (stacktraces: at 62, Collecting stacktraces from system.stack_trace table: at 2012), while every ReplaceRegexpImpl hit (3) is at line >= 2718 and every resolveFunction hit (25) at >= 2226 - all inside the Top messages not matching their format strings section that starts at 2017, as stacks of thrown-and-handled exceptions. tryFoldFunctionToConstant, executeImplDryRun and processString appear 0 times anywhere in the file. Of the 90 thread blocks in the dump, 84 are in __lll_lock_wait (61 on the SerializationObject prefix-callback mutex, 12 on FileSegment::lock), and every running thread is inside the marks read chain.

Also related but not a fix for this: my open #112918 makes a JSON structure-prefix read observe cancellation, which would have ended this query at the 60 s deadline instead of letting it run 26 minutes. It touches neither the packed reader nor the per-mark read path, so I am not claiming it covers this.

…rt` unwinds

If starting `cleanup_thread` throws `CANNOT_SCHEDULE_TASK` because the global
thread pool is full, `createServer` destroys the half-started listener without
calling `stop`, and the defaulted destructor aborted on the still-joinable
`server_thread`. Call `stop` before rethrowing, following the same
partial-start cleanup pattern as the other components in this PR.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Common/ThreadPool.cpp Resolved
alexey-milovidov and others added 3 commits August 7, 2026 03:56
…inds

If starting `cleanup_thread` throws `CANNOT_SCHEDULE_TASK`, the already
started `main_thread` used to keep running with a half-started worker.
Reuse `shutdown` (idempotent, joins whichever threads exist) in the catch
and rethrow, so the failure propagates fail-closed.

Co-Authored-By: Claude Fable 5 <[email protected]>
…gs` constructors unwind

Two more sites of the same class as the reviewed ones: if the Nth
`ThreadFromGlobalPool` start throws `CANNOT_SCHEDULE_TASK`,
- the `AsynchronousInsertQueue` constructor destroyed the member vector
  with joinable threads (`flushAndShutdown` is never called for an object
  that failed to construct), terminating the process;
- the `SystemLogs` constructor called `startCollect` outside its existing
  try/catch, and the implicit `PeriodicLog` destructor does not join
  `collecting_thread`, also terminating on unwind.

Both now stop and join the already started threads and rethrow, so a too
small `max_thread_pool_size` surfaces as a startup error.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Common/ThreadPool.cpp Resolved
…in `FileCache::initialize`

With `load_metadata_asynchronously` enabled, a `CANNOT_SCHEDULE_TASK` failure
from `CacheMetadata::startup` was deferred into `init_exception` on the metadata
loading thread, so the server came up with a registered but permanently broken
filesystem cache. Start the permanent background threads (downloads, delayed
cleanup) in the synchronous part of `FileCache::initialize`, before the
(possibly asynchronous) metadata loading, so the exception reaches the caller
and startup fails close. `CacheMetadata::startup` now also stops and joins
partially started download threads when it unwinds.

Until the metadata is loaded, the threads only sleep on their empty queues:
cache users block in `assertInitialized` on `init_mutex` until the load
finishes, and the delayed-cleanup consumer takes the same per-bucket locks as
the loader.

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov and others added 4 commits November 5, 2026 23:31
…licate setting in `gtest_filecache`

Master wrapped the responder of a gRPC `Call` into `CallResponder` (the member is
now `call_responder`), so the cancellation added by this PR in `Call::start` must go
through it. The previous merge also left `background_download_threads` declared twice
in `gtest_filecache.cpp`, which the style check rejects.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112928&sha=383bd9d478451d245a928eded62820f1b3a5e569&name_0=PR&name_1=Build%20%28arm_tidy%2C%204%2F4%29
#112928

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The slot of a thread scheduled through `scheduleThreadOrThrow` (and
`scheduleThreadOrQueueOrThrow`) was taken optimistically before the mutex of
the pool was locked. A concurrent worker that takes no slot could see the
counter at zero, and be rejected as if all the threads were long-lived,
while the long-lived thread was then rejected itself because all the workers
were busy with finite jobs. A rejection is fatal for the mandatory spawn of
an `AsyncLoader` worker.

The slot is now taken under `mutex`, after the worker is found, with no
unlock until the job is handed to its worker or queued, so no slot is ever
held by a job that may still be rejected.

Addresses the review comment of `clickhouse-gh` on 2026-11-06.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Common/ThreadPool.cpp
Comment thread src/Common/ThreadPool.cpp Resolved
alexey-milovidov and others added 2 commits November 9, 2026 02:13
…the singleton

Two findings of the automated review:

* A `ThreadFromGlobalPool` signalled `join` before the worker of the global pool
  destroyed its job, which is what gave its slot back. A caller that had just
  joined a long-lived thread could find the slot still taken, and the worker of a
  local pool that takes no slot was rejected as if all the threads were held by
  long-lived ones - fatal for the mandatory spawn of an `AsyncLoader` worker. The
  job now gives its slot back right before it signals `join`
  (`releaseCurrentGlobalThreadJobSlot`).

* `std::is_same_v<Thread, GlobalThreadType>` also holds for an independent
  `FreeThreadPool`, so an ordinary job queued in such a pool could evict an idle
  worker of a local pool and credit its slot of the singleton to its own counter,
  and the singleton lost that slot for good. Only the counter of the singleton
  can take back the slots of idle workers now.

New tests `ThreadPool.SlotOfJoinedThreadIsFreeAtOnce` (fails 84 runs of 100
without the fix) and `ThreadPool.IndependentFreeThreadPoolDoesNotEvictIdleWorkerOfSingleton`
(fails deterministically without the fix).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits November 10, 2026 07:09
…er holding no slot

A worker of a local pool with long-lived jobs (`scheduleThreadOrQueueOrThrow`) takes a slot
and may wait in the queue. When it was scheduled by a worker of the global pool that holds no
slot (for example the thread that loads a dictionary, which constructs
`CacheDictionaryUpdateQueue`) and took the last slot, it was queued behind the job of the
scheduling worker. The constructor then failed to schedule the next update worker and joined
the first one in `stopAndWait`, which could never start: the dictionary loading hung.

The check that the scheduling worker does not count as a worker that frees up for the queued
job now covers slot-taking jobs too. Added `ThreadPool.NestedLongLivedWorkerOnLastFreeThreadIsRejected`,
which fails (hangs until the deadline) without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the metadata is loading

The permanent threads of `CacheMetadata` are now started before the (possibly asynchronous)
metadata loading, so that a failure to start them is reported synchronously. But this let the
cleanup thread remove keys while they were still being reconstructed: a concurrent iteration
over the metadata, such as `SYSTEM SYNC FILESYSTEM CACHE`, could see a key that was published
but not yet filled, submit it for removal, and the cleanup thread would remove its directory
with valid cached segments.

The cleanup thread is still started (and its slot of the global thread pool taken) synchronously,
but it does not take keys from its queue until `CacheMetadata::startCleanup` is called after the
metadata is loaded, which restores the previous ordering of the removal relative to the loading.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (2d071c4, no conflicts; the PR's files that master also changed compile). The two remaining failures on 6f04dcf are unrelated and already have fixes in progress:

Conflict in `src/Storages/FileLog/DirectoryWatcherBase.cpp`: master replaced the
per-watcher thread with the shared `DirectoryWatchReactor`, so take master's version,
and start the long-lived reactor threads with `ThreadFromGlobalPoolScheduleMode::FailIfNoWorker`
as this PR did for the per-watcher thread.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (e60b108). The conflict in src/Storages/FileLog/DirectoryWatcherBase.cpp came from master replacing the per-watcher thread with the shared DirectoryWatchReactor. I took master's version and started the long-lived reactor threads with ThreadFromGlobalPoolScheduleMode::FailIfNoWorker, as this PR did for the old per-watcher thread. The PR's files that master also changed compile. The Performance Comparison failures on 2d071c4 were infrastructure: test selection hit a GitHub API 403 rate limit exceeded. They will rerun on the new head.

Comment thread src/Common/ThreadPool.h Resolved
alexey-milovidov and others added 2 commits November 14, 2026 12:39
The default constructor of `ThreadFromGlobalPoolImpl` scheduled the thread
through `scheduleOrThrow`, which queues it whenever the queue has room. With
all the workers of the global pool held by permanent threads, a finite thread
such as the one of `PullingAsyncPipelineExecutor` was accepted but never
started, and its creator hung in `join`.

Make `QueueUnlessSlotsExhausted` (`scheduleReturningThreadOrQueueOrThrow`) the
default: the thread still waits in the queue behind ordinary finite jobs, but it
is rejected with `CANNOT_SCHEDULE_TASK` when all the slots are taken by
long-lived threads. Remove the now unused `ThreadFromGlobalPoolScheduleMode::Queue`.
Extend `ThreadPool.GlobalFullLargeQueue` with a plain finite thread.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112928&sha=e60b108bb561433f2daa766d93a8b2233e3dc019&name_0=PR&name_1=Integration%20tests%20%28amd_msan%2C%20targeted%29 (test_storage_s3_queue/test_5.py::test_select_racing_drop, iteration 3: assert 'TABLE_IS_DROPPED' in '', passed on retry) and provide a fix in a separate PR. If the fix is already in progress, link it here. The test races a DROP against a SELECT with a fixed time.sleep(1.2), so it is timing-dependent, and over the last 14 days it failed once in about 1,300 runs. This PR changes only the startup of ObjectStorageQueueMetadata, not the read path.

The La Casa Del Dolor (amd_msan) failure, Chosen multipart upload for an empty file in copyAzureBlobStorageFile, is unrelated and is being fixed in #131587.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating test_storage_s3_queue/test_5.py::test_select_racing_drop (my test from #113695); I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix for test_select_racing_drop is in #131652. In the failing run the DROP's client needed 2.23 s to connect, past the test's ~1.8 s window, so the SELECT finished first; the test now pauses the SELECT in StorageObjectStorageQueue::read() on a one-shot failpoint until the DROP is done, instead of sleeping.

BorisTyshkevich pushed a commit to BorisTyshkevich/ClickHouse that referenced this pull request Nov 15, 2026
The test raced `DROP TABLE ... SYNC` against a direct `SELECT` by wall
clock: the `SELECT` kept its plan open for ~3 s in a scalar subquery and
pytest sent the `DROP` 1.2 s later, so the `DROP` had to reach the server
within ~1.8 s. In `Integration tests (amd_msan, targeted)` on ClickHouse#112928 the
`DROP`'s client needed 2.23 s to connect, the `SELECT` read the live
metadata first and returned 0 without an error, and the assertion
`'TABLE_IS_DROPPED' in ''` failed.

Add a one-shot pause failpoint `object_storage_queue_pause_in_direct_select`
in `StorageObjectStorageQueue::read()`, after the table is opened and
before the read path takes the metadata handle. It parks the query thread
during planning, never a pipeline worker inside `IProcessor::work()`.
The test now enables it, starts the `SELECT`, waits for the pause, runs
`DROP TABLE` (not `SYNC`: that waits for the paused `SELECT` to release
the table), disables the failpoint and asserts `TABLE_IS_DROPPED`. One
deterministic pass replaces the 10 sleep-based iterations. Same pattern as
`nats_pause_before_checking_direct_select_connection` (ClickHouse#125494).

Related: ClickHouse#112928
Related: ClickHouse#113695

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, #131652 (the test_select_racing_drop fix) is merged.

The CH Inc sync failure was build failed: clang-tidy in arm_tidy wanted [[nodiscard]] on ScopedDecrement::valueAfterDecrement in src/Common/ThreadPool.cpp. That is fixed in a7f8d54. The public CI on 10df2d9 was otherwise green.

qoega pushed a commit to qoega/ClickHouse that referenced this pull request Nov 19, 2026
…aths once

The test failed with "Test runs too long (> 180s)" in
`Stateless tests (amd_tsan, s3 storage, targeted)` on ClickHouse#112928 (181.5 s) and
ClickHouse#116257 (215.2 s).

`system.remote_data_paths` reads the metadata of every file on the disk (only
`disk_name` is pushed down). Concurrent tests leave ~32k files on `s3_disk`,
and the test read it three times with the same filter. From the failing jobs'
query_log:

| run                  | span  | 3 remote_data_paths SELECTs   | rest   | files per scan |
|----------------------|-------|-------------------------------|--------|----------------|
| ClickHouse#112928 run 1 (FAIL) | 178 s | 166.0 s (40.3 / 79.4 / 46.4)  | 8.9 s  | 31,709         |
| ClickHouse#112928 run 2 (OK)   |  50 s |  37.6 s                       | 10.1 s |  6,577         |
| ClickHouse#116257 run 1 (FAIL) | 212 s | 204.6 s                       |  4.3 s | 31,678         |

Read the source table's objects once into a temporary table and use it in the
three assertions. The assertions and the reference are unchanged.

With 200 filler parts (32,288 files) on `s3_disk`, the reads take
12.7-16.5 s -> 3.9-4.1 s per run on the amd_tsan binary from ClickHouse#112928
(1.9-2.1 s -> 0.64-0.67 s on a debug build).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-common-library Common library: the general-purpose code in src/Common and src/Core that belongs to no feature - ... and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 19, 2026
…all-thread-pool

Conflict in `ObjectStorageQueueMetadata::startup`: keep both sides. `update_registry_thread`
is started only in `unordered` mode (from master), with
`ThreadFromGlobalPoolScheduleMode::FailIfNoWorker`, and `startup_called` is published
under `startup_mutex` only after the workers are running (from this branch).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Comment thread src/Common/ThreadPool.cpp
global_queued_jobs = &globalQueuedJobs();
}
thread = Thread(
pool_jobs_are_long_lived ? ThreadFromGlobalPoolScheduleMode::ReserveSlot : ThreadFromGlobalPoolScheduleMode::QueueUnlessSlotsExhausted,

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.

[Blocker] Account for the persistent Keeper read-ahead workers

LogEntryStorage::ensureReadAheadPoolLocked creates readahead_pool without setJobsAreLongLived (src/Coordination/Changelog.cpp:2844–2851), although fillTask deliberately parks inside its callback at EOF or the byte budget until its reader is closed (:2756–2815). This branch therefore gives those workers QueueUnlessSlotsExhausted: they reserve no global slot and never reach the local pool's idle-slot accounting.

For example, with two global workers, one reserved permanent thread plus one parked read-ahead task consumes both workers while remaining_thread_job_capacity remains 1. A subsequent finite ThreadFromGlobalPool or local-pool worker passes admission and queues indefinitely. Reader eviction requires another reader access, so an unrelated waiting query cannot rely on it to release the worker. This leaves the queued-but-never-started hang reachable with embedded Keeper.

Mark readahead_pool as long-lived before scheduling its first task, and cover this capacity-exhaustion case. Its existing trySchedule rejection path already permits a direct read when a fill worker cannot be started.

This branch has not been deployed

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

Labels

comp-common-library Common library: the general-purpose code in src/Common and src/Core that belongs to no feature - ... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants