Repository navigation
Fix signed integer overflow in condition_variable::wait_for with huge timeouts - #106961
Conversation
Pre-PR validation gate
Repro stack matched the CI finding exactly: Session id: cron:clickhouse-worker-slot-2:20260610-110500 |
|
cc @serxa @KochetovNicolai - could you review this? It clamps user-controlled wait timeouts (interactive_delay, queue_max_wait_ms, replace_running_query_max_wait_ms) to one year before they reach condition_variable::wait_for, fixing a serverfuzz-found UBSan signed-integer-overflow in the ms->ns conversion. It generalizes the same one-year cap @ serxa added for CancellationChecker in #96450 to the ConcurrentBoundedQueue and ProcessList wait sites. |
|
Workflow [PR], commit [9197f40] Summary: ✅
AI ReviewSummaryThis PR closes most of the user-controlled Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 194/202 (96.04%) · Uncovered code |
Pre-PR validation gate (update for 4d71e32: QueryPriorities clamp + priority-wait test)
Session id: cron:clickhouse-worker-slot-29:20260610-200000 |
Pre-PR validation gate (update for 8410f83: source-level saturation + bugfix-validation fix)
Session id: cron:clickhouse-worker-slot-9:20260610-225430 |
The async insert queue reads async_insert_busy_timeout_max_ms, async_insert_busy_timeout_min_ms and async_insert_poll_timeout_ms straight into std::chrono::milliseconds. A value such as 100000000000000 ms is below the SettingFieldMilliseconds saturation cap (INT64_MAX / 1000), so the source-level saturation does not catch it, yet it still overflows the millisecond-to-nanosecond conversion (x * 1'000'000) that libc++ performs for both the `now + timeout_ms` deadline in pushDataChunk/processBatchDeadlines and the are_tasks_available.wait_for() call. That aborted the server under UBSan (release silently wrapped to an immediate timeout). Route every read of these three settings through saturatedMilliseconds(), the same one-year clamp already used for the other wait_for sites, so no user-controlled wait timeout can reach a chrono operation outside the representable range. Found by serverfuzz, reported by the CI review bot on PR ClickHouse#106961 after the earlier condition_variable::wait_for clamps. The validateSettings zero-check is left as is, it neither adds a duration to a time_point nor waits. Repro (UBSan abort at __chrono/duration.h:93 before this change): INSERT INTO t SETTINGS async_insert = 1, wait_for_async_insert = 0, async_insert_use_adaptive_busy_timeout = 0, async_insert_busy_timeout_max_ms = 100000000000000 VALUES (1); Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (update for 2afffb4: async insert wait-timeout clamp)
Session id: cron:clickhouse-worker-slot-24:20260610-225430 |
Pre-PR validation gate (fixup 3d0c788, test 04329)This fixup is test-only (no source change) and addresses the CI bot's test-hygiene change-request on
Session id: cron:clickhouse-worker-slot-18:20260611-004400 |
Pre-PR validation gate (fixup abfe187)Covers the two bot change-requests on 3d0c788 (
Session id: cron:clickhouse-worker-slot-7:20260611-064000 |
Pre-PR validation gate (fixup 9a2f8b2)Addresses the two 6th-round
Session id: cron:clickhouse-worker-slot-3:20260611-081600 |
Update for 56d9021: remove sanitizer-only async-insert / future-wait testsRemoved These two assert only that the server stays alive with a huge Coverage is unchanged in substance: the use-site clamps (
Session id: cron:clickhouse-worker-slot-2:20260611-085600 |
Pre-PR validation gateCovers HEAD
Session id: cron:clickhouse-worker-slot-7:20260611-094600 |
|
CI finished on 1a8068c. One non-passing check, not PR-caused:
All public checks green. No PR-caused failures. Ready for review. (cron:our-pr-ci-monitor:20260611-210000) |
The async insert queue reads async_insert_busy_timeout_max_ms, async_insert_busy_timeout_min_ms and async_insert_poll_timeout_ms straight into std::chrono::milliseconds. A value such as 100000000000000 ms is below the SettingFieldMilliseconds saturation cap (INT64_MAX / 1000), so the source-level saturation does not catch it, yet it still overflows the millisecond-to-nanosecond conversion (x * 1'000'000) that libc++ performs for both the `now + timeout_ms` deadline in pushDataChunk/processBatchDeadlines and the are_tasks_available.wait_for() call. That aborted the server under UBSan (release silently wrapped to an immediate timeout). Route every read of these three settings through saturatedMilliseconds(), the same one-year clamp already used for the other wait_for sites, so no user-controlled wait timeout can reach a chrono operation outside the representable range. Found by serverfuzz, reported by the CI review bot on PR ClickHouse#106961 after the earlier condition_variable::wait_for clamps. The validateSettings zero-check is left as is, it neither adds a duration to a time_point nor waits. Repro (UBSan abort at __chrono/duration.h:93 before this change): INSERT INTO t SETTINGS async_insert = 1, wait_for_async_insert = 0, async_insert_use_adaptive_busy_timeout = 0, async_insert_busy_timeout_max_ms = 100000000000000 VALUES (1); Co-Authored-By: Claude Opus 4.8 <[email protected]>
1a8068c to
146c6a5
Compare
|
Rebased onto current master to resolve a merge conflict. The only conflict was a trivial include-ordering collision in Session: cron:clickhouse-worker-slot-4:20260612-071200 |
|
CI fully finished on HEAD One failing check, not caused by this PR:
No PR-caused failures. Awaiting review/merge. |
`SettingFieldTimespan` now rejects a value that does not fit into `Int64` microseconds instead of wrapping it (`microsecondsFromUnits` and `float64AsSecondsToTimespan` both throw), and `parseFromString` for a `Seconds` setting already routes through the checked conversion. That supersedes the saturating `unitToMicroseconds` this branch added, so the `SettingsFields` side of the change and its unit tests are dropped in favour of master's, which cover the same ground with the stricter rule. `04327_wait_timeout_chrono_overflow` loses its five `Milliseconds`-typed settings assertions for the same reason: those values are now rejected at the setting, and `gtest_settings` covers the rejection. What the test still covers is the settings that reach a `wait_for` unchecked, above all the plain `UInt64` `interactive_delay`. `PoolBase` keeps master's `LogFrequencyLimiter` around the "No free connections in pool" message and applies `saturatedMilliseconds` to the timeout it reports and waits on.
| AlterLockHolder lock{alter_lock, std::defer_lock}; | ||
|
|
||
| if (!lock.try_lock_for(std::chrono::milliseconds(acquire_timeout.totalMilliseconds()))) | ||
| if (!lock.try_lock_for(saturatedMilliseconds(acquire_timeout.totalMilliseconds()))) |
There was a problem hiding this comment.
lock_acquire_timeout is documented as 0 — No locking timeout in src/Core/Settings.cpp:5214-5222, but this path still turns that value into an immediate poll. saturatedMilliseconds(0) returns 0ms, and std::timed_mutex::try_lock_for(0ms) does not mean "wait forever" — it fails immediately if the lock is contended.
So ALTER ... SETTINGS lock_acquire_timeout = 0 still times out at once instead of waiting indefinitely, and the same problem remains in the touched lightweight-update waits in StorageMergeTree.cpp. Please keep an explicit unlimited branch for zero (for example, lock.lock() / cv.wait(...)) and reserve saturatedMilliseconds() for strictly positive timeouts.
There was a problem hiding this comment.
The finding is correct, and I reproduced it. It is also pre-existing on master and outside this PR's concern, so I am not folding it in here.
Measured on a debug build of master 2169bf5d402d (server buildId() asserted equal to the binary's build id). A MergeTree table, one long lightweight UPDATE holding the lock, then a second UPDATE at all defaults except the timeout:
| arm | setting | result |
|---|---|---|
| A | lock_acquire_timeout=0 |
Code: 159 TIMEOUT_EXCEEDED, "Failed to get lock in 0 ms ... auto mode", after 0.113 s |
| B | lock_acquire_timeout=300 |
waited 54.95 s, then succeeded |
So a documented "no locking timeout" is honoured as "fail immediately", while a finite timeout waits. Arm B is the control that makes arm A meaningful.
Two corrections to the framing:
- It only bites under contention. Uncontended,
try_lock_for(0ms)succeeds: 3/3 runsrc=0with no error.try_lock_foron a free mutex acquires it regardless of the duration, so the claim needs that qualifier. - The site I could actually reach is not
tryLockForAlter.ALTER TABLE ... ADD COLUMN SETTINGS lock_acquire_timeout=0returnedrc=0on both arms while a slowALTER ... UPDATEran, becausealter_lockis not held across the mutation wait in that shape. The reachable sites are the lightweight-update waits:PatchPartsLock.cpp:284(automode, the default) andStorageMergeTree.cpp:1145(syncmode), plusStorageMergeTree.cpp:3723. I did not demonstrateIStorage.cpp:93reachable; I am reporting that as not measured, not as refuted.
On scope: this is pre-existing, not introduced here. On master, IStorage.cpp:93 is already try_lock_for(std::chrono::milliseconds(acquire_timeout.totalMilliseconds())) and StorageMergeTree.cpp:3723 is already wait_for(lock, std::chrono::milliseconds(timeout_ms), ...), with no zero-handling in either function. This PR's edit at both sites is a pure conversion swap, std::chrono::milliseconds(v) to saturatedMilliseconds(v); nothing about zero changes. So saturatedMilliseconds is not what makes zero an immediate poll, and adding an unlimited branch here would be a behaviour change (a query that fails fast today would block indefinitely) bundled into a PR whose single concern is removing signed overflow at the top of the range.
Your cited precedent is the right shape, and I verified it: RWLock.cpp:105-107 maps a zero timeout to time_point::max() and then waits with wait_until at :198. There is also merged precedent for the class in #112380, which made connection_pool_max_wait_ms = 0 an infinite timeout. I have filed this separately so it gets its own review rather than extending this one.
There was a problem hiding this comment.
Closing the loop here: I am not opening a separate PR for this.
The zero arm still reproduces on master (debug 26.8.1.1): contended, lock_acquire_timeout=0 fails in 0.09 to 0.14 s, 3/3, against a finite-timeout control that waits 33.8 s. But mapping zero to an infinite wait the way RWLockImpl::getLock does would be worse than the current rejection, because these two waits poll nothing. With lock_acquire_timeout=120 and max_execution_time=2, a contended update ran 113.21 s before failing, while the same binary honours max_execution_time=2 on a slow SELECT in 2.10 s; KILL QUERY ... SYNC against a contended waiter returned only after 108.11 s. An unbounded wait at these sites would be unkillable.
#114125 already rewrites both of them, adds the cancellation polling that is missing today, and keeps a zero timeout succeeding uncontended while still failing under contention. The behaviour is settled there, so there is nothing left for a separate PR.
| { | ||
| std::unique_lock lock{mutex}; | ||
| bool processed = wait_current_task_change.wait_for(lock, std::chrono::seconds(timeout), [&]() | ||
| bool processed = wait_current_task_change.wait_for(lock, saturatedSeconds(timeout), [&]() |
There was a problem hiding this comment.
database_replicated_initial_query_timeout_sec is documented as 0 — Unlimited in src/Core/Settings.cpp:6208-6215, but saturatedSeconds(0) still gives 0s, so this becomes wait_for(0s) and returns immediately on a lagging replica.
That means CREATE ... SETTINGS database_replicated_initial_query_timeout_sec = 0 still throws UNFINISHED instead of waiting without a timeout. This needs the same separate zero/unlimited branch that RWLockImpl::getLock already uses before the saturated positive-timeout path.
There was a problem hiding this comment.
Correct, and the same disposition applies as for the lock_acquire_timeout comment: real, pre-existing, and its own change.
database_replicated_initial_query_timeout_sec is documented "0 — Unlimited" at Settings.cpp:6214, and wait_for(lock, seconds(0), pred) returns immediately when the predicate is false, so = 0 throws UNFINISHED instead of waiting. I confirmed the primitive directly: condition_variable::wait_for(lock, seconds(0), pred) with a false predicate returns false in 58 us, while the same wait at seconds(2) returns true after 300 us when the predicate becomes true.
On master, DatabaseReplicatedWorker.cpp:481 is already wait_for(lock, std::chrono::seconds(timeout), ...) with no zero-handling anywhere in the function, so the behaviour predates this PR. The edit here is std::chrono::seconds(timeout) to saturatedSeconds(timeout), a conversion swap that leaves zero exactly as it was.
saturatedSeconds is deliberately a clamp for the positive range and does not carry unlimited semantics, so reserving it for strictly positive timeouts is the right call. The fix belongs where RWLockImpl::getLock puts it, in an explicit zero branch at the wait site, and it is tracked separately.
There was a problem hiding this comment.
Same disposition as the lock_acquire_timeout thread: no separate PR.
This site is the one where an infinite wait would actually be safe, since the predicate is cancellation-aware (StopToken plus StopCallback at :475-476, throwing QUERY_WAS_CANCELLED at :494). What is missing is impact: I have no observed user-visible failure for database_replicated_initial_query_timeout_sec = 0, only the cv.wait_for(seconds(0), pred) primitive measurement, which is an argument rather than a reproduction. I am not changing behaviour on that basis.
The two sites I could reproduce are the lightweight-update waits, and #114125 covers those.
CI finish ledger — 624c33fEvery 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 175 check-runs, all completed, 0 queued or in progress,
Session id: cron:our-pr-ci-monitor:20260806-060000 |
serxa
left a comment
There was a problem hiding this comment.
This is fantastic, why aren't we merging this?
Resolve the single conflict in AsynchronousInsertQueue.cpp: master wrapped the shard.last_insert_time read in TSA_SUPPRESS_WARNING_FOR_READ while this branch clamps the timeout through saturatedMilliseconds(). Both are kept.
|
Thanks. It was not review state: the branch had drifted into a conflict with master, so it was I merged master in just now ( I did not rebase, so CI is running on the new head. Three checks were red on the previous head, all with owners and none from this diff: |
| AlterLockHolder lock{alter_lock, std::defer_lock}; | ||
|
|
||
| if (!lock.try_lock_for(std::chrono::milliseconds(acquire_timeout.totalMilliseconds()))) | ||
| if (!lock.try_lock_for(saturatedMilliseconds(acquire_timeout.totalMilliseconds()))) |
There was a problem hiding this comment.
This lock_acquire_timeout sweep is still incomplete. StorageFile, StorageLog, and StorageStripeLog still turn the same setting into raw std::chrono::seconds and hand it straight to std::shared_timed_mutex timed-lock constructors (StorageFile.cpp:1408-1417 / 1500 / 1517, StorageLog.cpp:955-971, StorageStripeLog.cpp:376-407). Under contention, lock_acquire_timeout = 100000000000 on those engines still reaches libc++'s seconds -> nanoseconds conversion and can hit the same UBSan signed-overflow / immediate-timeout behavior this PR is fixing for IStorage and MergeTree.
Please clamp those helpers too (for example, make their local getLockTimeout return saturatedSeconds(...), or route them through the same RWLockImpl / Poco::Timespan path) so lock_acquire_timeout is safe across all storage families.
There was a problem hiding this comment.
The three citations are accurate, and the mechanism is worse than described: no contention is
needed. libc++ implements try_lock_for(rel) as try_lock_until(steady_clock::now() + rel)
(shared_mutex:229), so the seconds -> nanoseconds cast runs before any lock attempt. A
standalone UBSan build of exactly std::unique_lock<std::shared_timed_mutex>{m, seconds{N}} on an
uncontended mutex: N = 9223372036 acquires cleanly, N = 9223372037 gives
signed integer overflow: 9223372037 * 1000000000.
I am not clamping those three helpers here, for two measured reasons.
First, they are shadowed, so a clamp there is not verifiable by a test in this pull request. A bare
SELECT 1 with no table involved already aborts at the same threshold through a milliseconds site:
SELECT 1 SETTINGS lock_acquire_timeout = 9223372037 gives
signed integer overflow: 9223372037000 * 1000000 (multiplier 1e6, not 1e9). Both conversions
reach the same 9223372037e9 ns, so the thresholds are arithmetically identical and whichever site
runs first wins. Log, StripeLog and TinyLog reads report the 1e6 multiplier too, and
max_execution_time = 10, which clamps only these three seconds helpers, does not change it.
Second, the sweep is wider than the three files named. At this head, lock_acquire_timeout is still
converted unclamped at 12 sites in 9 files: QueryPlanOptimizationSettings.cpp, PlannerJoins.cpp,
StorageJoin.cpp (3), StorageSystemColumns.cpp, StorageSystemPartsBase.cpp,
PatchPartsLock.cpp (2), plus the three above. Patching three of them leaves nine behind, and none
of these files is in this pull request's change map.
This pull request is approved and mergeable after 10 weeks. Rather than extend its scope a
seventeenth time, I have filed the whole lock_acquire_timeout sweep separately so it gets its own
review, and I will post that fix link back in this thread. Also worth noting for whoever takes it:
the setting layer does not bound this. SettingFieldSeconds accepts up to 9223372036854 and only
rejects at 9223372036855 with Cannot convert seconds to microseconds, which is three orders of
magnitude above the first overflowing value, 9223372037.
There was a problem hiding this comment.
Correction to my previous reply: my "they are shadowed" claim is wrong, and the bot's ask is
verifiable in this pull request after all.
I generalised from table engines to table functions. A named table is resolved by the analyzer,
which takes the RWLockImpl table lock first (IdentifierResolver.cpp:362 -> IStorage.cpp:54
-> RWLock.cpp:125), so Log, StripeLog and File-engine reads do all abort through the
milliseconds site, as I said. A table function never takes that lock, so it reaches the seconds
helper directly:
SELECT * FROM file('/dev/null', 'LineAsString') SETTINGS lock_acquire_timeout = 9223372037
duration.h:93: signed integer overflow: 9223372037 * 1000000000
Multiplier 1e9, and it symbolizes to shared_timed_mutex::try_lock_shared_for inlined into
StorageFileSource::StorageFileSource at StorageFile.cpp:1500. The bare SELECT 1 on the same
binary and the same value still gives 1e6, so the two sites are distinguishable by the multiplier
in a single run. My max_execution_time = 10 claim was wrong for the same reason: on the table
function it removes the abort entirely, which is a clean positive control that these three helpers
are the code under test.
Two further corrections while I am here. There are two overflow sites, not one: below 9223372037
the abort is the now() + d addition at duration.h:403, at and above it the multiplication at
:93. And my "12 sites in 9 files" census counted conversions, not hazards. Of those, the
StorageJoin, StorageSystemColumns, StorageSystemPartsBase, PlannerJoins and
QueryPlanOptimizationSettings conversions all funnel into RWLockImpl::getLock, which this pull
request already clamps; the ThreadPool::scheduleOrThrow ones take microseconds, the setting's
native unit, so there is no multiplication to overflow; and PatchPartsLock goes through
Poco::Event::tryWait, which splits into a timespec rather than an Int64 nanosecond product.
The real residual is exactly the three helpers you named.
That leaves a question that is yours, not mine. saturatedSeconds() currently has one production
caller in this branch, and the fix is three one-line returns plus one test arm on the existing
04327 test, using file('/dev/null') so it needs no fixture and stays parallel-safe. Adding it
here completes a claim this description already makes; holding it for a follow-up keeps an approved
branch untouched at the cost of a second review on the same helper. @serxa, you approved this one -
which do you prefer? I will do either, and I am not pushing anything to this branch until you say.
There was a problem hiding this comment.
Fixed for the seconds carrier in #117974: the getLockTimeout helpers in StorageFile, StorageLog and StorageStripeLog, which TinyLog shares, now clamp the count before it becomes a std::chrono::seconds. The microsecond carrier of the same setting, in ThreadPoolImpl::scheduleImpl, is covered by #117898, so nothing raised in this thread is left without a fix.
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 units423 translation units recompiled, 3294 s compile time in total, 423 of them have a recent master baseline. |
…ax-wait-ms The only conflict is in PoolBase::get, and both sides of it are mine: master now carries the shared saturatedMilliseconds() clamp from ClickHouse#106961, while this branch restructures the same wait into deadline-bounded slices. Kept this branch's slice loop, since a plain wait_for without a deadline check is exactly the defect the branch fixes: a positive connection_pool_max_wait_ms would go back to being a wake-up interval rather than a deadline. Dropped the branch's own max_wait_ms constant in favour of saturatedMilliseconds(), so the overflow clamp on the deadline is the one shared by every other user-controlled wait_for site. The clamp is now one year instead of ~146 years; both are far beyond any timeout a caller can wait out, and negative values still mean "infinite" via has_deadline, which is evaluated before the clamp. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Resolve the ConcurrentBoundedQueue.h conflict by taking master's side. PR ClickHouse#106961 merged first and applies its own saturatedMilliseconds() to both wait_for() calls in that file, so the queue no longer needs this branch's edit. Keeping the branch's version would revert a merged change. The Keeper coordination sites this PR exists for are untouched by that merge and remain the whole subject of the PR.
The queue conversion this comment pointed at is no longer part of this branch: PR ClickHouse#106961 merged its own saturation into ConcurrentBoundedQueue, so the merge above takes that file from master unchanged. The two cases stay, because they are the only behavioural coverage of that merged fix.
…oordination Review asked how the new tests are relevant and whether they can be removed. Both new files are gone. src/Common/tests/gtest_saturated_wait_duration.cpp held seven cases restating the helper's own arithmetic and three exercising ConcurrentBoundedQueue, a file this PR no longer touches since ClickHouse#106961 merged. Neither group pins a line changed here. Three cases survive because they fail without the production change, and they move into the existing src/Coordination/tests/gtest_coordination.cpp rather than into a module of their own. That module already declares KeeperDispatcherTestAccessor a friend of KeeperDispatcher, so reaching the private interruptibleSleep no longer needs the two friend declarations this PR was adding to KeeperDispatcher.h. That header is back to its master content: no production file is modified for the sake of a test. Each surviving case reddens when the line it covers is reverted: KeeperContext.WaitCommittedUptoKeepsHugeTimeout and KeeperDispatcher.InterruptibleSleepKeepsHugePeriod fail on the raw std::chrono::milliseconds conversion, and KeeperDispatcher.InterruptibleSleepReturnsAtOnceForNonPositivePeriod fails when the site uses the upper-only helper variant instead of the wait variant. Test surface: 453 lines removed, 132 added.
…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]>
A wait-timeout setting that reaches
std::condition_variable::wait_forunchecked overflows the chrono conversion inside it. libc++ evaluateswait_for(d)assteady_clock::now() + din nanoseconds, multiplying a millisecond duration by 1000000: a timeout above ~9.2e12 ms overflows Int64, and one above the Int64 millisecond range even turns into a negative duration, so the wait returns at once and the caller busy-loops instead of waiting. UBSan aborts the server; a release build silently wraps.The setting that reaches it in practice is
interactive_delay, a plain unboundedUInt64of microseconds: the server waitsinteractive_delay / 1000milliseconds for the next result chunk inConcurrentBoundedQueue::popImpl, through the lazy output format, on both theTCPHandlerand theclickhouse-localpath.Found by serverfuzz on master, and again in the stress test of an unrelated pull request — https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112177&sha=e601607e228ad5d736ad491220ebf4b62d531d51&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29 (#112177):
Reproduces deterministically:
Fix: clamp the timeout to one year before constructing the chrono duration, via a small shared helper
saturatedMilliseconds. The same cap is already used forCancellationChecker(#96450); it is applied here to the remainingwait_forsites that take a user-controlled millisecond timeout, andsaturatedSeconds/saturatedSecondsFromcover the seconds-typed timeouts and the query cache expiry built asnow() + seconds(query_cache_ttl).A
Milliseconds- orSeconds-typed setting can no longer carry such a value in the first place:SettingFieldTimespanrejects a value that does not fit into Int64 microseconds, so the clamp there is only defence in depth. That check landed on master after this branch was cut and supersedes the saturating conversion this pull request originally added toSettingsFields, which is dropped along with its unit tests in favour of master's stricter ones. What is left for the clamp is every setting that is not a timespan — above allinteractive_delay.Keeper has its own coordination waits with a different bound; they are handled separately in #112088.
Related: #112088
Related: #112177
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 a wait-timeout setting, such as
interactive_delay, was set to a huge value: the wait could time out immediately instead of waiting, and the server could abort under the Undefined Behavior Sanitizer.Workflow [PR]
Sync PR [sync-upstream/pr/106961]