Repository navigation
Fix signed integer overflow in the table lock deadline built from lock_acquire_timeout - #117974
Conversation
…uire_timeout` `libc++` turns `wait_for(d)` into `wait_until(now() + d)` and converts `d` to nanoseconds first, multiplying by 1'000'000'000 for a `std::chrono::seconds` argument and by 1'000 for `std::chrono::microseconds`. `SettingFieldTimespan` only rejects values that do not fit Int64 microseconds, three orders of magnitude above the first value that overflows a nanosecond deadline, and no constraint caps the setting, so two carriers reached that conversion unbounded in both signs. No contention is required: the overflow is in the argument to `wait_for`, before any predicate check. The three byte-identical `getLockTimeout` helpers in `StorageFile`, `StorageLog` and `StorageStripeLog` return a `std::chrono::seconds` for a `std::shared_timed_mutex` that bypasses `RWLockImpl`, so the millisecond clamp added by ClickHouse#106961 never reached them. One clamp at each return also covers `max_execution_time`, because the body has already collapsed both settings into `lock_timeout`. `ThreadPoolImpl::scheduleImpl` builds the nanosecond deadline itself, out of a microsecond count whose parameter was `uint64_t`: the declared domain admitted values that cannot be converted, and the conversion at the call destroyed the caller's sign. Widening `wait_microseconds` to `Int64` and clamping once inside the pool covers all three of its callers and any future one, and no call site needed changing because all three already pass `Poco::Timespan::totalMicroseconds()`. `ConcurrentBoundedQueue` is the in-tree precedent for clamping inside an owned callee whose timeout parameter is unsigned. Measured both directions on one ASAN+UBSan build: seven fixtures abort before the change, at `__chrono/duration.h:93`, with the multiplier identifying the unit; all seven return correct results after it, while the same fixtures at the default timeout, at `max_threads = 1`, and with `max_execution_time = 10` are unaffected in both arms. Co-Authored-By: Claude Opus 5 <[email protected]>
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]>
Internal second-model review (2 gate rounds; 0 findings on the final pass)
💡 Contention coverage, noted and deliberately not added. The four arms take uncontended locks, so they would also pass if the helper returned zero unconditionally. That mapping is pinned instead by 💡 Only the sanitizer abort is measured (four arms, both signs, at |
|
Workflow [PR], commit [292e0d3] Summary: ✅
AI ReviewSummaryThis PR routes the Final Verdict✅ No findings. LLVM Coverage ReportMeasured on commit 292e0d3.
Changed lines: Changed C/C++ lines covered: 10/12 (83.33%) · Uncovered code |
|
cc @azat @kssenii, could you review this? The |
|
I extended this sweep to the rest of the tree (all 249 1.
|
| consumer | clamped? |
|---|---|
src/Interpreters/executeQuery.cpp:2939 |
yes, saturatedMilliseconds |
src/Server/TCPHandler.cpp:1537 |
yes, saturatedMilliseconds |
src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp:268 |
no — raw .totalMilliseconds() |
It is a SettingsSeconds, so it accepts negatives natively: float64AsSecondsToTimespan (SettingsFields.cpp:337-350) only rejects |d*1e6| > Int64, i.e. down to about −9.22e12 s. The wait at :269 is future::wait_for, also unsafe. SET wait_for_async_insert_timeout = -1e13 gives timeout_ms = -1e16.
Which primitives actually need clamping
Worth having explicitly, because it takes a lot of sites off the list — I checked the pinned contrib/llvm-project libc++:
| primitive | behaviour | overflows? |
|---|---|---|
this_thread::sleep_for(d), non-nanoseconds d |
clamps at duration<long double>(9223372036.0L) → nanoseconds::max(), and skips d <= 0 (__thread/this_thread.h:38-53) |
no |
cv::wait_for(lk, d) — no predicate |
__safe_nanosecond_cast + d <= zero() → timeout (condition_variable.h:142-155) |
no |
cv::wait_for(lk, d, pred) — with predicate |
wait_until(lk, steady_clock::now() + d, pred), raw promotion (condition_variable.h:192-194) |
yes |
cv::wait_until(lk, tp) where tp is already ns-rep |
no unit multiply | no (risk moves to whoever computed tp) |
future::wait_for(d) |
wait_until(now() + rel_time) |
yes |
shared_mutex::try_lock_for(d) |
try_lock_until(now() + rel_time) |
yes — this is what this PR's three helpers feed |
So every sleep_for site is safe by construction regardless of the setting value, and so is the non-predicate wait_for. That rules out, among others, MergeTreeData.cpp:3515, :7812, :7855, PartMovesBetweenShardsOrchestrator.cpp:549/:619, InstrumentationManager.cpp:517 and DiskAccessStorage.cpp:354 — all of which look alarming by provenance but cannot overflow.
Lower priority — server-config only, no query-level exposure
src/Common/CgroupsMemoryUsageObserver.cpp:70—cgroups_memory_usage_observer_wait_time(andkeeper_server.cgroups_memory_observer_wait_time). Seconds unit, so the lowest threshold of the set at 9,223,372,036; only!= 0is filtered.src/Common/Scheduler/CPULeaseAllocation.cpp:607—cpu_slot_preemption_timeout_ms(ServerSettings.cpp:1268, unvalidatedUInt64); the== milliseconds::max()guard at:600is equality-only.programs/server/Server.cpp:3965—shutdown_wait_unfinished:wait_start + std::chrono::milliseconds(wait_limit_seconds * 1000)has two problems, the unsigned* 1000wrap and then the ms→ns promotion when added to a ns-reptime_point. Clamping this one line covers both consumers (RefreshSet::joinBackgroundTasksat:3976andThreadPoolImpl::waitUntilat:3977);ThreadPool.cpp:690itself is fine, since it receives an already-computedtime_point.
Also noted, not this class: ExternalLoader.cpp:936/:966 survive only because WAIT is exactly Duration::max() and is short-circuited by an == test — any large-but-not-max() value would fall into the predicate wait_for. Fragile API rather than a live defect.
|
Thanks, the hand-over lands cleanly. Taking both as successor PRs, and leaving this one as is. I re-verified the two load-bearing claims at source rather than re-deriving your primitive table, and both hold: One sequencing note you may not have: the microsecond clamp site 1 wants, For site 1 the impact statement will report what I measure under real memory pressure rather than what the code path argues. If I cannot reach the wait I will say that instead of clamping on an argument. The server-config-only three are recorded but not promised yet: with no query-level exposure the impact cannot come from a |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units9 translation units recompiled, 34 s compile time in total, 9 of them have a recent master baseline. |
CI finish ledger - 292e0d3Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260904-090000 |
|
The first of the two sites you handed over in #117974 (comment) is now a separate pull request: #118040. It wraps the The second site, |
|
Fixing PR for the |
…protocol `wait_for_async_insert_timeout` is a `Seconds` setting, and its validator `float64AsSecondsToTimespan` rejects only values whose microsecond product leaves `Int64`. Any magnitude up to about `9.22e12` seconds is therefore legal, negatives included, and the setting is client-settable per request from the URL query string of a prometheus `write` handler. `insertBlock` passed that raw millisecond count to `std::future::wait_for`. The pinned libc++ turns `wait_for(d)` into `wait_until(steady_clock::now() + d)`, and `steady_clock::duration` is nanoseconds, so the converting `duration` constructor multiplies milliseconds by 1'000'000 in a signed 64-bit representation. That multiply overflows above about `9.22e9` seconds, in both directions, and the wait deadline becomes undefined. Signed overflow is undefined behaviour, so the combined ASan and UBSan build, which carries `-fno-sanitize-recover=all`, aborts the server; an ordinary build silently wraps the deadline. Standalone against the pinned libc++, `+1e13` and `-1e13` milliseconds both report `signed integer overflow` at `__chrono/duration.h:93` and exit non-zero, while `0` and the one-year cap exit cleanly. The setting has exactly three consumers in `src/`. `executeQuery.cpp` and `TCPHandler.cpp` already clamp with `saturatedMilliseconds`; this was the missed third, because these lines were added after the other two were fixed. Using the same helper keeps the three consistent and reuses the existing one-year cap; negatives clamp to `0`, which is what `wait_for` already treats as "already expired", so the shipped behaviour for a negative timeout is unchanged in kind and merely becomes well-defined. The message reports the clamped value rather than the raw setting, matching `TCPHandler.cpp`: the sentence names the timeout that was actually applied, so printing the raw value would assert a wait that did not happen. Measured over HTTP with a three second flush deadline. Without the clamp, `+1e10` seconds wraps the deadline into the past and the request fails with 503 instead of 204, and `-1e10` seconds wraps it positive so the request returns 204 after waiting on an undefined deadline. With the clamp the first returns 204 and the second returns 503 with `(0 ms)` immediately. An in-range control of one millisecond reports `(1 ms)` in both builds, which is the only arm that distinguishes this fix from an implementation that clamps every value. Left alone deliberately: unlike both other consumers, this site does not consult `wait_for_async_insert` and waits unconditionally once `async_insert` is set. That is intentional for remote-write durability, and it is why the timeout maps to a retryable 503. Reported by @tiandiwonder, who found this site while sweeping the wait primitives in `src/` and handed it over rather than growing ClickHouse#117974. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Site 1 of the hand-over in #117974 (comment) is now #118227, after #118040 covered site 2. One measurement worth passing back for the primitive table: the predicate |
b922ae0
Related: #106961
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 the effective table lock timeout, the smaller of
lock_acquire_timeoutand a non-zeromax_execution_time, was above roughly 9.2e9 seconds or a large negative value. Reading or writing aLog,TinyLog,StripeLogorFiletable built the lock deadline from it without bounding it first, so the deadline was undefined and the wait was no longer bounded by the setting; under the Undefined Behavior Sanitizer the server aborted.Description
Root cause.
libc++turnstry_lock_for(d)intotry_lock_until(now() + d)and convertsdto nanoseconds first (__chrono/duration.h:93), multiplying astd::chrono::secondsargument by1'000'000'000.SettingFieldTimespanrejects only values that do not fit Int64 microseconds, about three orders of magnitude above the first value that overflows a nanosecond deadline, and no constraint caps the setting. No contention is required: the overflow is in the argument to the wait, before any predicate is checked. The product is undefined rather than merely large, so the deadline stops bounding the wait; what reproduces on demand is the sanitizer abort below.The three
getLockTimeouthelpers inStorageFile,StorageLogandStorageStripeLogreturn astd::chrono::secondsfor the storage's ownstd::shared_timed_mutex, bypassingRWLockImpl, so the millisecond clamp added by #106961 never reached them.Change. Three behavioural lines: each helper returns
saturatedSeconds(...)in place ofstd::chrono::seconds{...}.saturatedSecondsalready exists, with the same one-year bound and a negative count mapping to 0. The clamp sits at each helper's singlereturn, so it also coversmax_execution_time(the body has already reduced both settings to the smaller one) and all fiveStorageFilelock sites. No call site changed;TinyLogis registered byStorageLog.cppand shares that helper.Validation. Both directions on one ASAN+UBSan build. Before, each of the four arms aborts:
After, all four return correct results, and six controls (default timeout, in-range timeout,
max_execution_time = 10) are unaffected in both arms. Four arms were added to04327_wait_timeout_chrono_overflow; 50 randomized runs pass.The microsecond sibling carrier of the same setting is fixed by #117898, which is why this PR stops at the seconds carrier.
Workflow [PR]
Sync PR [sync-upstream/pr/117974]
Version info
26.9.1.889(included in26.9and later)