Skip to content

Fix signed integer overflow in the table lock deadline built from lock_acquire_timeout - #117974

Merged
tiandiwonder merged 2 commits into
ClickHouse:masterfrom
groeneai:clamp-log-family-lock-acquire-timeout
Sep 7, 2026
Merged

tiandiwonder merged 2 commits into
ClickHouse:masterfrom
groeneai:clamp-log-family-lock-acquire-timeout

Conversation

@groeneai

@groeneai groeneai commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #106961

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 the effective table lock timeout, the smaller of lock_acquire_timeout and a non-zero max_execution_time, was above roughly 9.2e9 seconds or a large negative value. Reading or writing a Log, TinyLog, StripeLog or File table built the lock deadline from it without bounding it first, so the deadline was undefined and the wait was no longer bounded by the setting; under the Undefined Behavior Sanitizer the server aborted.

Description

Root cause. libc++ turns try_lock_for(d) into try_lock_until(now() + d) and converts d to nanoseconds first (__chrono/duration.h:93), multiplying a std::chrono::seconds argument by 1'000'000'000. SettingFieldTimespan rejects only values that do not fit Int64 microseconds, about three orders of magnitude above the first value that overflows a nanosecond deadline, and no constraint caps the setting. No contention is required: the overflow is in the argument to the wait, before any predicate is checked. The product is undefined rather than merely large, so the deadline stops bounding the wait; what reproduces on demand is the sanitizer abort below.

The three getLockTimeout helpers in StorageFile, StorageLog and StorageStripeLog return a std::chrono::seconds for the storage's own std::shared_timed_mutex, bypassing RWLockImpl, so the millisecond clamp added by #106961 never reached them.

Change. Three behavioural lines: each helper returns saturatedSeconds(...) in place of std::chrono::seconds{...}. saturatedSeconds already exists, with the same one-year bound and a negative count mapping to 0. The clamp sits at each helper's single return, so it also covers max_execution_time (the body has already reduced both settings to the smaller one) and all five StorageFile lock sites. No call site changed; TinyLog is registered by StorageLog.cpp and shares that helper.

Validation. Both directions on one ASAN+UBSan build. Before, each of the four arms aborts:

SELECT count() FROM t_log SETTINGS lock_acquire_timeout = 100000000000;
  duration.h:93: signed integer overflow: 100000000000 * 1000000000

After, all four return correct results, and six controls (default timeout, in-range timeout, max_execution_time = 10) are unaffected in both arms. Four arms were added to 04327_wait_timeout_chrono_overflow; 50 randomized runs pass.

The microsecond sibling carrier of the same setting is fixed by #117898, which is why this PR stops at the seconds carrier.


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

Version info

  • Merged into: 26.9.1.889 (included in 26.9 and later)

groeneai and others added 2 commits September 3, 2026 19:53
…uire_timeout`

`libc++` turns `wait_for(d)` into `wait_until(now() + d)` and converts `d` to
nanoseconds first, multiplying by 1'000'000'000 for a `std::chrono::seconds`
argument and by 1'000 for `std::chrono::microseconds`. `SettingFieldTimespan`
only rejects values that do not fit Int64 microseconds, three orders of
magnitude above the first value that overflows a nanosecond deadline, and no
constraint caps the setting, so two carriers reached that conversion unbounded
in both signs. No contention is required: the overflow is in the argument to
`wait_for`, before any predicate check.

The three byte-identical `getLockTimeout` helpers in `StorageFile`,
`StorageLog` and `StorageStripeLog` return a `std::chrono::seconds` for a
`std::shared_timed_mutex` that bypasses `RWLockImpl`, so the millisecond clamp
added by ClickHouse#106961 never reached them. One clamp at each return also covers
`max_execution_time`, because the body has already collapsed both settings
into `lock_timeout`.

`ThreadPoolImpl::scheduleImpl` builds the nanosecond deadline itself, out of a
microsecond count whose parameter was `uint64_t`: the declared domain admitted
values that cannot be converted, and the conversion at the call destroyed the
caller's sign. Widening `wait_microseconds` to `Int64` and clamping once
inside the pool covers all three of its callers and any future one, and no
call site needed changing because all three already pass
`Poco::Timespan::totalMicroseconds()`. `ConcurrentBoundedQueue` is the in-tree
precedent for clamping inside an owned callee whose timeout parameter is
unsigned.

Measured both directions on one ASAN+UBSan build: seven fixtures abort before
the change, at `__chrono/duration.h:93`, with the multiplier identifying the
unit; all seven return correct results after it, while the same fixtures at
the default timeout, at `max_threads = 1`, and with `max_execution_time = 10`
are unaffected in both arms.

Co-Authored-By: Claude Opus 5 <[email protected]>
The microsecond carrier is clamped by ClickHouse#117898, which adds the same
`saturatedMicroseconds` helper to `saturatedDuration.h`; keeping both would
define that helper and its constant twice. This commit therefore drops the
microsecond half and the `wait_microseconds` widening, leaving the three
`getLockTimeout` helpers in `StorageFile`, `StorageLog` and `StorageStripeLog`
as the only change.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 gate rounds; 0 findings on the final pass)

⚠️ Changelog wording, agreed and fixed before publishing. The entry had described a huge max_execution_time as independently reaching the overflow. It cannot: the helper keeps the smaller of the two settings, so a huge positive max_execution_time is never selected (a large negative one always is). TinyLog was also missing from the engine list; it is registered by StorageLog.cpp with the same create_fn as Log, so it shares the clamped helper.

💡 Contention coverage, noted and deliberately not added. The four arms take uncontended locks, so they would also pass if the helper returned zero unconditionally. That mapping is pinned instead by gtest_saturated_duration.cpp, which asserts the clamped maximum converts to a positive representable wait rather than an immediate deadline. A contention fixture was built and its own controls killed it: an in-range lock_acquire_timeout = 1 also waited the full 8.6 s and succeeded, so the blocking there is not governed by this setting. Not added rather than added blind.

💡 Only the sanitizer abort is measured (four arms, both signs, at __chrono/duration.h:93 with the named operand, plus the fix removing all four). The release consequence is undefined behaviour, so the changelog says the deadline stops bounding the wait instead of naming an outcome I did not observe.

@clickhouse-gh clickhouse-gh Bot closed this Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [292e0d3]

Summary: ✅


AI Review

Summary

This PR routes the Log/TinyLog, StripeLog, and File table-engine lock timeout helpers through saturatedSeconds so extreme effective lock_acquire_timeout values no longer overflow when libc++ builds the timed-lock deadline. I checked the current diff, the touched lock sites, the surrounding saturation helpers/tests, the existing PR discussion, and the current CI state, and I did not find a correctness, safety, or evidence gap that warrants an inline review comment.

Final Verdict

✅ No findings.

LLVM Coverage Report

Measured on commit 292e0d3.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 10/12 (83.33%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @kssenii, could you review this? The getLockTimeout helpers in StorageLog, StorageStripeLog and StorageFile built a std::shared_timed_mutex deadline straight from lock_acquire_timeout, so libc++ multiplied the seconds count by 1'000'000'000 and overflowed Int64 for an out-of-range value; each helper now clamps through the existing saturatedSeconds, which the millisecond lock path already used.

@tiandiwonder tiandiwonder self-assigned this Sep 3, 2026
@tiandiwonder

Copy link
Copy Markdown
Contributor

I extended this sweep to the rest of the tree (all 249 wait_for/wait_until/try_lock_for/sleep_for sites in src/) to see what else carries the same defect. Two sites are query-level reachable and unclamped — handing them over rather than growing this PR.

1. src/Common/OvercommitTracker.cpp:86 — memory_usage_overcommit_max_wait_microseconds

DECLARE(UInt64, memory_usage_overcommit_max_wait_microseconds, 5'000'000, …) (Settings.cpp:4059) is a plain UInt64 query-level setting with no SettingFieldTimespan validation at all, so its full range is accepted while the us→ns threshold is 9,223,372,036,854,775. The wait is the predicate wait_for overload, which is the unsafe one (see the table below).

Negative values reach it too, via an unsigned→signed store:

void MemoryTracker::setOvercommitWaitingTime(UInt64 wait_time)
{
    max_wait_time.store(wait_time * 1us, std::memory_order_relaxed);   // MemoryTracker.cpp:715
}

wait_time * 1us has a signed long long rep, so any wait_time >= 2^63 lands as a negative microseconds. OvercommitTracker.cpp:86 then passes it straight through; the only guard is == ZERO_MICROSEC. Reaching the wait needs actual memory pressure, which is the one discount relative to site 2.

2. src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp:268 — wait_for_async_insert_timeout

This is a missed sibling call site of a setting you have already clamped twice:

consumer clamped?
src/Interpreters/executeQuery.cpp:2939 yes, saturatedMilliseconds
src/Server/TCPHandler.cpp:1537 yes, saturatedMilliseconds
src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp:268 no — raw .totalMilliseconds()

It is a SettingsSeconds, so it accepts negatives natively: float64AsSecondsToTimespan (SettingsFields.cpp:337-350) only rejects |d*1e6| > Int64, i.e. down to about −9.22e12 s. The wait at :269 is future::wait_for, also unsafe. SET wait_for_async_insert_timeout = -1e13 gives timeout_ms = -1e16.

Which primitives actually need clamping

Worth having explicitly, because it takes a lot of sites off the list — I checked the pinned contrib/llvm-project libc++:

primitive behaviour overflows?
this_thread::sleep_for(d), non-nanoseconds d clamps at duration<long double>(9223372036.0L) → nanoseconds::max(), and skips d <= 0 (__thread/this_thread.h:38-53) no
cv::wait_for(lk, d) — no predicate __safe_nanosecond_cast + d <= zero() → timeout (condition_variable.h:142-155) no
cv::wait_for(lk, d, pred) — with predicate wait_until(lk, steady_clock::now() + d, pred), raw promotion (condition_variable.h:192-194) yes
cv::wait_until(lk, tp) where tp is already ns-rep no unit multiply no (risk moves to whoever computed tp)
future::wait_for(d) wait_until(now() + rel_time) yes
shared_mutex::try_lock_for(d) try_lock_until(now() + rel_time) yes — this is what this PR's three helpers feed

So every sleep_for site is safe by construction regardless of the setting value, and so is the non-predicate wait_for. That rules out, among others, MergeTreeData.cpp:3515, :7812, :7855, PartMovesBetweenShardsOrchestrator.cpp:549/:619, InstrumentationManager.cpp:517 and DiskAccessStorage.cpp:354 — all of which look alarming by provenance but cannot overflow.

Lower priority — server-config only, no query-level exposure

  • src/Common/CgroupsMemoryUsageObserver.cpp:70 — cgroups_memory_usage_observer_wait_time (and keeper_server.cgroups_memory_observer_wait_time). Seconds unit, so the lowest threshold of the set at 9,223,372,036; only != 0 is filtered.
  • src/Common/Scheduler/CPULeaseAllocation.cpp:607 — cpu_slot_preemption_timeout_ms (ServerSettings.cpp:1268, unvalidated UInt64); the == milliseconds::max() guard at :600 is equality-only.
  • programs/server/Server.cpp:3965 — shutdown_wait_unfinished: wait_start + std::chrono::milliseconds(wait_limit_seconds * 1000) has two problems, the unsigned * 1000 wrap and then the ms→ns promotion when added to a ns-rep time_point. Clamping this one line covers both consumers (RefreshSet::joinBackgroundTasks at :3976 and ThreadPoolImpl::waitUntil at :3977); ThreadPool.cpp:690 itself is fine, since it receives an already-computed time_point.

Also noted, not this class: ExternalLoader.cpp:936/:966 survive only because WAIT is exactly Duration::max() and is short-circuited by an == test — any large-but-not-max() value would fall into the predicate wait_for. Fragile API rather than a live defect.

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, the hand-over lands cleanly. Taking both as successor PRs, and leaving this one as is.

I re-verified the two load-bearing claims at source rather than re-deriving your primitive table, and both hold: wait_for_async_insert_timeout has exactly three C++ consumers, two of them wrapped in saturatedMilliseconds and the PrometheusRemoteWriteProtocol one passing the raw totalMilliseconds value straight into future::wait_for; and the memory_usage_overcommit_max_wait_microseconds DECLARE carries no SettingFieldTimespan, with MemoryTracker::setOvercommitWaitingTime storing wait_time * 1us, whose signed long long rep is what delivers a negative microseconds to the predicate wait_for overload.

One sequencing note you may not have: the microsecond clamp site 1 wants, saturatedMicroseconds, is added by #117898, which is still open. I am starting with site 2 to keep site 1 off that header until it merges.

For site 1 the impact statement will report what I measure under real memory pressure rather than what the code path argues. If I cannot reach the wait I will say that instead of clamping on an argument.

The server-config-only three are recorded but not promised yet: with no query-level exposure the impact cannot come from a SET, so they queue behind the two reachable ones.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 292e0d3fa with master 752470550 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of f16484443; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 292e0d3

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

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) / test_unknown_config_option/test.py::test_graphite_default_rule_type_not_all_rejected harness TEARDOWN defect, not a test failure: the assertions passed (praktika labels the leaf retry_ok) and Cluster.shutdown died with UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8a reading docker.log, which tests/integration/helpers/cluster.py:4459 opens with strict UTF-8. Non-UTF-8 bytes are expected in that file by construction: line 4376 opens the same path for writing with errors="replace" and line 4379 hands the fd to a docker compose logs subprocess, which writes raw bytes the text layer never sees. The correct idiom is 18 lines below at 4477 (errors="replace"). This diff touches no harness file a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
AST fuzzer (amd_debug) / Server unresponsive: memory limit exceeded pre-existing fuzzer-driven memory exhaustion. Job-level descriptor with an empty context (Error:), and the signature fires on unrelated heads across both the AST fuzzer and Stress test families. Unreachable from this diff, which only clamps a chrono deadline computation in three Log-family storages and allocates nothing. #116782 was checked as a candidate owner and refuted: it adds a container memory cap, which lowers the server budget rather than raising it, and fixpresence puts it absent from this tree anyway (0 hits here, 2 at its own merge commit and 2 on live master as controls) a fix task is created and owns this signature across both job families (investigating at full effort, fixing-PR link to follow on this PR)

Session id: cron:our-pr-ci-monitor:20260904-090000

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

The first of the two sites you handed over in #117974 (comment) is now a separate pull request: #118040. It wraps the wait_for_async_insert_timeout read in PrometheusRemoteWriteProtocol.cpp with saturatedMilliseconds, so all three consumers of that setting now clamp, and it carries your in-range control as a third test arm: that arm is the only one that catches an implementation which clamps out-of-range values correctly and also mangles in-range ones.

The second site, OvercommitTracker.cpp, needs a microsecond-typed clamp that is not on master yet and follows separately. This pull request is untouched.

@clickhouse-gh clickhouse-gh Bot added the comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... label Sep 4, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the cluster.py docker.log decode failure on this PR's Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) row: #118195.

pull Bot pushed a commit to Mattlk13/ClickHouse that referenced this pull request Sep 5, 2026
…protocol

`wait_for_async_insert_timeout` is a `Seconds` setting, and its validator
`float64AsSecondsToTimespan` rejects only values whose microsecond product
leaves `Int64`. Any magnitude up to about `9.22e12` seconds is therefore legal,
negatives included, and the setting is client-settable per request from the URL
query string of a prometheus `write` handler.

`insertBlock` passed that raw millisecond count to `std::future::wait_for`. The
pinned libc++ turns `wait_for(d)` into `wait_until(steady_clock::now() + d)`,
and `steady_clock::duration` is nanoseconds, so the converting `duration`
constructor multiplies milliseconds by 1'000'000 in a signed 64-bit
representation. That multiply overflows above about `9.22e9` seconds, in both
directions, and the wait deadline becomes undefined. Signed overflow is
undefined behaviour, so the combined ASan and UBSan build, which carries
`-fno-sanitize-recover=all`, aborts the server; an ordinary build silently wraps
the deadline. Standalone against the pinned libc++, `+1e13` and `-1e13`
milliseconds both report `signed integer overflow` at
`__chrono/duration.h:93` and exit non-zero, while `0` and the one-year cap exit
cleanly.

The setting has exactly three consumers in `src/`. `executeQuery.cpp` and
`TCPHandler.cpp` already clamp with `saturatedMilliseconds`; this was the missed
third, because these lines were added after the other two were fixed. Using the
same helper keeps the three consistent and reuses the existing one-year cap;
negatives clamp to `0`, which is what `wait_for` already treats as "already
expired", so the shipped behaviour for a negative timeout is unchanged in kind
and merely becomes well-defined.

The message reports the clamped value rather than the raw setting, matching
`TCPHandler.cpp`: the sentence names the timeout that was actually applied, so
printing the raw value would assert a wait that did not happen.

Measured over HTTP with a three second flush deadline. Without the clamp,
`+1e10` seconds wraps the deadline into the past and the request fails with 503
instead of 204, and `-1e10` seconds wraps it positive so the request returns 204
after waiting on an undefined deadline. With the clamp the first returns 204 and
the second returns 503 with `(0 ms)` immediately. An in-range control of one
millisecond reports `(1 ms)` in both builds, which is the only arm that
distinguishes this fix from an implementation that clamps every value.

Left alone deliberately: unlike both other consumers, this site does not consult
`wait_for_async_insert` and waits unconditionally once `async_insert` is set.
That is intentional for remote-write durability, and it is why the timeout maps
to a retryable 503.

Reported by @tiandiwonder, who found this site while sweeping the wait
primitives in `src/` and handed it over rather than growing
ClickHouse#117974.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Site 1 of the hand-over in #117974 (comment) is now #118227, after #118040 covered site 2.

One measurement worth passing back for the primitive table: the predicate wait_for has two overflow points, not one. 9223372036854775 microseconds converts safely, with 807 ns of headroom under INT64_MAX, but condition_variable_any::wait_for is wait_until(lock, steady_clock::now() + d, pred) and steady_clock counts from boot, so at 36 days of uptime the addition overflowed and aborted a UBSan build on its own. The safe ceiling therefore moves with uptime, which is why site 1 preserves the configured duration and slices the wait rather than clamping it the way site 2 could.

@tiandiwonder
tiandiwonder added this pull request to the merge queue Sep 7, 2026
Merged via the queue into ClickHouse:master with commit b922ae0 Sep 7, 2026
342 of 514 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... groeneai-origin-review-bot PR origin: review-bot finding 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.

3 participants