Repository navigation
Fix undefined behavior on a huge max_concurrent_threads_ratio_to_cores workload setting - #113206
Conversation
CREATE WORKLOAD with a large max_concurrent_threads_ratio_to_cores triggers undefined behavior in WorkloadSettings::initFromChanges: src/Common/Scheduler/WorkloadSettings.cpp:366:46: runtime error: 1.47574e+20 is outside the range of representable values of type 'long' The setting is a user-settable Float64, so a single ordinary DDL statement is enough; the AST fuzzer found it as STID 3587-3c65 in AST fuzzer (arm_asan_ubsan). The product ratio_to_cores * getNumberOfCPUCoresToUse() is computed in Float64 and narrowed with a bare static_cast<Int64>. Narrowing a float whose truncated value is not representable in the destination type is undefined behavior ([conv.fpint]/1). The value > 0 test on the following line runs after the fact, so it cannot recognise an unspecified positive result. Nothing aborts in a release build; the limit is simply unspecified (INT64_MAX on aarch64 via fcvtzs, INT64_MIN on x86-64 via cvttsd2si). getFloat64 does not bound the input either: its UInt64 and Int64 branches return immediately, so its finiteness check is only reached by genuine Float64 literals and an integer literal arrives unbounded. Clamp in the Float64 domain before narrowing. This is the same pattern the sibling max_memory_ratio block a few lines below already uses, added in 991c2a7 for exactly this bug; the ratio_to_cores twin was missed then. unlimited is the semantically correct saturation target rather than an arbitrary cap: a thread limit above INT64_MAX is no limit, the block already starts at Int64 limit = unlimited, and hasSemaphore tests != unlimited. Values in range are bit-for-bit unchanged, so no setting default moves and no SettingsChangesHistory.cpp entry is needed. Rejecting out-of-range ratios at validate time was considered and rejected: it would be backward incompatible for workloads that already carry such a value, and inconsistent with the saturating sibling. Note the behavioral outcome is unlimited both before and after the change, so no assertion on the resolved limit or on system.scheduler can distinguish them. The sanitizer is the only oracle, which is why the tests are statement-only and were verified to report at :366:46 without this change. Context.cpp's concurrent_threads_soft_limit_ratio_to_cores twin is unaffected: ServerSettings declares it UInt64, so the product is integer arithmetic. The narrowing in ThrottlerConstraint.h is a separate defect with different semantics, since clamping there would relocate the overflow into the subsequent now + delay_ns and throttling_duration += delay_ns arithmetic; it is tracked separately.
Internal second-model review (1 finding, adjudicated)An independent cold review plus a second-model gate pass ran against this diff before publication.
The concern is precise and worth stating: the The follow-on inference, that the tests therefore may not redden, does not hold, for two
The gate noted that runtime sanitizer execution was unavailable to it, so it could not observe that Wiring verified independently: the new stateless test runs on six Also checked and clean: the clamp boundary is exact, since |
Pre-PR validation gate (click to expand)
Validation: 50/50 randomized runs of the new test green; Session id: cron:clickhouse-impl-slot-5:20260803-195600 |
|
cc @serxa @antonio2368, could you review this? A user-settable |
|
Workflow [PR], commit [d7a9199] Summary: ❌
AI ReviewSummaryThis PR clamps Final Verdict✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 35/35 (100.00%) · Uncovered code |
| // Clamp before casting to `Int64`: a large ratio (e.g. `1e100`) would otherwise produce a | ||
| // float outside `Int64` range and trigger undefined-behaviour on conversion. | ||
| Float64 raw = ratio_to_cores * getNumberOfCPUCoresToUse(); | ||
| Int64 value = (raw >= static_cast<Float64>(unlimited)) ? unlimited : static_cast<Int64>(raw); |
There was a problem hiding this comment.
This fixes the CREATE WORKLOAD carrier, but the server-wide twin still does unchecked UInt64 multiplication in Context::setConcurrentThreadsSoftLimit (src/Interpreters/Context.cpp:2584). concurrent_threads_soft_limit_ratio_to_cores is a changeable UInt64 server setting, so a large value can wrap to a tiny limit instead of behaving as "no limit" on the global concurrency controller: for example, 9223372036854775809 on a 2-core host produces 2. Since both settings expose the same ratio-to-cores contract, this looks incomplete unless the global path gets the same saturating or rejecting rule.
There was a problem hiding this comment.
Confirmed, and the arithmetic checks out: 9223372036854775809 * 2 mod 2^64 == 2, so on a two-core host the global limit really does become 2. I reproduced it with a probe copying the exact shape of setConcurrentThreadsSoftLimit, and the wrap is well-defined UInt64 arithmetic (ratio_to_cores is UInt64 at ServerSettings.cpp:920, getNumberOfCPUCoresToUse returns unsigned, SlotCount = UInt64), so there is no undefined behavior there, only a wrong value. The value > 0 guard cannot catch it for the same reason it could not catch the workload case: a wrapped product is usually positive.
One detail worth adding: ratios whose product is an exact multiple of 2^64 wrap to 0 instead and are accidentally rescued by that guard, so 2^63 at two cores already resolves to unlimited today. The reddening inputs are the wrap-to-finite ones such as 2^63 + 1 and UINT64_MAX.
So the observation is right, and the exclusion sentence in the description was not. It said the twin was "unaffected (declared UInt64, so integer arithmetic)", which conflated "no undefined behavior" with "no defect". The description is now corrected to state the wrap and the resulting limit of 2.
Fixing it here is the wrong scope, and I am tracking it separately instead:
- Different defect class. This PR is a float-to-integer narrowing that is undefined behavior; that one is a defined unsigned wrap producing a wrong value. The changelog entry and the whole validation story here are about the former.
- Different oracle, so a different test. This PR's tests are reddened by the UBSan build itself. The server setting produces no sanitizer report at all, and it is config-only with no query-level equivalent, so it needs a behavioural assertion in an integration test.
tests/integration/test_concurrent_threads_soft_limit/already has the per-node config harness for exactly this setting. - Different file and owner surface:
src/Interpreters/Context.cppglobal concurrency control versussrc/Common/Scheduler/WorkloadSettings.cpp.
That is the same reasoning that kept ThrottlerConstraint.h:175 out of this PR, where clamping only relocates the overflow into the following now + delay_ns and throttling_duration += delay_ns.
The likely fix there is the UInt64-domain analogue of this one: saturate to UnlimitedSlots when ratio_to_cores > UnlimitedSlots / cores. Verified in the probe that this yields unlimited for 2^63 - 1 and UINT64_MAX while leaving in-range products identical, and the accidental wrap-to-zero inputs already resolve to unlimited, so it is compatible. Rejecting the value at config-parse time would be backward-incompatible for an operator whose config already carries one.
There was a problem hiding this comment.
Closing the loop on this, since I said above I was tracking it separately: I measured it and I am not opening a fix.
The wrap is real and reproduces exactly as described. On a host where getNumberOfCPUCoresToUse() is 192, a ratio of 9223372036854775809 resolves to a limit of 192, and I found ratios that resolve as low as 64, confirmed live via ConcurrencyControlSoftLimit in system.metrics after SYSTEM RELOAD CONFIG.
What it costs is bounded throughput, nothing more. There is no wrong result, and no hang: setMaxConcurrency clamps with std::max<SlotCount>(1, value) and every allocation still gets its min slots unconditionally, so 8 concurrent 192-thread queries under an effective limit of 1 all completed normally. Measured cost at a wrapped limit of 64, against 24 concurrent CPU-bound queries: 1.50 to 1.67 s versus 0.93 to 0.97 s unlimited, about 1.6x.
Two things decided it. The plausible accident path is already closed: -1, the usual "unlimited" idiom, is rejected at parse time with Code: 72, so reaching this needs an operator to type a specific value above 2^63 on purpose. And the resulting state is one an operator can already ask for deliberately through concurrent_threads_soft_limit_num, so the outcome is a supported configuration rather than a broken one, visible in system.metrics and in the server log and reverted by one config edit.
I could not find anyone who has hit it: no issue, no user report, and no in-tree precedent guarding an operator-supplied ratio against wrap. On that balance a change here is not worth reviewer time, so I am leaving it unfixed rather than carrying an open item I do not intend to act on.
CI finish ledger — d7a9199Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Nothing is PR-caused. This PR changes None of the four failures touches workload settings or the scheduler. On the submodule item I Session id: cron:our-pr-ci-monitor:20260804-113000 |
|
Fixing PR for the I had a fix for this on a local branch, but @alexey-milovidov opened #113415 with the identical |
|
Not worth fixing |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units7 translation units recompiled, 6 s compile time in total, 7 of them have a recent master baseline. |
28dcbaf
Closes: #116200
Related: #112854
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a large
max_concurrent_threads_ratio_to_coresvalue inCREATE WORKLOADproducing an unspecified concurrent-thread limit. The ratio is now clamped before narrowing, so such a value means "no limit".Description
CREATE WORKLOAD w SETTINGS max_concurrent_threads_ratio_to_cores = 9223372036854775807triggersundefined behavior in
WorkloadSettings::initFromChanges:Found by the AST fuzzer, check
AST fuzzer (arm_asan_ubsan), STID3587-3c65(report).
Root cause.
ratio_to_cores * getNumberOfCPUCoresToUse()is computed inFloat64and narrowedwith a bare
static_cast<Int64>. Narrowing a float whose truncated value is not representable inthe destination type is undefined behavior, and the
value > 0guard on the next line runs afterthe fact, so it cannot recognise an unspecified positive result. Nothing aborts in a release build,
but the resulting limit is unspecified.
The change clamps in the
Float64domain before narrowing, matching the siblingmax_memory_ratioblock a few lines below (added in991c2a7441a3for this same bug; theratio_to_corestwin was missed).unlimitedis the right saturation target: a thread limit aboveINT64_MAXis no limit, and the block already starts atInt64 limit = unlimited. In-range valuesare unchanged, so there is no compatibility impact and no
SettingsChangesHistory.cppentry.Rejecting such ratios would instead break workloads that already carry one.
Validation. The resolved limit is
unlimitedboth before and after, so the sanitizer is theonly oracle. On a local
address,undefinedbuild the new stateless test and gtest each reportWorkloadSettings.cpp:366:46without the change and pass with it. 50/50 randomized runs are green,as are four existing workload and CPU-scheduling tests.
Context.cpp'sconcurrent_threads_soft_limit_ratio_to_corestwin isUInt64, so it has noundefined behavior, but its product wraps modulo 2^64: a ratio of
2^63 + 1on a two-core hostresolves to a limit of
2. That wrong-value defect is tracked separately, as is theThrottlerConstraint.h:175narrowing, where clamping only relocates the overflow into the followingnow + delay_nsandthrottling_duration += delay_ns.Workflow [PR]
Sync PR [sync-upstream/pr/113206]