Skip to content

Fix undefined behavior on a huge max_concurrent_threads_ratio_to_cores workload setting - #113206

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-workload-ratio-to-cores-int64-overflow
Aug 25, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-workload-ratio-to-cores-int64-overflow

Conversation

@groeneai

@groeneai groeneai commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #116200
Related: #112854

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 large max_concurrent_threads_ratio_to_cores value in CREATE WORKLOAD producing 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 = 9223372036854775807 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'

Found by the AST fuzzer, check AST fuzzer (arm_asan_ubsan), STID 3587-3c65
(report).

Root cause. 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, and the value > 0 guard on the next line runs after
the 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 Float64 domain before narrowing, matching the sibling
max_memory_ratio block a few lines below (added in 991c2a7441a3 for this same bug; the
ratio_to_cores twin was missed). unlimited is the right saturation target: a thread limit above
INT64_MAX is no limit, and the block already starts at Int64 limit = unlimited. In-range values
are unchanged, so there is no compatibility impact and no SettingsChangesHistory.cpp entry.
Rejecting such ratios would instead break workloads that already carry one.

Validation. The resolved limit is unlimited both before and after, so the sanitizer is the
only oracle. On a local address,undefined build the new stateless test and gtest each report
WorkloadSettings.cpp:366:46 without the change and pass with it. 50/50 randomized runs are green,
as are four existing workload and CPU-scheduling tests.

Context.cpp's concurrent_threads_soft_limit_ratio_to_cores twin is UInt64, so it has no
undefined behavior, but its product wraps modulo 2^64: a ratio of 2^63 + 1 on a two-core host
resolves to a limit of 2. That wrong-value defect is tracked separately, as is the
ThrottlerConstraint.h:175 narrowing, where clamping only relocates the overflow into the following
now + delay_ns and throttling_duration += delay_ns.


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

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.
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (1 finding, adjudicated)

An independent cold review plus a second-model gate pass ran against this diff before publication.
Both raised the same point, and it resolves to a property of the defect rather than a defect of the
tests.

⚠️ Test liveness: do the new tests distinguish the fix from the reverted code? (major) -
disagreed, with evidence.

The concern is precise and worth stating: the EXPECT_EQ(..., unlimited) rows cannot tell the two
implementations apart on their own. Pre-fix, aarch64 saturates to INT64_MAX, which is
unlimited and fails value < limit; x86-64 gives INT64_MIN, which fails value > 0. Post-fix
the clamp yields unlimited. All three end at max_concurrent_threads == unlimited, and
hasSemaphore(CPUNanosecond) tests != unlimited, so no SemaphoreConstraint node exists in any
arm and system.scheduler has no row to compare either. That is exactly why the PR body says the
sanitizer is the only oracle.

The follow-on inference, that the tests therefore may not redden, does not hold, for two
independent reasons.

  1. Fatality is a property of the build, not of the CI environment. cmake/sanitize.cmake:116
    compiles the address,undefined flavour with -fno-sanitize-recover=all. Compiling the exact
    conversion shape three ways confirms what that implies: with recovery on, the process prints the
    report and exits 0, reaching the value <= 0 path the finding describes; with
    -fno-sanitize-recover=all it exits 1; and UBSAN_OPTIONS=halt_on_error=0 does not relax it,
    since the flag is baked in at compile time. So the conversion aborts the process before any
    assertion is evaluated. WorkloadSettings.cpp is not in tests/ubsan_ignorelist.txt, and the
    new test carries no sanitizer-exclusion tag.
  2. The reverted-code run already exists. Only WorkloadSettings.cpp was reverted, both new tests
    were kept, and the tree was rebuilt, with distinct Build IDs per arm. Both new tests report at
    WorkloadSettings.cpp:366:46 without the change and pass with it. The pre-existing sibling
    WorkloadSettingsMaxMemoryRatio stayed green in both arms, which is the control showing the new
    gtest carries the oracle rather than passing incidentally.

The gate noted that runtime sanitizer execution was unavailable to it, so it could not observe that
arm.

Wiring verified independently: the new stateless test runs on six asan_ubsan stateless jobs, the
gtest on Unit tests (asan_ubsan) with an empty default --gtest_filter, and clickhouse-test
surfaces server-side sanitizer output as test stderr.

Also checked and clean: the clamp boundary is exact, since (double)INT64_MAX == 2^63 and the
largest double below it truncates to 9223372036854774784 <= INT64_MAX; NaN cannot reach the site
because ratio_to_cores > 0 is false, and inf is rejected upstream; every integral narrowing in
src/Common/Scheduler/ was enumerated independently and the only other true carrier
(max_memory_ratio) already has this clamp; and persisted workloads are re-validated through this
same function, so replay is covered by the same fix.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%. One DDL statement on an address,undefined build: CREATE WORKLOAD w IN a SETTINGS max_concurrent_threads_ratio_to_cores = 9223372036854775807 reports WorkloadSettings.cpp:366:46 runtime error: ... outside the range of representable values of type 'long' on every invocation. No fuzzer, no randomized settings.
b Root cause explained? Yes. ratio_to_cores * getNumberOfCPUCoresToUse() is a Float64 narrowed by a bare static_cast<Int64>; narrowing a float whose truncated value is not representable in the destination type is undefined behavior. The value > 0 guard is on the next line, i.e. downstream of the UB, and cannot recognise an unspecified-positive result. getFloat64 cannot bound the input either: its UInt64/Int64 branches return before its finiteness check, so an integer literal arrives unbounded.
c Fix matches root cause? Yes. The clamp is applied in the Float64 domain before the narrowing that is the UB, so the unsafe conversion never happens. Not a guard at the symptom, not a suppression, not a widened bound. It is a verbatim copy of the sibling max_memory_ratio clamp added in 991c2a7441a3 for this same bug, whose ratio_to_cores twin was missed.
d Test intent preserved / new tests added? Yes. Nothing existing was weakened or removed. Two new tests: a stateless SQL test and a gtest, both demonstrated to report the UBSan error without the change.
e Both directions demonstrated? Yes, three arms with distinct Build IDs: (1) the master ASan+UBSan snapshot at this PR's base reports at :366:46; (2) same tree, source reverted but new tests kept, rebuilt: both new tests report at :366:46; with the change both pass; (3) the reported statement completes cleanly on the fixed binary. The pre-existing sibling WorkloadSettingsMaxMemoryRatio gtest stayed green in both arms, so the new gtest is the one carrying the oracle.
f Fix is general across code paths? Yes. All 14 integer-narrowing sites in src/Common/Scheduler/ were enumerated and classified. max_memory already carries this clamp; max_cpus keeps its product in Float64 and needs no fix; max_burst_bytes/max_burst_queries assign to Float64 members. Context.cpp's concurrent_threads_soft_limit_ratio_to_cores twin is a non-carrier (declared UInt64, so integer arithmetic). ThrottlerConstraint.h:175 is a genuinely separate defect with different semantics and is tracked separately, not bundled here.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. All three getFloat64 branches exercised on the fixed binary: UInt64 (9223372036854775807, the reported input), Int64 (9223372036854775806, 4611686018427387904), Float64 (1e19, 1e100, DBL_MAX, 9223372036854775807.0), and String-with-size-suffix ('9000000T', '1000Ti'). Plus in-range values (0, 0.5, 2.5, 1e-9, the 5e-324 denormal) unchanged, and the pre-existing rejections for inf/nan (CANNOT_PARSE_NUMBER) and -0.1 (BAD_ARGUMENTS) unchanged. Type wrappers are not applicable: these are scalar settings parsed from a Field, never column types.
h Backward compatible? (maintainer-approved exception only) Yes, fully. Saturation only changes outcomes for inputs that previously had no defined outcome; every in-range value is bit-for-bit unchanged. No setting default moves, so no SettingsChangesHistory.cpp entry is needed. Rejecting out-of-range ratios at validate time was considered and rejected precisely because it would be incompatible for workloads that already carry one.
i Invariants and contracts preserved? Yes. The block's invariant (limit starts at unlimited and only ever narrows through value < limit) is preserved: the saturated value fails value < limit, so the limit stays unlimited, which is the correct reading of "a thread limit above INT64_MAX". raw is finite and positive at that point, so raw >= 2^63 is exactly the unrepresentable set and the comparison itself is well-defined. No new state, no locking, no allocation, no serialization: workload entities are stored as CREATE AST text and re-parsed through this same path, so replay is covered by the same fix.

Validation: 50/50 randomized runs of the new test green; 03232_workloads_and_resources, 03232_workload_create_and_drop, 04082_workload_negative_float64_settings and 03562_cpu_scheduling_with_one_thread green at 10 runs each; SchedulerWorkloadResourceManager.WorkloadSettings* gtests pass. All on a local address,undefined build.

Session id: cron:clickhouse-impl-slot-5:20260803-195600

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @serxa @antonio2368, could you review this? A user-settable max_concurrent_threads_ratio_to_cores is multiplied by the core count in Float64 and then narrowed with a bare static_cast<Int64>, so a huge ratio makes the conversion undefined and the value > 0 guard on the next line cannot recognise the unspecified result. The clamp is a verbatim copy of the max_memory_ratio sibling added in 991c2a7.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d7a9199]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) ERROR
Bugfix validation (unit tests) ERROR

AI Review

Summary

This PR clamps max_concurrent_threads_ratio_to_cores * cores in WorkloadSettings::initFromChanges before narrowing to Int64, which removes the UBSan-reported undefined behavior while preserving the existing in-range behavior and the unlimited semantics for oversized limits. The touched tests match the defect shape, and I did not find a remaining correctness, compatibility, or test-coverage problem in the changed code.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 35/35 (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 Aug 4, 2026
// 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);

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 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.cpp global concurrency control versus src/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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d7a9199

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Hung check failed, possible deadlock found two independent trunk cancellation gaps in one processlist: an AST-fuzzer merge(REGEXP('t.*')) query stuck 1158 s in plan-time work with is_cancelled = 1, and UNDROP TABLE stuck 457 s in the DatabaseCatalog::undropTable retry-sleep loop while holding the DDL guard, convoying two DROP TABLEs behind it (341 s / 296 s) UNDROP half: #113263 (external, open). merge() plan-time half: a fix task is moved to pending (investigating at full effort — fixing-PR link to follow here)
AST fuzzer (amd_tsan) / STID 2467-2c2d logical error Reading from materialized CTE 't' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan, on a fuzzer-generated WITH t AS MATERIALIZED (...) SELECT ... FROM merge('t.*') #102308 (external, open)
Bugfix validation (unit tests) harness: aborts as inconclusive because the base branch moved a submodule after the branch split (.gitmodules, contrib/arrow, contrib/orc, contrib/simdjson, contrib/xsimd), so the before-worktree cannot be populated at the merge-base revisions a fix task is moved to pending (investigating at full effort — fixing-PR link to follow here)
Build (arm_release) / Post Hooks infra: build_profile_hook.py telemetry INSERT INTO build_time_trace gets LogCluster query failed with code 500; the check itself is success a fix task is created (investigating at full effort — fixing-PR link to follow here)

Nothing is PR-caused. This PR changes src/Common/Scheduler/WorkloadSettings.cpp, its gtest, and
the new 04718_workload_ratio_settings_overflow. The new test passes 199 times across all
flavours, all four flaky checks are green, and both Bugfix validation (functional tests, aarch64) and (amd64) reproduce the UBSan report at WorkloadSettings.cpp:366 on the
before-binary and pass on the after-binary, which is the validation this PR needs.

None of the four failures touches workload settings or the scheduler. On the submodule item I
verified the diff contains zero contrib/ paths, and the signature spans 62 rows across 43
distinct PRs in 14 days, so it cannot originate in one diff. The Reason: Timeout!-free hung
check is the two-query shape already reported on other PRs this week; the merge() half has no
fixing PR yet and is mine to author.

Session id: cron:our-pr-ci-monitor:20260804-113000

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the ReadFromMerge::createChildrenPlans plan-time cancellation hung check on my
CI finish ledger: #113415 (external, open).

I had a fix for this on a local branch, but @alexey-milovidov opened #113415 with the identical
guard at the identical call site, so I dropped mine rather than open a duplicate. My analysis and
the one coverage gap I measured are in
#113415 (comment).

@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Aug 19, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Not worth fixing

@PedroTadim
PedroTadim enabled auto-merge August 25, 2026 08:38
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d7a9199a6 with master 773aa57a7 (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
Binary Master PR Δ
programs/clickhouse-stripped 709.95 MiB 706.91 MiB -3.04 MiB (-0.43%)

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 units

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

Job report

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 25, 2026
Merged via the queue into ClickHouse:master with commit 28dcbaf Aug 25, 2026
351 of 356 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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.

AST fuzzer: UBSan float-to-integer overflow in WorkloadSettings on huge max_concurrent_threads_ratio_to_cores

4 participants