Skip to content

Clamp the thread pool schedule timeout before the chrono conversion - #117898

Merged
alexey-milovidov merged 6 commits into
masterfrom
fix-threadpool-schedule-wait-timeout-overflow
Sep 20, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
fix-threadpool-schedule-wait-timeout-overflow

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

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; 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::filterPartsByPrimaryKeyAndSkipIndexes passes lock_acquire_timeout.totalMicroseconds() to scheduleOrThrow when it analyses the primary key of several parts in parallel. SettingFieldSeconds accepts 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:

/ClickHouse/contrib/llvm-project/libcxx/include/__chrono/duration.h:93:79: runtime error:
signed integer overflow: -100000000000000000 * 1000 cannot be represented in type '_Ct' (aka 'long long')
...
#5  std::condition_variable::wait_for<...>(...)                                     __condition_variable/condition_variable.h:193
#6  ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true>>::scheduleImpl<void>(...)   src/Common/ThreadPool.cpp:470
#7  ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true>>::scheduleOrThrow(...)      src/Common/ThreadPool.cpp:655
#8  DB::MergeTreeDataSelectExecutor::filterPartsByPrimaryKeyAndSkipIndexes(...)      src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp:1286

SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior

-100000000000000000 microseconds is lock_acquire_timeout = -100000000000, the value that 04327_wait_timeout_chrono_overflow sets. There it runs against numbers(1000), which never reaches a thread pool; under the stress test the AST fuzzer carried the same SETTINGS clause onto a MergeTree read (the trace goes through executeASTFuzzerQueries), and that read schedules the per-part index analysis.

Fix: keep the timeout signed (Int64) through trySchedule, scheduleOrThrow, scheduleImpl and ThreadPoolCallbackRunnerLocal, and clamp the count with a new saturatedMicroseconds, the microsecond-typed sibling of the saturatedMilliseconds / saturatedSeconds helpers added in #106961, 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 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):

  • 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 signed integer overflow when scheduling a thread pool job with an out-of-range timeout: negative or huge lock_acquire_timeout values could overflow the chrono conversion inside ThreadPoolImpl::scheduleImpl during MergeTree index 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

  • Merged into: 26.10.1.304-master (included in 26.10 and later)

`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.
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a11c85e]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes the lock_acquire_timeout overflow in ThreadPoolImpl::scheduleImpl by keeping the timeout signed and clamping microsecond waits before std::condition_variable::wait_for. The core fix looks right, but the new regression coverage for the huge-timeout case is still nondeterministic, so the "large positive timeout still waits instead of failing immediately" contract is not actually proven yet.

Findings

⚠️ Majors

  • [src/Common/tests/gtest_thread_pool_schedule_timeout.cpp:109-118] HugeTimeoutWaitsForAFreeThread can pass without ever exercising the saturated wait_for path it is supposed to validate. The main thread calls release() immediately after spawning scheduler, so if that new thread has not yet reached pool.trySchedule(..., std::numeric_limits<Int64>::max()), the pool is already unsaturated by the time scheduling happens. In that interleaving the assertions still pass even if the huge-timeout clamp is broken or if the call never blocks at all.

Suggested fix: add a handshake that makes the test wait until the second trySchedule is observably blocked on the saturated pool before releasing the first worker.

Final Verdict

Status: ⚠️ Request changes

Minimum required action: make HugeTimeoutWaitsForAFreeThread deterministic enough to prove that the clamped wait_for path is actually taken before release() runs.

LLVM Coverage Report

Measured on commit a11c85e.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.70% +0.10%

Changed lines: Changed C/C++ lines covered: 65/65 (100.00%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit a11c85e0dc9bbae01a05a9870f65bb8ead17ac2e with master failed: RuntimeError: CI logs cluster query failed: SELECT file, symbol, sumIf(size, side = 'pr….

See the job log for details.

@clickhouse-gh clickhouse-gh Bot added the comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... label Sep 4, 2026
alexey-milovidov pushed a commit to mneedham/ClickHouse that referenced this pull request Sep 7, 2026
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]>
alexey-milovidov and others added 2 commits September 10, 2026 14:07
…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]>
Comment thread src/Common/ThreadPool.h Resolved
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... labels Sep 10, 2026
Comment on lines +109 to +114
std::thread scheduler([&]
{
scheduled = saturated.pool.trySchedule([&]{ job_ran = true; }, {}, std::numeric_limits<Int64>::max());
});

saturated.release();

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.

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.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Sep 20, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 20, 2026
Merged via the queue into master with commit 4ae01ef Sep 20, 2026
175 of 177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-threadpool-schedule-wait-timeout-overflow branch September 20, 2026 21:37
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants