Repository navigation
Clamp the thread pool schedule timeout before the chrono conversion - #117898
Conversation
`ThreadPoolImpl::scheduleImpl` handed its `wait_microseconds` parameter straight to `std::condition_variable::wait_for`, which evaluates the wait as `steady_clock::now() + duration` in nanoseconds, multiplying a microsecond duration by 1'000. The parameter is a `uint64_t`, while the settings that feed it are `Int64` microsecond timespans, so a negative timeout arrives as a huge unsigned count and that multiplication overflows `Int64`. UBSan aborts the server; a release build wraps to a deadline in the past, so the schedule fails at once with `Cannot schedule a task: no free thread` instead of waiting. The setting that reaches it is `lock_acquire_timeout`: `MergeTreeDataSelectExecutor::filterPartsByPrimaryKeyAndSkipIndexes` passes `lock_acquire_timeout.totalMicroseconds()` to `scheduleOrThrow` when it analyses the primary key of several parts in parallel. Found on master in the stress test: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=a54f19b0b7169af771a26d449065c368684b07a3&name_0=MasterCI&name_1=Stress%20test%20%28amd_asan_ubsan%29 /ClickHouse/contrib/llvm-project/libcxx/include/__chrono/duration.h:93:79: runtime error: signed integer overflow: -100000000000000000 * 1000 cannot be represented in type '_Ct' #5 std::condition_variable::wait_for<...>(...) condition_variable.h:193 #6 ThreadPoolImpl<...>::scheduleImpl<void>(...) src/Common/ThreadPool.cpp:470 #7 ThreadPoolImpl<...>::scheduleOrThrow(...) src/Common/ThreadPool.cpp:655 #8 DB::MergeTreeDataSelectExecutor::filterPartsByPrimaryKeyAndSkipIndexes(...) src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp:1286 Clamp the count with a new `saturatedMicroseconds`, the microsecond-typed sibling of the `saturatedMilliseconds` and `saturatedSeconds` helpers, which covered every millisecond- and second-typed `wait_for` but not this microsecond one. The pool cannot reuse the millisecond clamp because `wait_microseconds` must keep sub-millisecond resolution. A count above the one-year cap keeps meaning "wait until a thread frees up", the same thing the existing clamp already does for a huge positive timeout.
|
Workflow [PR], commit [a11c85e] Summary: ❌
AI ReviewSummaryThis PR fixes the Findings
Suggested fix: add a handshake that makes the test wait until the second Final VerdictStatus: Minimum required action: make LLVM Coverage ReportMeasured on commit a11c85e.
Changed lines: Changed C/C++ lines covered: 65/65 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing commit See the job log for details. |
The microsecond carrier is clamped by ClickHouse#117898, which adds the same `saturatedMicroseconds` helper to `saturatedDuration.h`; keeping both would define that helper and its constant twice. This commit therefore drops the microsecond half and the `wait_microseconds` widening, leaving the three `getLockTimeout` helpers in `StorageFile`, `StorageLog` and `StorageStripeLog` as the only change. Co-Authored-By: Claude Opus 5 <[email protected]>
…wait `ThreadPoolImpl::scheduleImpl` took `wait_microseconds` as a `uint64_t`, while the settings that feed it (`lock_acquire_timeout`) are `Int64` microsecond timespans. Clamping alone removed the overflow, but a negative setting still reached the clamp as a huge unsigned count and became a one-year wait, whereas the rest of the timeout code treats a negative timeout as an already expired deadline. Keep the timeout signed all the way down: `trySchedule`, `scheduleOrThrow`, `scheduleImpl` and the `wait_microseconds` parameter of `ThreadPoolCallbackRunnerLocal` now take `Int64`. All three call sites that pass a timeout hand over `lock_acquire_timeout.totalMicroseconds`, which is already `Int64`, so the sign survives and `saturatedMicroseconds` clamps a negative timeout to zero: the schedule gives up at once instead of waiting for a year. Add `src/Common/tests/gtest_thread_pool_schedule_timeout.cpp`, which saturates a one-thread, one-slot pool and then schedules into it, so it really reaches the `job_finished.wait_for` branch: a negative timeout must return immediately, a positive one must wait for its duration, and a timeout above the clamp must keep waiting until a thread frees up rather than overflowing or failing at once. The functional test cannot reach that branch (`ThreadPool(max_threads)` sets `queue_size == max_threads`, so nothing blocks), so its comment now says what it does cover: that such a setting reaches index analysis end-to-end. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…dule-wait-timeout-overflow
…dule-wait-timeout-overflow
| std::thread scheduler([&] | ||
| { | ||
| scheduled = saturated.pool.trySchedule([&]{ job_ran = true; }, {}, std::numeric_limits<Int64>::max()); | ||
| }); | ||
|
|
||
| saturated.release(); |
There was a problem hiding this comment.
This still does not deterministically exercise the huge-timeout wait_for path. scheduler and the main thread race here: if the new thread does not reach pool.trySchedule(..., std::numeric_limits<Int64>::max()) until after release has already let the blocked worker finish, the pool is no longer saturated and the call succeeds without ever touching saturatedMicroseconds or job_finished.wait_for. In that interleaving the test also cannot distinguish Int64::max() from an incorrectly tiny or already-expired timeout.
Please add a handshake that proves the second schedule is already blocked before calling release, or otherwise keep the worker from finishing until that state is observable, so this case actually validates the clamped huge-timeout behavior.
ThreadPoolImpl::scheduleImplhanded itswait_microsecondsparameter straight tostd::condition_variable::wait_for, which evaluates the wait assteady_clock::now() + durationin nanoseconds, multiplying a microsecond duration by 1'000. The parameter is auint64_t, while the settings that feed it areInt64microsecond timespans, so a negative timeout arrives as a huge unsigned count and that multiplication overflowsInt64. UBSan aborts the server; in a release build the multiplication wraps, so the resulting deadline is undefined rather than the immediate expiry that the rest of the timeout code gives a negative timeout.The setting that reaches it is
lock_acquire_timeout:MergeTreeDataSelectExecutor::filterPartsByPrimaryKeyAndSkipIndexespasseslock_acquire_timeout.totalMicroseconds()toscheduleOrThrowwhen it analyses the primary key of several parts in parallel.SettingFieldSecondsaccepts a negative value, so any query can produce the overflowing count.Found on master in the stress test — https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=a54f19b0b7169af771a26d449065c368684b07a3&name_0=MasterCI&name_1=Stress%20test%20%28amd_asan_ubsan%29:
-100000000000000000microseconds islock_acquire_timeout = -100000000000, the value that04327_wait_timeout_chrono_overflowsets. There it runs againstnumbers(1000), which never reaches a thread pool; under the stress test the AST fuzzer carried the sameSETTINGSclause onto aMergeTreeread (the trace goes throughexecuteASTFuzzerQueries), and that read schedules the per-part index analysis.Fix: keep the timeout signed (
Int64) throughtrySchedule,scheduleOrThrow,scheduleImplandThreadPoolCallbackRunnerLocal, and clamp the count with a newsaturatedMicroseconds, the microsecond-typed sibling of thesaturatedMilliseconds/saturatedSecondshelpers added in #106961, which covered every millisecond- and second-typedwait_forbut not this microsecond one. The pool cannot reuse the millisecond clamp becausewait_microsecondsmust keep sub-millisecond resolution. A negative timeout stays an already-expired deadline, so the schedule fails immediately when no thread is free, exactly as a zero timeout does; a count above the one-year cap keeps meaning "wait until a thread frees up", which is the same thing the existing clamp does for a huge positive timeout.Related: #106961
Related: #112088
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a signed integer overflow when scheduling a thread pool job with an out-of-range timeout: negative or huge
lock_acquire_timeoutvalues could overflow the chrono conversion insideThreadPoolImpl::scheduleImplduringMergeTreeindex analysis, aborting the server under the Undefined Behavior Sanitizer and producing undefined timeout handling in release builds.Workflow [PR]
Sync PR [sync-upstream/pr/117898]
Version info
26.10.1.304-master(included in26.10and later)