Skip to content

Fix signed integer overflow in condition_variable::wait_for with huge timeouts - #106961

Merged
alexey-milovidov merged 20 commits into
ClickHouse:masterfrom
groeneai:fix-wait-for-chrono-overflow
Aug 21, 2026
Merged

alexey-milovidov merged 20 commits into
ClickHouse:masterfrom
groeneai:fix-wait-for-chrono-overflow

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

A wait-timeout setting that reaches std::condition_variable::wait_for unchecked overflows the chrono conversion inside it. libc++ evaluates wait_for(d) as steady_clock::now() + d in 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 unbounded UInt64 of microseconds: the server waits interactive_delay / 1000 milliseconds for the next result chunk in ConcurrentBoundedQueue::popImpl, through the lazy output format, on both the TCPHandler and the clickhouse-local path.

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):

/ClickHouse/contrib/llvm-project/libcxx/include/__chrono/duration.h:93:79: runtime error:
signed integer overflow: 18584892780430 * 1000000 cannot be represented in type '_Ct' (aka 'long long')
...
#6  ConcurrentBoundedQueue<DB::Chunk>::popImpl<true>(...)  src/Common/ConcurrentBoundedQueue.h:73
#8  DB::LazyOutputFormat::getChunk(unsigned long)          src/Processors/Formats/LazyOutputFormat.cpp:25
#11 DB::TCPHandler::processOrdinaryQuery(DB::QueryState&)  src/Server/TCPHandler.cpp:1540

SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior

Reproduces deterministically:

clickhouse-local --query "SELECT 1 SETTINGS interactive_delay = 100000000000000000"

Fix: clamp the timeout to one year before constructing the chrono duration, via a small shared helper saturatedMilliseconds. The same cap is already used for CancellationChecker (#96450); it is applied here to the remaining wait_for sites that take a user-controlled millisecond timeout, and saturatedSeconds/saturatedSecondsFrom cover the seconds-typed timeouts and the query cache expiry built as now() + seconds(query_cache_ttl).

A Milliseconds- or Seconds-typed setting can no longer carry such a value in the first place: SettingFieldTimespan rejects 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 to SettingsFields, 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 all interactive_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):

  • 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 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]

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. clickhouse-local --query "SELECT 1 SETTINGS interactive_delay = 100000000000000000" aborts 3/3 on a master ASAN+UBSan binary (UBSan signed-integer-overflow at __chrono/duration.h:93).
b Root cause explained? wait_for(milliseconds(N)) is evaluated by libc++ as steady_clock::now() + d in nanoseconds, casting the millisecond duration to ns by N * 1000000. For N above ~9.2e12 ms this overflows int64 (UB). The timeout comes straight from a user setting (interactive_delay / queue_max_wait_ms / replace_running_query_max_wait_ms), so any near-max value triggers it.
c Fix matches root cause? Yes. The millisecond timeout is clamped to one year before the chrono duration is built, so the ns multiplication can never overflow. Same approach already used for CancellationChecker (#96450).
d Test intent preserved / new tests added? New regression test 04327_wait_timeout_chrono_overflow.sql added. It runs a query with a huge interactive_delay; on an unfixed binary it aborts under UBSan, on the fixed binary it returns normally.
e Both directions demonstrated? Yes. Unfixed master ASAN+UBSan binary: rc=134 (overflow) 3/3. Rebuilt ASAN+UBSan binary with the fix: rc=0, correct result, no UBSan finding 3/3. Normal small timeout still works.
f Fix is general, not a narrow patch? Yes. I surveyed all wait_for(milliseconds(setting)) sites and fixed every one taking a user-controlled timeout via a shared helper: ConcurrentBoundedQueue (push + pop, the serverfuzz site) and ProcessList::insert (queue_max_wait_ms, replace_running_query_max_wait_ms). Sites with fixed/small constant timeouts cannot overflow and were left unchanged. This addresses the root cause (unbounded timeout reaching chrono), not just the one symptom site.

Repro stack matched the CI finding exactly: ConcurrentBoundedQueue<Chunk>::popImpl -> LazyOutputFormat::getChunk -> PullingAsyncPipelineExecutor::pull -> TCPHandler::processOrdinaryQuery.

Session id: cron:clickhouse-worker-slot-2:20260610-110500

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9197f40]

Summary: ✅


AI Review

Summary

This PR closes most of the user-controlled chrono overflow holes by clamping millisecond and seconds waits before they reach wait_for/deadline arithmetic, and the changelog metadata is fine. I do not think it is ready to merge yet, because one seconds-based backup wait is still completely unclamped and the lock_acquire_timeout sweep misses some storage engines that still feed huge durations directly into std::shared_timed_mutex.

Findings

❌ Blockers

  • [src/Backups/BackupKeeperSettings.cpp:39, src/Backups/BackupCoordinationStageSync.cpp:1262-1265] backup_restore_finish_timeout_after_error_sec is still stored as raw std::chrono::seconds and passed unchanged to state_changed.wait_for. A value such as 100000000000 still reaches libc++'s seconds-to-nanoseconds conversion and can raise the same signed-overflow / immediate-timeout behavior this PR is fixing elsewhere.
    Suggested fix: clamp this setting with saturatedSeconds(...) before it reaches wait_for, or reject values above the chrono-safe range.
  • [src/Storages/IStorage.cpp:94] The lock_acquire_timeout fix only covers the IStorage / MergeTree timed-lock paths. StorageFile, StorageLog, and StorageStripeLog still build raw std::chrono::seconds(lock_acquire_timeout) and pass it to std::shared_timed_mutex timed-lock constructors, so contended operations on those engines can still hit the same chrono overflow.
    Suggested fix: clamp their local getLockTimeout helpers with saturatedSeconds(...), or route those locks through the already-clamped RWLockImpl / Poco::Timespan path.
Final Verdict

Changes requested.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 194/202 (96.04%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 10, 2026
Comment thread src/Interpreters/ProcessList.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (update for 4d71e32: QueryPriorities clamp + priority-wait test)

# Question Answer
a Deterministic repro? Yes. ASAN+UBSan server, two concurrent queries: SELECT count() FROM numbers(1e11) SETTINGS priority = 1 running while SELECT count() FROM numbers(1e8) SETTINGS priority = 2, low_priority_query_wait_time_ms = 100000000000000 reports progress. The lower-priority query's progress callback hits QueryPriorities::waitIfNeed -> condvar.wait_for and aborts every time on the unfixed binary (UBSan signed-integer-overflow at __chrono/duration.h:93).
b Root cause explained? low_priority_query_wait_time_ms was passed unclamped into priorities.insert (ProcessList.cpp:332), stored in QueryPriorities::HandleImpl::wait_time, and later handed to condvar.wait_for(lock, timeout) (QueryPriorities.h:85) whenever a lower-priority query reports progress while a higher-priority one runs. libc++ evaluates wait_for(ms) as now() + ms*1'000'000 ns; a value above ~9.2e12 ms overflows int64. This is the 4th wait_for site of the same bug, missed by the original commit which only covered the two ConcurrentBoundedQueue/ProcessList queue waits.
c Fix matches root cause? Yes. Clamp with saturatedMilliseconds(...) at the insertion point in ProcessList::insert, capping the timeout to one year before it can reach the ms-to-ns conversion. Same helper and one-year cap as the other three sites; clamping at insertion (vs inside QueryPriorities) touches one TU and keeps QueryPriorities generic.
d Test intent preserved / new tests added? New test 04328_query_priority_wait_chrono_overflow.sh added, exercising the priority-wait path (a .sh test because the trigger needs two concurrent queries; the existing 04327 .sql test only covers the lazy-output queue path via interactive_delay). Tagged no-parallel because QueryPriorities is server-global.
e Both directions demonstrated? Yes. Unfixed binary: test FAILS, server aborts at duration.h:93 via QueryPriorities::waitIfNeed (symbolized stack confirmed). Fixed binary: test PASSES (OK), 5/5 iterations, 0 UBSan reports.
f Fix is general, not a narrow patch? Yes. Audited all condition_variable::wait_for sites taking a millisecond timeout. The other query-setting paths are not affected: async_insert_poll_timeout_ms is already bounded by std::min(busy_timeout_ms, ...); wait_for_async_insert_timeout uses std::future::wait_for (no signed-overflow UB). Remaining sites are config-level keeper/zookeeper timeouts, not user-query controllable. With this commit all four user-controllable condition_variable::wait_for timeout settings (interactive_delay, queue_max_wait_ms, replace_running_query_max_wait_ms, low_priority_query_wait_time_ms) are clamped.

Session id: cron:clickhouse-worker-slot-29:20260610-200000

Comment thread src/Common/saturatedDuration.h Resolved
Comment thread src/Common/saturatedDuration.h Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (update for 8410f83: source-level saturation + bugfix-validation fix)

# Question Answer
a Deterministic repro? Yes. The SettingFieldMilliseconds wrap is deterministic integer arithmetic (no sanitizer needed): clickhouse-local --query "SELECT toUInt64(value) FROM system.settings WHERE name='queue_max_wait_ms' SETTINGS queue_max_wait_ms=18446744073709551615" reads back 18446744073709551615 on unfixed master (Int64 microsecond field wrapped negative, then read back through operator UInt64) and 9223372036854775 with the fix. Same for replace_running_query_max_wait_ms, low_priority_query_wait_time_ms, connection_pool_max_wait_ms.
b Root cause explained? Two remaining reachable overflows from the review: (1) connection_pool_max_wait_ms reached PoolBase::get, which built std::chrono::milliseconds(timeout) directly and called wait_for, overflowing the ms->ns conversion. (2) All four wait settings are Milliseconds-typed; SettingFieldTimespan stored x * 1000 in an Int64 microsecond field with no overflow check, so a value above INT64_MAX/1000 wrapped negative before totalMilliseconds(), and saturatedMilliseconds() (positive-only clamp) let the negative value through. The overflow had been moved, not removed.
c Fix matches root cause? Yes. (1) PoolBase::get now uses saturatedMilliseconds() (the timeout < 0 infinite-wait branch is preserved, before the chrono construction). (2) SettingFieldTimespan::unitToMicroseconds() saturates the unit->microsecond multiplication to INT64_MAX instead of wrapping, so the stored timespan can never be negative for any Milliseconds/Seconds setting. saturatedMilliseconds() additionally clamps negative inputs to 0. The fix is at the source (the setting carrier), per "fix the bad value where it originates".
d Test intent preserved / new tests added? New gtest SettingFieldMilliseconds.HugeValueSaturatesInsteadOfWrapping covers the source fix (ctor / assignment / parseFromString at the 9223372036854776 ms boundary). 04327_wait_timeout_chrono_overflow.sql now asserts the observable stored value of all four settings (toUInt64(value) <= 9223372036854775), not a UBSan abort, so it stays meaningful on any build. The UBSan-only 04328_query_priority_wait_chrono_overflow.sh is removed (Bugfix validation cannot reproduce a sanitizer-only abort on a release master build); the low_priority_query_wait_time_ms path is covered by 04327's stored-value check.
e Both directions demonstrated? Yes. 04327 is build-independent: unfixed master -> stored value 18446744073709551615 -> toUInt64(value) <= 9223372036854775 is 0 (test FAILS, bug reproduces); with the fix -> 9223372036854775 -> 1 (PASS). Verified the PR direction on the real ASAN+UBSan binary (5x 1, matches .reference). The gtest PASSES on the fixed binary; on unfixed master ASSERT_GE(totalMicroseconds(), 0) fails because the field wrapped to -1000. This makes Bugfix validation able to reproduce-on-master + pass-on-PR, same approach as the levenshtein UBSan fix (#106934) which asserted an observable return value.
f Fix is general, not a narrow patch? Yes. The saturation lives in SettingFieldTimespan, so it protects every Milliseconds/Seconds setting, not just the four wait timeouts. All five condition_variable::wait_for(milliseconds(user_setting)) sites are now clamped: ConcurrentBoundedQueue push+pop, ProcessList::insert (queue_max_wait_ms, replace_running_query_max_wait_ms), QueryPriorities via ProcessList.cpp:332 (low_priority_query_wait_time_ms), and PoolBase::get (connection_pool_max_wait_ms). Other wait_for sites take fixed/bounded timeouts (async_insert_poll_timeout_ms is std::min-bounded; config-level keeper/zookeeper timeouts are not query-controllable).

Session id: cron:clickhouse-worker-slot-9:20260610-225430

Comment thread src/Core/SettingsFields.h Resolved
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 11, 2026
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (update for 2afffb4: async insert wait-timeout clamp)

# Question Answer
a Deterministic repro? Yes. On an ASAN+UBSan server: 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) aborts the server every time.
b Root cause explained? async_insert_busy_timeout_max_ms = 1e14 is below the SettingFieldMilliseconds saturation cap (INT64_MAX/1000 ≈ 9.2e15), so the source-level fix from 8410f83 does not clamp it. The async insert queue converts it to std::chrono::milliseconds and uses it in now + timeout_ms (pushDataChunk/processBatchDeadlines) and are_tasks_available.wait_for; libc++ multiplies ms by 1e6 for the ns representation, and 1e14 * 1e6 overflows Int64 → UBSan abort (release wraps to an immediate timeout).
c Fix matches root cause? Yes. Every read of the three async-insert wait settings (async_insert_busy_timeout_max_ms, async_insert_busy_timeout_min_ms, async_insert_poll_timeout_ms) is routed through saturatedMilliseconds() before any time_point + duration or wait_for, the same one-year clamp used by the other wait_for sites. No value can reach a chrono op outside the representable range.
d Test intent preserved / new tests added? New test 04329_async_insert_wait_chrono_overflow.sh: exercises the fire-and-forget and adaptive wait paths with huge async_insert_busy_timeout_max_ms/async_insert_poll_timeout_ms, then asserts the server is still alive. Existing async-insert behavior unchanged (normal inserts and the async_insert_busy_timeout_max_ms = 0 validation still work).
e Both directions demonstrated? Yes. Before: server aborts with signed integer overflow: 100000000000000 * 1000000 at __chrono/duration.h:93. After (this build): the insert succeeds, server stays up, UBSan clean.
f Fix is general, not a narrow patch? Yes. Swept all 8 read sites of the 3 settings and all time_point + duration / wait_for consumers in AsynchronousInsertQueue; clamped the 7 that feed a chrono op. validateSettings (zero-check + warning log only, no add/wait) is intentionally left as is. This is the same invariant as the rest of the PR: no user-controlled wait timeout reaches chrono outside the safe range.

Session id: cron:clickhouse-worker-slot-24:20260610-225430

@groeneai

Copy link
Copy Markdown
Collaborator Author

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 04329_async_insert_wait_chrono_overflow.sh.

# Question Answer
a Deterministic repro? Yes. A single fire-and-forget async insert with async_insert_busy_timeout_max_ms = 100000000000000 deterministically aborts the unclamped server: the overflow is on the synchronous pushDataChunk path (now + timeout_ms at AsynchronousInsertQueue.cpp:561), hit on every fresh queue key.
b Root cause explained? The previous test had two problems the runner exposed: (1) the second insert used wait_for_async_insert = 1 with the huge timeout and a single sub-threshold row, so it did not flush and the client blocked until the 120s wait_for_async_insert_timeout (test FAIL); (2) the fire-and-forget insert left a batch in the server-wide AsynchronousInsertQueue with a ~1-year deadline that DROP TABLE does not evict, leaking into later async-insert tests.
c Fix matches root cause? Yes. Dropped the blocking sync insert (the fire-and-forget insert already drives the same overflow path), and drain the queued batch with table-scoped SYSTEM FLUSH ASYNC INSERT QUEUE t_04329 before DROP TABLE. Table-scoped flush processes the entry regardless of deadline and does not set the global flush_stopped, so it cannot stall unrelated parallel tests.
d Test intent preserved / new tests added? Preserved. The test still exercises the exact overflow path (huge async_insert_busy_timeout_max_ms / async_insert_poll_timeout_ms reaching the ms-to-ns chrono conversion) and still asserts the server stays alive. The fix to the test only removes a self-inflicted hang and a queue leak; it does not weaken the assertion.
e Both directions demonstrated? Yes, on an ASAN+UBSan build. Unclamped binary: the test aborts the server (UBSan signed-integer-overflow at duration.h:93, symbolized to pushDataChunk at AsynchronousInsertQueue.cpp:561), runner reports FAIL/server died. Clamped binary: 10/10 runs PASS, system.asynchronous_inserts empty afterwards (no leak).
f Fix is general, not a narrow patch? N/A for this fixup (test-only). The generality of the source fix was covered in the prior gate comments: all six user-controlled millisecond wait-timeout settings are clamped, and SettingFieldTimespan saturates the microsecond multiplication so no value wraps negative before reaching the clamp.

Session id: cron:clickhouse-worker-slot-18:20260611-004400

Comment thread src/Common/saturatedDuration.h Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup abfe187)

Covers the two bot change-requests on 3d0c788 (wait_for_async_insert_timeout future-wait, kafka_max_wait_ms consumer-wait) plus a broader lock_acquire_timeout path found while auditing the rest.

# Question Answer
a Deterministic repro? Yes. On an ASan+UBSan build: (1) HTTP async insert ?async_insert=1&wait_for_async_insert=1&wait_for_async_insert_timeout=100000000000&async_insert_busy_timeout_max_ms=100 aborts the server; (2) SELECT count() FROM system.numbers_mt SETTINGS lock_acquire_timeout=100000000000 aborts the server. Both: signed integer overflow: 100000000000000 * 1000000 at duration.h:93.
b Root cause explained? libc++ evaluates wait_for(d)/future::wait_for(d)/try_lock_for(d) as steady_clock::now() + d in nanoseconds, multiplying milliseconds by 1e6. SettingFieldTimespan caps the stored microseconds at INT64_MAX, but totalMilliseconds() can still return up to INT64_MAX/1000 (~9.2e15) ms, so ms * 1e6 overflows Int64 at the wait site -> UBSan abort (silent immediate-timeout wrap in release). Each unclamped user-setting reaching such a site is therefore vulnerable.
c Fix matches root cause? Yes. Each user-setting ms timeout is saturated to a one-year cap with the existing saturatedMilliseconds() helper before it reaches now()+d/wait_for/try_lock_for: wait_for_async_insert_timeout (TCPHandler + executeQuery future-wait), kafka_max_wait_ms (KafkaSource -> popConsumer), and lock_acquire_timeout (RWLockImpl::getLock upper-bound cap preserving the 0=wait-forever and negative=expired sentinels; tryLockForAlter; lightweight-update sync/auto paths). No symptom-masking; the timeout still behaves as a finite wait.
d Test intent preserved / new tests added? Added. 04327 gains assertions that kafka_max_wait_ms and lock_acquire_timeout saturate; new 04330_wait_timeout_chrono_overflow_more.sh exercises the async-insert future-wait path over HTTP with a huge wait_for_async_insert_timeout. No existing tests weakened.
e Both directions demonstrated? Yes. Pre-fix binary (HEAD 3d0c788, Build ID fbb1007): both repros abort with the UBSan overflow. Post-fix binary (Build ID a2ff44e): 04327 + 04330 pass via clickhouse-test, 0 UBSan reports, server stays up; lock_acquire_timeout=0 (wait-forever) and default behavior unaffected; async-insert regression tests (02015_async_inserts_3/_5) still pass.
f Fix is general, not a narrow patch? Yes. Rather than patch only the two reported sites, I enumerated every user-setting ms reaching a chrono now()+d/wait_for/future::wait_for/try_lock_for and clamped each: the async-insert future-wait (both call sites), the Kafka consumer wait, and the lock_acquire_timeout table-lock path at the RWLockImpl::getLock chokepoint (covering SELECT/INSERT/DROP) plus the alter-lock and lightweight-update siblings. Other matches (ZooKeeper/Keeper operation timeouts, config-level intervals) are not user-query-controllable.

Session id: cron:clickhouse-worker-slot-7:20260611-064000

Comment thread src/Core/SettingsFields.h Resolved
Comment thread src/Common/RWLock.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup 9a2f8b2)

Addresses the two 6th-round clickhouse-gh[bot] change-requests on abfe187: SettingFieldSeconds::parseFromString (string parse path) and the negative side of RWLockImpl::getLock.

# Question Answer
a Deterministic repro? Yes. CR#2: SELECT count() FROM t SETTINGS lock_acquire_timeout = -100000000000 aborts the server every time (UBSan signed integer overflow: -100000000000000 * 1000000 at __chrono/duration.h:93). CR#1: SettingFieldSeconds.HugeStringValueDoesNotWrap gtest aborts pre-fix (1e+20 is outside the range of representable values of type long at SettingsFields.cpp:397).
b Root cause explained? Two pre-clamp wrap points. CR#1: parseFromString did static_cast<Int64>(n * microseconds_per_unit) directly, so a Seconds setting sent as a string (native protocol STRINGS_WITH_FLAGS -> setValueString) produced an out-of-range float-to-Int64 cast (UB) and could wrap the stored microseconds before any later saturation. CR#2: getLock clamped only the upper bound with std::min, so a negative lock_acquire_timeout (accepted within the Int64 us range) survived as a huge negative duration and underflowed steady_clock::now() + duration in the ms->ns multiply.
c Fix matches root cause? Yes. CR#1: route SettingFieldSeconds::parseFromString through float64AsSecondsToTimespan(n), the same checked conversion the Field path uses (rejects out-of-range instead of wrapping). CR#2: replace std::min(...) with saturatedMilliseconds(lock_timeout_ms.count()), which clamps both signs into [0, MAX]; 0 still means wait-forever, negatives become an immediate deadline.
d Test intent preserved / new tests added? New SettingFieldSeconds.HugeStringValueDoesNotWrap gtest (huge/fractional/large-but-valid string values). 04327 gains a negative lock_acquire_timeout assertion. No existing assertion weakened.
e Both directions demonstrated? Yes, on an ASan+UBSan build. CR#2 server repro: pre-fix aborts at duration.h:93, post-fix the negative + huge-positive + boundary cases return normally and the server stays alive. CR#1 gtest: pre-fix aborts at SettingsFields.cpp:397, post-fix out-of-range strings throw and valid values parse exactly.
f Fix is general, not a narrow patch? Yes. SettingFieldMilliseconds::parseFromString was already safe (goes through unitToMicroseconds, which saturates) and stays covered. The sibling lock_acquire_timeout sites from the prior fixup (IStorage::tryLockForAlter, the two StorageMergeTree lightweight-update paths) already wrap the value in saturatedMilliseconds, so they handle the negative side too; RWLockImpl::getLock was the only now() + duration site still on std::min.

Session id: cron:clickhouse-worker-slot-3:20260611-081600

Comment thread src/Common/saturatedDuration.h Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Update for 56d9021: remove sanitizer-only async-insert / future-wait tests

Removed 04329_async_insert_wait_chrono_overflow.sh and 04330_wait_timeout_chrono_overflow_more.sh.

These two assert only that the server stays alive with a huge async_insert_busy_timeout_max_ms / wait_for_async_insert_timeout. The overflow they target is at the chrono use site (ms-to-ns in wait_for / future::wait_for) and is observable only as a UBSan abort; on a non-sanitizer build it wraps silently and the server stays alive either way. Both settings are below the SettingFieldTimespan source cap (INT64_MAX/1000 ms), so their stored value is identical on master and PR, leaving no build-independent observable. Bugfix validation runs changed tests on a non-UBSan master HEAD binary and reports both as "Failed to reproduce the bug" on every head. This is the same limitation that already led to removing 04328_query_priority_wait_chrono_overflow.sh earlier in this PR.

Coverage is unchanged in substance: the use-site clamps (AsynchronousInsertQueue, TCPHandler/executeQuery future-wait, KafkaSource) stay and were verified on a local ASan+UBSan build (both directions); the build-independent source-level saturation is covered by 04327_wait_timeout_chrono_overflow.sql and the SettingFieldMilliseconds/SettingFieldSeconds gtests, which fail on master and pass with the fix.

# Question Answer
a Deterministic repro? Yes (prior gates). The removed tests' paths overflow deterministically under UBSan; the retained 04327 + gtests reproduce build-independently.
b Root cause explained? The two removed tests have no build-independent observable: their settings stay under the source cap, so master and PR store the same value and the only difference is a UBSan-only abort the bugfix-validation (release) master binary cannot see.
c Fix matches root cause? Yes. Removing them resolves the persistent "Failed to reproduce the bug" rows without weakening real coverage; the source fix and use-site clamps remain.
d Test intent preserved / new tests added? Preserved. No source change. 04327 + gtests still assert the saturation; the deleted tests duplicated paths that cannot be asserted without a sanitizer.
e Both directions demonstrated? Yes (prior gates, ASan+UBSan binary). The retained 04327/gtests fail on master and pass with the fix.
f Fix is general, not a narrow patch? N/A (test-only cleanup). Generality of the source fix covered in earlier gate comments.

Session id: cron:clickhouse-worker-slot-2:20260611-085600

Comment thread src/Storages/Kafka/KafkaSource.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Covers HEAD 1a8068c477a1 (commits 59d6dd6 engine/table-setting clamps + 1a8068c RabbitMQ clamp), follow-up to the earlier fixups on this PR.

# Question Answer
a Deterministic repro? Yes for the overflow class (e.g. lock_acquire_timeout=100000000000 aborts the pre-fix server at __chrono/duration.h:93 signed integer overflow: ... * 1000000, UBSan). The four engine/table-setting sites (Kafka2 consumer acquire, AsyncBlockIDsCache, OPTIMIZE-FINAL background lock, replicated shutdown) and the RabbitMQ flush-interval wait require a broker/replica/concurrent-merge to reach the actual wait branch, so they are not deterministically reproducible standalone; they are the same chrono::milliseconds(setting.totalMilliseconds()) -> now()+d/wait_for/wait_until pattern proven crashing on the already-fixed sibling sites.
b Root cause explained? A user-controllable millisecond timeout (SettingFieldTimespan, query or table/engine) is converted to a chrono duration and added to a steady_clock/system_clock now() or passed to condition_variable/future/lock wait_for/wait_until. libc++ multiplies ms by 1'000'000 to nanoseconds; for ms above ~9.2e12 (still below the SettingFieldTimespan storage cap of INT64_MAX/1000) the multiplication overflows Int64 -> UBSan abort, or a silent wrap to an immediate/negative timeout in release.
c Fix matches root cause? Yes. Each site routes the ms value through the existing saturatedMilliseconds() helper (clamps to [0, one year]) before the chrono conversion, so the ms->ns multiply can never overflow. Same helper and cap used by the query-setting clamps already in this PR.
d Test intent preserved / new tests added? New build-independent gtest SaturatedMilliseconds (huge-positive -> one-year cap, huge-negative -> 0, in-range -> pass-through, plus an ns-fits-Int64 assertion). Existing SettingFieldMilliseconds/SettingFieldSeconds gtests and 04327_wait_timeout_chrono_overflow.sql still pass unchanged. No tests weakened.
e Both directions demonstrated? Pre-fix: the overflow class aborts under UBSan (duration.h:93). Post-fix (ASan+UBSan build id 13aaad5b): gtests pass; 04327 output matches reference exactly (8/8); the four MergeTree settings and the RabbitMQ flush interval accept huge values with the server staying alive (no UBSan abort).
f Fix is general, not a narrow patch? Yes. This closes the audit of user-controllable timeout settings reaching a condition_variable/future/lock wait. All such sites now clamp via saturatedMilliseconds: ConcurrentBoundedQueue, PoolBase, RWLock getLock, IStorage try_lock_for, ProcessList (queue/replace/low-priority), AsynchronousInsertQueue (busy/min/poll), TCPHandler + executeQuery (wait_for_async_insert_timeout future-wait), StorageMergeTree lightweight-update + committing-blocks + OPTIMIZE-FINAL, KafkaSource (kafka_max_wait_ms), StorageKafka2 (kafka_consumer_acquire_timeout_ms), AsyncBlockIDsCache (async_block_ids_cache_update_wait_ms), StorageReplicatedMergeTree shutdown (wait_for_unique_parts_send_before_shutdown_ms), and RabbitMQConsumer::waitForMessages (rabbitmq_flush_interval_ms / stream_flush_interval_ms). The remaining wait_for(ms) sites take config-level values that are not user-query-controllable: ZooKeeper/Keeper operation/session/startup timeouts (Coordination settings + zk args) and <system_log> flush_interval_milliseconds. query_cache_ttl/query_cache_min_query_duration use system_clock at microsecond resolution and do not overflow in the user range.

Session id: cron:clickhouse-worker-slot-7:20260611-094600

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on 1a8068c. One non-passing check, not PR-caused:

  • CH Inc sync: internal private sync job (not a public test), unrelated to this condition_variable overflow clamp.

All public checks green. No PR-caused failures. Ready for review.

(cron:our-pr-ci-monitor:20260611-210000)

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 12, 2026
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]>
@groeneai
groeneai force-pushed the fix-wait-for-chrono-overflow branch from 1a8068c to 146c6a5 Compare June 12, 2026 07:43
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased onto current master to resolve a merge conflict. The only conflict was a trivial include-ordering collision in src/Interpreters/ProcessList.cpp (master added #include <array>, this PR adds #include <Common/saturatedDuration.h>); both includes are kept. No logic changed: the 10 commits replay unchanged, and the 20 non-conflicting files remain byte-identical to the pre-rebase versions. New HEAD: 146c6a5 (was 1a8068c). Verified locally that all changed translation units still compile cleanly against current master (no API drift). The branch is now MERGEABLE.

Session: cron:clickhouse-worker-slot-4:20260612-071200

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished on HEAD 146c6a5a7ed1 (Finish Workflow SUCCESS @ 12:40 UTC). This HEAD is the rebase onto current master that resolved the merge conflict; the condition_variable::wait_for overflow clamp logic is unchanged.

One failing check, not caused by this PR:

  • AST fuzzer (amd_debug, targeted) / Logical error: Column identifier A is already registered (STID: 4697-4326) -- chronic analyzer trunk bug, unrelated to this condition_variable timeout clamp. CIDB 30d: 115 unrelated PRs / 11 master hits. Tracked under a separate P0 task.

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.
Comment thread src/Storages/IStorage.cpp
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())))

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.

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.

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.

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:

  1. It only bites under contention. Uncontended, try_lock_for(0ms) succeeds: 3/3 runs rc=0 with no error. try_lock_for on a free mutex acquires it regardless of the duration, so the claim needs that qualifier.
  2. The site I could actually reach is not tryLockForAlter. ALTER TABLE ... ADD COLUMN SETTINGS lock_acquire_timeout=0 returned rc=0 on both arms while a slow ALTER ... UPDATE ran, because alter_lock is not held across the mutation wait in that shape. The reachable sites are the lightweight-update waits: PatchPartsLock.cpp:284 (auto mode, the default) and StorageMergeTree.cpp:1145 (sync mode), plus StorageMergeTree.cpp:3723. I did not demonstrate IStorage.cpp:93 reachable; 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.

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 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), [&]()

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.

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.

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.

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.

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.

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.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 624c33f

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, and there is no such row on this head.

175 check-runs, all completed, 0 queued or in progress, Finish Workflow = success.

Check / test Reason Owner / fixing PR
Stress test (amd_asan_ubsan) / Logical error: 'IDENTIFIER is not a table expression' (STID 3981-42df) fuzzed-query logical error, unrelated to this diff #113400 (mine, open)
Integration tests (amd_msan, 3/8) / test_keeper_dynamic_log_level::test_adjust_log_level trunk flaky: asserts a <Trace> line after a dynamic log-level raise, reads 0 (19 fails against 111,178 passes over 90 days, including 2 on master) #113571 (external, open)
Bugfix validation (unit tests) harness-inconclusive, not a test result: the job compiles the overlaid regression gtest against the before-binary, and src/Common/tests/gtest_saturated_duration.cpp includes src/Common/saturatedDuration.h, which this PR adds. Neither file exists at the merge base, so the before-binary cannot compile it a fix task is moved to pending (investigating at full effort — fixing PR link to follow on this PR)

Build (arm_release) / Post Hooks was red on the previous head and is green here: this head carries merged #113409, verified by probing ci/jobs/scripts/log_cluster.py at this exact commit for the retry the fix introduces, with the fix's merge commit as a positive control and its parent as a negative one.

Session id: cron:our-pr-ci-monitor:20260806-060000

@serxa serxa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is fantastic, why aren't we merging this?

@serxa serxa self-assigned this Aug 20, 2026
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks. It was not review state: the branch had drifted into a conflict with master, so it was CONFLICTING/DIRTY and unmergeable regardless of approval.

I merged master in just now (9197f401) and it is MERGEABLE again. One conflict, in AsynchronousInsertQueue.cpp: master wrapped the shard.last_insert_time read in TSA_SUPPRESS_WARNING_FOR_READ while this branch clamps the same line through saturatedMilliseconds(). Kept both. No other line was touched, and the clamp census is unchanged at 94 call sites across 20 files.

I did not rebase, so 624c33fb is still in the history.

CI is running on the new head. Three checks were red on the previous head, all with owners and none from this diff: Stress test (amd_asan_ubsan) (fuzzer logical error, #113400), Integration tests (amd_msan, 3/8) (test_keeper_dynamic_log_level, #113571), and Bugfix validation (unit tests), which cannot compile the new gtest against the before-binary because the header under test does not exist there.

Comment thread src/Storages/IStorage.cpp
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())))

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

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.

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.

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.

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.

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9197f4019 with master ea3d0db80 (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 704.45 MiB 701.40 MiB -3.05 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

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

Job report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 21, 2026
Merged via the queue into ClickHouse:master with commit f02caa0 Aug 21, 2026
176 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 21, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 22, 2026
…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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 23, 2026
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.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 23, 2026
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.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 24, 2026
…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.
alexey-milovidov pushed a commit to mneedham/ClickHouse that referenced this pull request Sep 7, 2026
…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]>
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-review-human PR origin: human review feedback on a groeneai PR 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.

6 participants