Skip to content

Fix signed integer overflow in Keeper coordination timeouts - #112088

Merged
antonio2368 merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-keeper-wait-for-overflow
Aug 25, 2026
Merged

antonio2368 merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-keeper-wait-for-overflow

Conversation

@groeneai

@groeneai groeneai commented Jul 27, 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):

Fixes signed integer overflow when a Keeper coordination timeout such as operation_timeout_ms, session_timeout_ms or startup_timeout is set to a very large value. Converting the millisecond count to nanoseconds, and adding it to the current time to form a deadline, could both overflow, so the wait expired immediately instead of waiting for the configured time, and the server aborted in builds with the undefined behaviour sanitizer.

Description

Keeper coordination timeouts overflow when converted to nanoseconds. Found while sweeping the Keeper half of #106961 and scoped out of it, because coordination timeouts need a different bound from query-execution waits (scope-out comment).

What goes wrong. A millisecond timeout reaches a std::chrono expression whose common type is nanoseconds, held in an Int64. Both the count() * 1000000 conversion and the deadline addition steady_clock::now() + d can overflow, which is undefined behaviour. The wrapped deadline lies in the past, so a wait configured to be long gives up immediately; in sanitizer builds (-fno-sanitize-recover=all) the server aborts instead, example report.

The fix. Saturate at the unsafe conversion, in the callee owning the timeout, bounded at (INT64_MAX / 2) / 1000000, about 146 years. No setting is capped, and no value master converts without overflow changes. Seventeen sites across KeeperServer, KeeperContext, KeeperDispatcher and both request dispatchers, two at the open_client_req_stream boundary into NuRaft; the three boundaries keep different rules, detailed below. The three sites reached through ConcurrentBoundedQueue are fixed on master by #106961, so this PR no longer touches that file.

Tests. Three cases in the existing src/Coordination/tests/gtest_coordination.cpp; these timeouts have no SQL surface. Each goes red when the line it covers is reverted. No production file is modified to give a test access: that module already declares KeeperDispatcherTestAccessor a friend of KeeperDispatcher.

Not in this PR. contrib/NuRaft/src/asio_service.cxx, a submodule needing its own pull request against the fork. Converging with master's DB::saturatedMilliseconds, whose one year policy cap is the wrong bound for a coordination timeout. And src/Coordination/Changelog.cpp, which builds two steady_clock deadlines from raw UInt64 settings (:2954, :4147) of a different setting family, where I have not shown such a value is reachable in a running Keeper.

The three boundary rules, and which waits are actually unsafe
  • Waits get the half-range bound, two-sided, non-positive clamped to zero, which is what wait_for does with a non-positive duration anyway, so no shutdown path can newly block. The two dispatchers already read this setting into different types on master, int64_t in KeeperRequestDispatcher and uint64_t in KeeperRequestDispatcherOld, so a negative count saturates to zero on the signed sites and to the bound on the unsigned ones. Those declarations are untouched; on master both are undefined behaviour instead.
  • min_session_timeout/max_session_timeout in KeeperTCPHandler only get their * 1000 made safe, at the full Poco::Timespan::TimeDiff range. This is not a wait: it is copied into the replicated request, stored in session_and_timeout and the expiry queue, and compared at full microsecond value, so clamping it would change expiry policy. The wait on this path is bounded inside getSessionID. The handshake reply is a protocol int32, so a session_timeout_ms above INT32_MAX already diverges between server and client on master, identically; widening that field is separate.
  • The NuRaft boundary saturates only the upper end, converting to unsigned first exactly as the uint64_t parameter does today. NuRaft arms its timers only when the count is nonzero, so mapping a negative count to zero would silently disable the timer, which is worse than the overflow.

condition_variable::wait_for without a predicate is already safe, going through __safe_nanosecond_cast; the undefined behaviour is only in the predicate overload, which every one of these sites uses. std::future::wait_for is unsafe regardless, being wait_until(now() + rel) with no checked cast. sleep_for is safe, so the two Keeper sleep_for sites are untouched, and KeeperServer.cpp's operation_timeout_ms * 2 never enters std::chrono.

The added cases build against the merge-base tree unchanged, because Bugfix validation (unit tests) overlays them there without the fix and reports a compile failure as inconclusive. They name no new symbol: every API they use already exists there.

Version info

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

groeneai added 3 commits July 27, 2026 05:37
A millisecond timeout count reaches a std::chrono expression whose common
type is nanoseconds, represented as Int64. Two operations there can
overflow, and both are undefined behaviour: the milliseconds to
nanoseconds conversion, a count() * 1000000 in __chrono/duration.h, and
the deadline addition steady_clock::now() + d reached from
condition_variable::wait_for with a predicate and from
std::future::wait_for.

Such a count is reachable from configuration.
SettingFieldMilliseconds::operator=(UInt64) performs an unchecked
UInt64 * 1000 and then casts to Int64, so a value in
[9223372036855, 9223372036854775] is stored faithfully and overflows the
conversion, while a value above that wraps to a negative microsecond
count whose totalMilliseconds() is negative and huge and overflows as
well. Several Keeper sites read that negative count into a uint64_t,
turning it back into a huge positive one, so the guard has to be
two-sided and signedness-agnostic.

Without a sanitizer the effect is silent and user-visible: the wrapped
deadline lies in the past, so a wait configured to be long gives up
immediately. With -fno-sanitize-recover=all, which ClickHouse sets for
its sanitizer builds, the report aborts the server. In CI this appears as
UndefinedBehaviorSanitizer: signed integer overflow at
__chrono/duration.h:93 on Stress test (amd_asan_ubsan) and its arm
variants.

Saturate at the unsafe conversion, in the callee that owns the timeout,
at a representability bound rather than capping any setting. e902388
("Allow to use bigger timeouts for zookeeper") fixes this same bug class
by widening the conversion and leaving the configured value alone, so a
large operator-set timeout is meant to keep working.

The bound is half of the Int64 nanosecond range, (INT64_MAX / 2) / 1e6,
about 146 years. Half and not the full range because every one of these
sites then adds steady_clock::now(), which on Linux is nanoseconds since
boot, so a bound that only just fits the conversion still wraps after a
few days of uptime. AtomicStopwatch::secondsToNanoseconds saturates at
half of UInt64::max for exactly this reason.

Twenty sites are covered. Fifteen are direct waits and steady_clock
comparisons in KeeperServer, KeeperContext, KeeperDispatcher,
KeeperRequestDispatcher and KeeperRequestDispatcherOld. Three are reached
through ConcurrentBoundedQueue::tryPop and tryPush, fixed inside
emplaceImpl and popImpl because nanosecond representability of that
argument is a precondition of the queue's own wait, shared by every
consumer of its timeout API. The last two are the open_client_req_stream
boundary into NuRaft, saturated on our side because contrib/NuRaft is a
submodule.

Where the timeout arrives as a parameter the callee is fixed once rather
than each caller, so KeeperDispatcher::getSessionID,
KeeperContext::waitCommittedUpto and
KeeperDispatcher::interruptibleSleep cover every caller, including the
client-negotiated session timeout and
keeper_server.http_control.storage.session_timeout_ms.

Three boundaries deliberately use three different rules. Waits get the
half-range bound, two-sided, with a non-positive count clamped to zero,
which is what wait_for does with it anyway. min_session_timeout and
max_session_timeout in KeeperTCPHandler only get their * 1000 made safe,
at the full Poco::Timespan::TimeDiff range, because that value is the
session TTL: it is replicated, stored in session_and_timeout and echoed
to the client, so clamping it would change policy. The NuRaft boundary
saturates only the upper end and converts to unsigned first, because
NuRaft arms its timers only for a nonzero count and mapping a negative
count to zero would silently disable the timer.

Which waits are unsafe is not obvious. condition_variable::wait_for
without a predicate is already safe, since that overload goes through
__safe_nanosecond_cast which pre-checks the multiplication; the
undefined behaviour is only in the predicate overload, which these sites
use. std::future::wait_for is unsafe regardless, being
wait_until(steady_clock::now() + rel) with no checked cast.
std::this_thread::sleep_for is safe, so the two sleep_for sites are
untouched, and KeeperServer's operation_timeout_ms * 2 never enters
std::chrono, so it is untouched too.
Both assertions strengthened here were one-sided. `InterruptibleSleepKeepsHugePeriod`
signalled shutdown after 300 ms but only required at least 150 ms to have elapsed, so an
implementation that silently shortened the period to anything in that window timed out and
still passed; a build whose `interruptibleSleep` clamps to a fixed 200 ms was measured to
pass it. It now also records whether shutdown had been signalled at the instant the wait
returned, which distinguishes "the saturated period was kept and the predicate became
true" from "the period was lost and the wait timed out". The flag is read before joining
the signaller on purpose: the signaller sets it whatever ended the wait, so a reading taken
after the join is true unconditionally and asserts nothing.

`NonZeroCountKeepsZeroPolicy` required only a nonzero result at or below the bound for the
two negative inputs, which admits every value from 1 upwards. The conversion returns the
bound exactly, and it has to: NuRaft arms its send and receive timers from that count, so
1 ms would make them fire essentially at once, the mirror of the zero-means-disabled hazard
the test exists to guard. Both rows now assert exact equality, matching the positive rows
in the same test. A variant returning 1 for a negative input was measured to pass the old
form and to fail this one.

No production code changes.
Both tests that assert a non-positive count returns immediately checked only
that the call took less than 300 ms. An empty queue reports failure however
long it waited, and a bounded elapsed time cannot say a wait did not happen,
so an implementation that substituted a 200 ms wait for a zero duration
satisfied every assertion while breaking exactly the contract these tests
exist to protect: no shutdown path may newly block.

Each test now schedules an event a little later, calls the wait, and requires
the call to have returned while that event had not happened yet. For the
Keeper dispatcher the event is signalShutdown, sampled at the instant the wait
returns because the flag latches; for the queue it is a push, and the item
must still be in the queue afterwards. The existing elapsed bounds are kept.

The event delay is deliberately shorter than the bound: an ordering oracle can
only observe a spurious wait at least as long as the delay, so a delay above
the regression it must catch would be vacuous.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, 6 findings, all adjudicated)

I put this change through an independent code review plus a second-model review pass on each
revision, before opening the pull request. Every finding is listed with what I did about it.

Round 0 (c6ac37891003bb)

❌ blocker - session timeout wire width. Claim: a large session_timeout_ms is truncated to
Int32 on the ZooKeeper handshake, so client and server disagree.
Disagreed, with evidence. The necessary step is performed entirely by untouched code: the
static_cast<int32_t> on the handshake reply is byte-identical on master, the protocol field is
int32 in both directions, and the new microsecond guard is the identity for every value below
INT64_MAX / 1000. Measured over 7 configurations, master and this branch produce identical
microseconds and identical wire values except where master's own multiplication is undefined
behaviour. The finding's own example (one year) is what master already sends. I did not simply
drop it: the divergence is now disclosed in the description above, together with the fact that
widening the field is a separate change.

⚠️ major - interruptibleSleep oracle. The test proved a long wait lasted long enough, not
that it lasted long enough because the period was kept. Agreed and fixed: it now captures
isShuttingDown at the instant the wait returns and asserts it, so a period silently shortened to
any value above the elapsed bound is caught. Verified by building that degraded implementation.

⚠️ major - NuRaft negative oracle. The two negative rows asserted only "nonzero and at most the
bound", which admits 1. Agreed and fixed: they now assert the bound exactly. A returned 1
would satisfy "timer not disabled" while making the timer fire immediately, which is the mirror of
the hazard that conversion exists to avoid.

💡 Three nits disagreed with measurement rather than argument: the new header adds 52 preprocessed
lines
to the real translation units that include it (<chrono> and <algorithm> are already in
their closures; only the standalone test translation unit sees a large increase); the carrier
enumeration agreed with mine; the sibling-pull-request collision was already disclosed.

Round 1 (656dbf6a92b435)

❌ blocker - wrapped timeout signedness. Claim: a wrapped-negative setting still expires
immediately on the signed dispatcher while its unsigned sibling saturates.
Disagreed, with evidence. Every declaration the claim depends on is untouched here, and the diff
matches no line containing any of them; the file named as the wrapping storage is not in the diff at
all. The baseline is also wrong: on master both sites are undefined behaviour for such a value
and neither waits the configured time. This change makes each defined without changing which one a
given site sees. The asymmetry is now stated in the description, and fixing the wrap at its source
belongs to SettingFieldTimespan.

⚠️ major (re-raise) - non-positive sleep oracle. ⚠️ major - zero-timeout queue oracle.
Both agreed and fixed. An elapsed upper bound cannot assert that a wait did not happen: an
empty queue reports failure however long it waited, and any wait shorter than the bound passes. Both
tests now assert an ordering fact against a delayed event - the call must have returned while the
event had not happened yet, and for the queue the pushed item must still be in the queue afterwards.
Verified by building implementations that substitute a 200 ms wait for a zero duration: each fails
the strengthened test and passes the previous one.

Round 2 (3f27c2b663448b) - clean

No findings. The delta is test-only: all nine production files are byte-identical to the first
reviewed revision.

While adjudicating round 2 I found that my own fix plan's prescribed delay constant could not
detect its own mandated regression
- an ordering oracle sees a spurious wait of W ms only when
W is at least the event delay D, and the plan paired D = 300 ms with a 200 ms regression. The
implementation used a separate smaller constant and demonstrated the arithmetic by building the
literal-constant variants and showing they pass under the regression. Correct call.

💡 Two nits of my own, disclosed rather than acted on: the two ordering oracles rely on the main
thread reaching its sampling point within 100 ms (measured 20/20 stable across repeats, with about
four orders of magnitude of headroom over the actual work, and bracketed by comparable margins in
neighbouring test files; a larger delay is capped at 199 ms by the detection requirement). And two
added lines exceed the formatter's column limit - measured, the file already had 11 such lines and
now has 10, both edited statements were already over the limit, and no check enforces it.

Verification carried across rounds

Each of the four production changes was reverted on its own and confirmed to fail exactly the one
test that covers it. Five further degraded implementations were built to confirm the assertions are
not one-sided; every one of them passes the bounds that were asserted before these strengthenings,
and every one fails as shipped.

Session id: cron:clickhouse-review-slot-52:20260727-112200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Result
a Deterministic repro Yes. A standalone TU linked against the in-tree libcxx, one ms count per process invocation, reproduces on demand: 9223372036855 gives duration.h:93:79: signed integer overflow: 9223372036855 * 1000000 and 9223372036854 gives the deadline-addition report at duration.h:403:33. Not probabilistic: a given configured value either overflows or it does not.
b Root cause explained Yes. A millisecond count reaches a nanosecond-typed std::chrono expression; both the * 1000000 conversion and the steady_clock::now() + d deadline addition overflow Int64. Such a count is reachable because SettingFieldMilliseconds::operator=(UInt64) does an unchecked UInt64 * 1000 then casts to Int64, so large values are stored faithfully and very large ones wrap negative.
c Fix matches root cause Yes. The conversion is made total at the point of conversion, in the callee that owns the timeout. No setting is capped, following e90238828006b0, which fixes this bug class by widening the conversion and leaving the configured value alone. No guard at a crash site.
d Tests added, none weakened Yes. 14 new unit tests across src/Common/tests/gtest_saturated_wait_duration.cpp and src/Coordination/tests/gtest_keeper_saturated_wait.cpp. No pre-existing test in the tree is changed. Four of the new tests were strengthened during review rather than weakened: one pins that a long wait ended because its predicate became true, one requires the NuRaft boundary conversion to return the bound exactly for a negative input instead of merely a nonzero value, and the two that assert a non-positive count does not wait now pin that ordering against a later event instead of only bounding the elapsed time.
e Demonstrated in both directions Yes, twice. Under the undefined behaviour sanitizer the unsaturated form reports and aborts while the saturated form is clean, per value. Without a sanitizer the unsaturated form returns failure after 0 ms where the saturated form waits and observes its predicate. The tests also pin why each wait ended, not only how long it took: a build whose period is silently shortened to a fixed 200 ms satisfies the elapsed bound and is still caught.
f General across code paths Twenty sites, list re-derived independently rather than inherited: 15 direct waits and steady_clock comparisons, 3 through ConcurrentBoundedQueue (fixed inside emplaceImpl and popImpl, not at the call sites), 2 at the NuRaft boundary. Both dispatchers are covered. Sites that are already safe (this_thread::sleep_for, condition_variable::wait_for without a predicate, the operation_timeout_ms * 2 that never enters std::chrono) are enumerated and deliberately untouched.
g Generalizes across inputs The helper is a template over std::integral, exercised at 0, 1, a normal default, the exact bound, bound+1, the two values that break only the addition, the two that break the multiplication, INT64_MAX, INT64_MIN, -1 and UINT64_MAX, in both signed and unsigned form. The signedness-agnostic comparison is pinned by reverting it to a signed one and confirming the unsigned case then fails.
h Backward compatible No setting default changes, so no SettingsChangesHistory.cpp entry is needed (that file tracks Settings, not CoordinationSettings). No serialization or wire-format change. Every value any configuration can express today behaves exactly as before; only counts above about 146 years change, and their current behaviour is undefined or an instantly expiring timeout.
i Invariants and contracts preserved Every edit replaces a duration value; no control flow, lock scope or lock ordering is touched. A non-positive count still returns immediately, so no shutdown path can newly block. That is pinned by two ordering tests rather than by a duration bound: each starts an event that arrives a little later, calls the wait, and requires the call to have returned while the event had not happened yet, so an implementation that waits instead of returning is caught however short the wait is. The NuRaft boundary keeps zero meaning "timer disabled". The session timeout keeps its magnitude and sign, so the value replicated through Raft, stored in session_and_timeout and echoed to the client is unchanged.

Each of the four production changes was reverted on its own and confirmed to fail exactly the one test that covers it, so no assertion here is vacuous. Five further degraded implementations were built to check the assertions are not merely one-sided: a period clamped to a fixed 200 ms; the NuRaft boundary conversion returning 1 for a negative input; a period substituted with 200 ms whenever the saturated duration is zero; a period ignored entirely in favour of a 1000 ms wait; and the same zero-to-200 ms substitution inside the queue's popImpl. Every one of them satisfies all the bounds the tests asserted before the strengthenings added during review, and every one of them fails as shipped.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antonio2368 @Michicosun - could you review this? It makes the millisecond-to-nanosecond conversion total at the Keeper coordination waits: a large operation_timeout_ms/session_timeout_ms/startup_timeout overflows both the * 1000000 product and the steady_clock::now() + d deadline, so the wait expires instantly (and aborts under UBSan). The bound is representability, not policy - no setting value changes - and the session TTL and the NuRaft zero-means-disabled boundary deliberately get two different rules.

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

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bd5f747]

Summary: ✅


AI Review

Summary

This PR makes Keeper timeout conversions total by saturating the milliseconds to nanoseconds path and the now() + duration deadline construction, with separate handling for NuRaft timer inputs and KeeperTCPHandler session TTLs. The production changes look internally consistent, but the current regression coverage only proves the generic wait helper; the two new boundary-specific helper rules remain unproven.

Tests
  • ⚠️ [src/Common/saturatedWaitDuration.h:32-54] The surviving tests in src/Coordination/tests/gtest_coordination.cpp exercise only saturatedWaitMilliseconds. There is no focused case for saturatedMicrosecondsFromMilliseconds (KeeperTCPHandler session TTLs) or saturatedWaitMillisecondsCountNonZero (NuRaft's nonzero-timer rule), so those two contracts from the PR description are still unproven.
Final Verdict

Needs focused regression coverage for the two non-generic boundary rules before I would treat the fix as fully validated.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 119/140 (85.00%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3f27c2b

Every failure below has an owner: a fixing PR (ours 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
Bugfix validation (unit tests) / Compile before-binary (ninja unit_tests_dbms, without the fix) PR-caused, test-side only. The job overlays this PR's src/**/tests/* onto the merge-base tree, where the new Common/saturatedWaitDuration.h does not exist yet, so the overlaid TU cannot compile: src/Common/tests/gtest_saturated_wait_duration.cpp:10:10: fatal error: 'Common/saturatedWaitDuration.h' file not found. The runtime assertions are unaffected. fixed in this PR — the new gtest will be made to build against the merge base as well (keeping every runtime assertion intact), which is the sanctioned test-side repair for this job
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d) + Server died (one abort, two rows) pre-existing trunk abort, unrelated to this diff (Keeper coordination timeouts + two new gtests): 94 hits over 83 distinct pull requests and 5 master runs in the last 14 days, first seen 2026-07-14. Tracking issue #110518. #111689 (ours, open)

Session id: cron:our-pr-ci-monitor:20260727-180000

groeneai added 2 commits July 27, 2026 18:50
The Bugfix validation (unit tests) job builds a "before" binary from the
merge-base sources with only this PR's unit-test files overlaid, and requires a
touched test to fail there at runtime. Both new test files instead failed to
COMPILE, because both include Common/saturatedWaitDuration.h, which this PR
adds:

  gtest_saturated_wait_duration.cpp:10:10: fatal error:
      'Common/saturatedWaitDuration.h' file not found

A compile failure is deliberately reported as inconclusive rather than as a
reproduction, so the check stayed red.

Compile the cases that name the helper, and the two that reach the private
KeeperDispatcher::interruptibleSleep, only where the header exists, and leave
the cases that go through public APIs unconditional. Nothing is weakened: the
same 14 cases run on the PR binary, and each of the two suites keeps at least
one case that reproduces the lost timeout on the before-binary. Measured
against the merge-base queue header, six of the seven queue assertions fail
without the fix (every huge timeout gives up after 0 ms instead of waiting) and
all pass with it.

Both privacy and the missing header have to be handled: on the merge-base
KeeperContext::waitCommittedUpto is public, so its case builds and reproduces
there, while interruptibleSleep is private until this PR declares the two
suites its friends.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Bugfix validation (unit tests): fixed on the test side

The Bugfix validation (unit tests) red on 3f27c2b663448bba28f7bbf391e2be0d58fa66b8 was mine,
not infrastructure. The job overlays this PR's src/**/tests/* onto the merge-base tree and requires
a touched case to fail there at runtime; a compile failure is reported as inconclusive instead. Both
new test files failed to compile, because both include Common/saturatedWaitDuration.h, a file this
PR adds:

FAILED: src/CMakeFiles/unit_tests_dbms.dir/Common/tests/gtest_saturated_wait_duration.cpp.o
src/Common/tests/gtest_saturated_wait_duration.cpp:10:10: fatal error:
    'Common/saturatedWaitDuration.h' file not found

Fixed in b1a5100215e6e2df132f285e7258edebaf52e390, test files only, +27/-0. All nine production
files are md5-identical to the previous head.

The cases that name the helper, and the two that reach KeeperDispatcher::interruptibleSleep, are
compiled only where the header exists. The cases that go through public APIs stay unconditional, so
each of the two suites keeps a case the job can run and fail on the before-binary. Two things had to
be handled, not one: on the merge-base KeeperContext::waitCommittedUpto is public, so its case
builds and reproduces there, while interruptibleSleep is private until this PR declares the two
suites its friends.

Nothing is weakened. The same 14 cases run on the PR binary, and the reproduction is measured rather
than assumed. Building the surviving queue cases against the merge-base copy of
ConcurrentBoundedQueue.h and against this PR's copy, only the header differing:

case merge-base (no fix) this PR
tryPop, timeout 9223372036854 to UINT64_MAX (4 values) gives up after 0 ms, returns false waits, returns the item at ~300 ms
tryPush on a full queue, 2 values gives up after 0 ms, returns false waits, succeeds at ~300 ms
zero timeout must not wait returns at once (correct on both) returns at once

Six of the seven assertions fail without the fix and all pass with it, so the check has something to
reproduce. Verified in both directions:

  • the two overlaid files now compile against the merge-base tree, and forcing the guard open again
    reproduces the original file not found in both of them;
  • exposing the two interruptibleSleep cases while leaving the header guarded fails with
    'interruptibleSleep' is a private member of 'DB::KeeperDispatcher', which is why those two are
    guarded as well;
  • on this PR's binary, 14/14 pass, and 20/20 with --gtest_repeat=20.

I also corrected one sentence in the description. It said the linked UBSan report carries no
symbolized ClickHouse frame. It does, and into a line this PR changes: frames 5 to 8 are
condition_variable::wait_for from ConcurrentBoundedQueue<DB::Chunk>::popImpl at
src/Common/ConcurrentBoundedQueue.h:73, through tryPop and LazyOutputFormat::getChunk. That is
direct CI evidence for the queue part of this change, on a query path rather than a Keeper one.

The remaining red on the previous head, Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d), is a pre-existing failure on master (94 hits across 83 unrelated pull
requests in 14 days) and is not caused by this PR. Its fixing PR is #111689.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 244/263 (92.78%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b1a5100

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

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Logical error: Block structure mismatch in A stream: different columns: (STID 0993-29ef) aggregate-state column nested in a Tuple: the block-structure check's aggregate-state tolerance applies only to a top-level ColumnAggregateFunction, so a nested pair falls through to a raw getName() compare and diverges on the spelling fixing PR #111191 (external, open)
CH Inc sync - CH Inc sync (private, not actionable)

Not caused by this PR, whose diff is confined to Keeper coordination and src/Common/saturatedWaitDuration.h - nothing in the query planner or src/Core/Block.cpp.

Context confirms the nested-aggregate-state half of this family: the message is Block structure mismatch in after optimization liftUpUnion stream, and the two dumped column lines are byte-identical (tuple(__table1.a) Tuple(AggregateFunction(quantiles(0.5), UInt8)) Tuple(size = 0, AggregateFunction(size = 0)) twice), because IColumn::dumpStructure prints only the family name and sizes and never the nested spelling that actually differs. Fuzzed query: SELECT quantileMergeTuple(tuple(*)) FROM (SELECT quantilesState(0.5)(1) AS a UNION ALL SELECT quantileStateIf(3, identity(1))).

fatal.log holds exactly one distinct signature, so this is a single event and not an aftermath cascade.

#111191 replaces the top-level-only carve-out with a recursive compatible-structure check that applies the aggregate-state tolerance at any depth. It is still open and master does not carry it, so recurrence here is expected rather than fix failure. Over the last 20 days this exact message has fired on 39 unrelated PRs plus 3 master runs.

Session id: cron:our-pr-ci-monitor:20260728-053000

Resolves the include-block conflict in KeeperRequestDispatcher.cpp introduced
by master's shutdown() split into drainQueues / shutdownRequests /
drainAndCheckQueues (which added Common/FailPoint.h and base/sleep.h at the
same spot this branch added Common/saturatedWaitDuration.h). Both sides kept.

The two saturating-wait call sites that lived in shutdown() now sit inside
master's renamed shutdownRequests(); verified all 10 saturatedWait* call sites
in the file survive the merge, and that the branch's delta against master is
still exactly the same 11 files and +561/-20 as before it.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — af75432

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

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / ColumnBLOB should be converted to a regular column before usage (STID 3059-3663) logical error, trunk family (245 rows / 158 unrelated PRs / 15 master runs in 14d) #111997 (mine, merged 2026-08-04 21:56Z) — this build predates the merge; it will be picked up on the next master merge
Stress test (arm_debug) / Test script failed install_thread_pool_fault_injection aborts the whole job when its --receive_timeout=15 verification query times out after SYSTEM RELOAD CONFIG (68 rows / 64 unrelated PRs / 3 master runs in 14d) #113248 (external, open)
Stress test (arm_msan) / Hung check failed, possible deadlock found cancelled merge('system', '.+') spends 1550s in ReadFromMerge::createChildrenPlans -> QueryAnalysisPass::run with is_cancelled = 1; no cancellation point during QueryPlan::optimize (274 rows / 197 unrelated PRs / 14 master runs in 14d) a fix task owns it (investigating at full effort — fixing-PR link to follow here)
Build (arm_release) / Post Hooks build_profile_hook.py telemetry INSERT fails with LogCluster HTTP 500; non-gating, the enclosing build succeeded a fix task owns it (investigating at full effort — fixing-PR link to follow here)

None of these are caused by this PR's diff: it changes only Keeper millisecond-to-nanosecond wait
conversions, and every signature above is reproduced on master and across dozens of unrelated PRs.

Session id: cron:our-pr-ci-monitor:20260805-013000

groeneai and others added 2 commits August 10, 2026 12:23
Only conflict: src/Coordination/KeeperDispatcher.h include area. Master added
<future>; this branch added two gtest forward declarations at the same spot.
Took both sides, master's include first.

Co-Authored-By: Claude Fable 5 <[email protected]>
ClickHouse#112757 made SettingFieldTimespan reject millisecond values that overflow
Int64 microseconds, so a configured value can no longer wrap negative in
storage. The negative and unsigned-huge cases are still worth pinning
because several Keeper sites hold the count in an unsigned type, so the
comments now state that invariant instead of the storage path.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b6c6c7d

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

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan) / Hung check failed, possible deadlock found deadlock, pre-existing on master #113692 (mine, open)
Stress test (arm_asan_ubsan) / Sanitizer (STID: 1367-26c6) LeakSanitizer, 36864 bytes indirect, 0 direct #113953 (mine, merged) - not in this build, see below
Sync - CH Inc sync (private, not actionable)

The LeakSanitizer red is the Context::createCopy indirect-leak family (all-indirect, zero-direct).
Its fix merged on 2026-08-09; the GitHub compare API reports this head as ahead of that merge
commit, so I checked the failure timing rather than assuming: this stress job completed at 16:09Z
today from a build whose base predates the rebase, and the leak stack is the known
QueryTreeBuilder -> Context::createCopy shape rather than anything in the Keeper paths this PR
touches. If it recurs on a head that provably contains the merge commit I will treat the fix as
insufficient and open a follow-up instead of relinking it.

Build (arm_release) / Post Hooks also appears as a failed row in the CI database, but that
check's own conclusion is success - bookkeeping noise, so I have not ledgered it.

Session id: cron:our-pr-ci-monitor:20260810-193000

Master moved KeeperRequestDispatcher (SessionID routing / special response
router) and KeeperDispatcher. The only textual conflict was one include line:
master added <Common/assert_cast.h> where this branch added
<Common/saturatedWaitDuration.h>. Both kept.

All 23 saturating-wait call sites re-verified against the merged tree: per-file
counts identical to the pre-merge head, every enclosing function still present
and reachable, and both dispatchers (new and Old) keep their
session_shutdown_timeout conversions symmetric.
Each block stated the rationale that belongs in the commit message and PR
description. Comment-only, net -4 lines, no behaviour change.
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bd5f747b1 with master 0df24796b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 6f9856ca1; 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 708.96 MiB 705.86 MiB -3.10 MiB (-0.44%)

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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9f3808f

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

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error: Not-ready Set is passed as the second argument for function 'A (STID 0250-41a5) chronic trunk family in the IN/Set planner path, not this diff: 147 rows / 119 distinct PRs / 10 master hits in 30 days #102308 (external, open)
Stress test (arm_asan_ubsan) / Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (STID 6726-6449) regular-column read abort in MergeTreeReaderWide::readData (Array -> Named -> Nullable), distinct from the skip-index variant of the same message a fix task is created (investigating at full effort - fixing-PR link to follow here)
Stress test (arm_asan_ubsan) / Test script failed job-level marker for the abort above same owner as the row above

Neither failure is caused by this PR: the diff clamps condition_variable::wait_for durations in
Keeper coordination and touches no file under src/DataTypes/Serializations/ or
src/Storages/MergeTree/.

On the second row, note it is not the family that the just-merged #112484 ("Do not deserialize a
skip index whose on-disk type is stale") fixes, even though the message text is identical. That fix is
entirely skip-index scoped, while this stack aborts inside a plain column read:
SerializationNullable.cpp:178 <- SerializationNamed.cpp:106 <- SerializationArray.cpp:528 <-
MergeTreeReaderWide::readData, with no index frame present. Splitting the message-keyed rows of the
last 7 days by stack content gives 290 of 300 in the skip-index path and exactly 1 in this one, so
linking #112484 here would be a coincidental same-area link rather than a fix.

Session id: cron:our-pr-ci-monitor:20260815-193000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up on the STID 6726-6449 ledger line (the MergeTreeReaderWide Nullable size mismatch, not the skip-index variant): no fixing PR will be opened for it, so the owner is the investigation write-up rather than a link.

It did not reproduce across every arm I ran on a debug build at 2409fdca32a8, and the two mechanisms that would explain the stack are ruled out in source. Details, measurements and the two refutations: #114368 (comment)

If the signature recurs on this PR or on master with a coredump, that write-up is where it should be picked up.

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 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.
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.
/// product: this value is the session TTL and is reported to the client, so its magnitude is
/// preserved up to the full Poco::Timespan::TimeDiff (Int64) range rather than clamped to a
/// wait bound. The wait itself is bounded inside KeeperDispatcher::getSessionID.
, min_session_timeout(saturatedMicrosecondsFromMilliseconds(

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.

Preserving min_session_timeout_ms / session_timeout_ms up to the full Int64 Poco::Timespan range here does not actually make large session timeouts defined end-to-end. The same session_timeout is still written through static_cast<int32_t>(session_timeout.totalMilliseconds()) in sendHandshake and truncated to int milliseconds inside poll_wrapper->poll, so even the new “one year” example (31_536_000_000 ms) becomes 1_471_228_928 ms (about 17 days) on both paths.

That means the PR still misreports and misuses large session timeouts rather than preserving their magnitude. I think this needs either a clamp to the narrowest downstream carrier until the protocol is widened, or a split design where the full TTL stays internal but each poll wait is chunked and the wire field is handled 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.

Both casts are real, but neither is touched here and neither behaves differently than on master.

sendHandshake's static_cast<int32_t> and poll's static_cast<int> are byte-identical to master (:293, :164, :194 here; :286, :163, :193 there) and absent from the diff. The only changed expression is the constructor's ms * 1000.

For your own example the two builds agree exactly. session_timeout_ms = 31536000000 gives 31536000000000 microseconds on both, and both then write 1471228928 to the wire. I swept the whole range where master's ms * 1000 is defined, 1000012 samples including every boundary: 0 mismatches. A negative control that clamps the helper inside that range reports 500004, so the sweep discriminates. Divergence begins only above INT64_MAX / 1000, where master is undefined behaviour rather than a smaller number.

So the magnitude loss you describe predates this change and survives it unchanged. Widening the protocol field is a separate, backward-incompatible change, and chunking the poll wait is a behavioural change to the session loop; neither belongs in a bugfix whose contract is to make one conversion total. The handshake int32 divergence is already stated under the boundary rules in the description.

/// steady_clock arithmetic. Comparisons are signedness-agnostic, so an unsigned count holding a
/// wrapped signed value is clamped too. A non-positive count becomes zero.
template <std::integral T>
inline std::chrono::milliseconds saturatedWaitMilliseconds(T ms)

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 helper centralizes the safe conversion for Keeper waits, but the same raw deadline construction is still reachable in src/Coordination/Changelog.cpp: LogEntryStorage::drainReader does steady_clock::now() + std::chrono::milliseconds(readahead_settings.serve_wait_timeout_ms) at src/Coordination/Changelog.cpp:2954, and Changelog::writeThread does the same for flush_settings.min_time_between_fsyncs_ms at src/Coordination/Changelog.cpp:4147.

Both settings are plain UInt64 / NonZeroUInt64, so they can still exceed the safe ~146-year bound and recreate the wrapped-deadline bug this PR is fixing. If the contract here is “fix Keeper coordination timeout overflows”, those sibling deadline sites need to use the same saturation helper too.

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.

Both sites are real and I verified them: :2954 (serve_wait_timeout_ms, reaching the wait_until at :3100) and :4147 (min_time_between_fsyncs_ms). Under UBSan the :4147 shape aborts as you predict, signed integer overflow: 2066730979329341 + 9223372036854000000, so the mechanism carries. Note the deadline addition overflows before tryPop is reached, so master's saturation inside ConcurrentBoundedQueue does not cover it.

I am not folding them in, for two reasons.

Reachability is unproven. Both are UInt64 changelog settings, not Milliseconds, so the validation added by #112757 does not gate them, but a code reading is not a demonstration: I have not shown a running Keeper that accepts such a value and loses the wait. That is exactly the bar I hold my own findings to, so I will not act on it here.

Scope. This PR exists because the same class of finding was expanded indefinitely into #106961 without a maintainer ever weighing in. Changelog.cpp is a different setting family in a file this PR does not touch, and this is a pr-bugfix already at +548. Adding it grows the review surface for a defect I cannot yet show is reachable.

Both file:line sites are now recorded in the description so the information is not lost. If a Keeper owner wants them in the same change, say so and I will add them.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 414012d

CI is fully finished at this commit and no check failed, so no ledger row is owed.

Evidence: 172 unique check runs, none queued or in progress; Config Workflow, Style check and
Finish Workflow all green; no non-green check-run conclusion; praktika result_pr.json reports
the root as OK with every node in {OK, SKIPPED} and 150 OK.

One clarification, because a raw CIDB query at this commit is not empty: the 6 non-green CIDB
rows are all Performance Comparison (arm_release, master_head, N/6) per-query verdicts with
test_status = unstable and check_status = success (set_index #0, set_index #1,
synthetic_hardware_benchmark #39, each an ::old/::new pair). unstable is a perf delta
reported for a human to read rather than a job failure, and the matching praktika nodes read
OK. That count is a real filtered subset rather than an empty query: the control at the same
commit returns 289,916 rows. Nothing to own.

Session id: cron:our-pr-ci-monitor:20260823-180000

@antonio2368 antonio2368 self-assigned this Aug 24, 2026
Comment on lines +140 to +231
TEST(SaturatedWaitDuration, ConcurrentBoundedQueuePopKeepsHugeTimeout)
{
/// popImpl converts the caller's count with the predicate overload of wait_for, so an
/// unsaturated huge count wraps the deadline into the past: the pop gives up at once and
/// reports failure although the caller asked to wait a very long time. Satisfying the
/// predicate a little later separates the two behaviours without waiting out the real timeout.
for (uint64_t timeout_ms : {uint64_t{9'223'372'036'854},
uint64_t{9'223'372'036'855},
uint64_t{9'223'372'036'854'775},
std::numeric_limits<uint64_t>::max()})
{
SCOPED_TRACE(timeout_ms);
ConcurrentBoundedQueue<int> queue(1);

std::thread producer(
[&]
{
std::this_thread::sleep_for(std::chrono::milliseconds(300));
ASSERT_TRUE(queue.tryPush(42, 1000));
});

int x = 0;
Stopwatch watch;
const bool popped = queue.tryPop(x, timeout_ms);
const auto elapsed_ms = watch.elapsedMilliseconds();
producer.join();

EXPECT_TRUE(popped);
EXPECT_EQ(x, 42);
EXPECT_GE(elapsed_ms, 150u);
}
}

TEST(SaturatedWaitDuration, ConcurrentBoundedQueuePushKeepsHugeTimeout)
{
/// Same for emplaceImpl on a full queue: both *Impl functions convert, so each needs a case.
for (uint64_t timeout_ms : {uint64_t{9'223'372'036'854}, std::numeric_limits<uint64_t>::max()})
{
SCOPED_TRACE(timeout_ms);
ConcurrentBoundedQueue<int> queue(1);
ASSERT_TRUE(queue.tryPush(1, 1000));

std::thread consumer(
[&]
{
std::this_thread::sleep_for(std::chrono::milliseconds(300));
int taken = 0;
ASSERT_TRUE(queue.tryPop(taken, 1000));
});

Stopwatch watch;
const bool pushed = queue.tryPush(2, timeout_ms);
const auto elapsed_ms = watch.elapsedMilliseconds();
consumer.join();

EXPECT_TRUE(pushed);
EXPECT_GE(elapsed_ms, 150u);
}
}

TEST(SaturatedWaitDuration, ConcurrentBoundedQueueZeroTimeoutStillReturnsAtOnce)
{
/// Saturation must not turn "do not wait" into a wait. An empty queue reports failure however
/// long the wait lasted, and an elapsed bound accepts any wait shorter than the bound, so
/// neither can say the wait did not happen. A producer that pushes a little later makes it an
/// ordering fact instead: the item must still be in the queue afterwards, which is only true if
/// the pop returned before the push landed. The delay stays below the shortest spurious wait
/// worth catching, because a wait shorter than it would go unnoticed.
constexpr UInt64 push_after_ms = 100;

ConcurrentBoundedQueue<int> queue(1);

std::thread producer(
[&]
{
std::this_thread::sleep_for(std::chrono::milliseconds(push_after_ms));
ASSERT_TRUE(queue.tryPush(42, 1000));
});

int x = 0;
Stopwatch watch;
const bool popped = queue.tryPop(x, 0);
const auto elapsed_ms = watch.elapsedMilliseconds();
producer.join();

EXPECT_FALSE(popped);
EXPECT_LT(elapsed_ms, 300u);

int still_queued = 0;
EXPECT_TRUE(queue.tryPop(still_queued, 0));
EXPECT_EQ(still_queued, 42);
}

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.

How are these tests relevant to this PR? can we remove them?

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.

Removed, the whole file is gone in bd5f747.

Seven of its cases only restated the helper's own arithmetic, and the other three
exercised ConcurrentBoundedQueue, which this PR no longer touches now that #106961 has
merged and master owns that file. Neither group pinned a line changed here.

Comment on lines +90 to +222
TEST_F(KeeperSaturatedWaitTest, WaitCommittedUptoKeepsHugeTimeout)
{
for (UInt64 timeout_ms : hugeUnsignedTimeoutsMs())
{
SCOPED_TRACE(timeout_ms);

auto keeper_context = std::make_shared<KeeperContext>(true, std::make_shared<CoordinationSettings>());
keeper_context->setLastCommitIndex(1);

std::thread committer(
[&]
{
std::this_thread::sleep_for(std::chrono::milliseconds(notify_after_ms));
keeper_context->setLastCommitIndex(10);
});

Stopwatch watch;
const bool committed = keeper_context->waitCommittedUpto(10, timeout_ms);
const auto elapsed_ms = watch.elapsedMilliseconds();
committer.join();

EXPECT_TRUE(committed);
EXPECT_GE(elapsed_ms, static_cast<UInt64>(notify_after_ms) / 2);
}
}

#if SATURATED_WAIT_DURATION_AVAILABLE

/// Sites 5 to 7. All three callers of interruptibleSleep build the period from a coordination
/// setting, so one saturation in the callee covers every one of them.
/// The period arrives already typed as std::chrono::milliseconds, whose representation is signed,
/// and all three callers build it from a signed totalMilliseconds(), so the reachable extremes here
/// are the signed ones. An unsigned count would already have wrapped at the call site.
TEST_F(KeeperSaturatedWaitTest, InterruptibleSleepKeepsHugePeriod)
{
for (Int64 period_ms : huge_timeouts_ms)
{
SCOPED_TRACE(period_ms);

KeeperDispatcher dispatcher;

std::thread shutdown_signaller(
[&]
{
std::this_thread::sleep_for(std::chrono::milliseconds(notify_after_ms));
dispatcher.signalShutdown();
});

Stopwatch watch;
dispatcher.interruptibleSleep(std::chrono::milliseconds(period_ms));
const auto elapsed_ms = watch.elapsedMilliseconds();
/// Read where the wait returned, not after joining the signaller: the signaller sets the
/// flag unconditionally, so a reading taken after the join would be true whatever ended the
/// wait, and would assert nothing.
const bool shutdown_was_signalled_when_the_wait_returned = dispatcher.isShuttingDown();
shutdown_signaller.join();

/// Without saturation the wrapped deadline is already in the past, so this returns at once
/// instead of sleeping until shutdown is signalled.
EXPECT_GE(elapsed_ms, static_cast<UInt64>(notify_after_ms) / 2);
/// The elapsed bound alone would also accept a period silently shortened to anything from
/// 150 ms upwards, which times out instead of keeping the requested period. This pins why
/// the wait ended: the predicate became true, so the saturated period was really kept.
EXPECT_TRUE(shutdown_was_signalled_when_the_wait_returned);
}
}

/// A non-positive period still returns immediately: saturation must not turn "already expired" into
/// a wait, otherwise shutdown paths that pass a wrapped negative count would hang.
TEST_F(KeeperSaturatedWaitTest, InterruptibleSleepReturnsAtOnceForNonPositivePeriod)
{
for (Int64 period_ms : {Int64{0}, Int64{-1}, Int64{-9'223'372'036'854'775}})
{
SCOPED_TRACE(period_ms);

/// A fresh dispatcher per period: the flag latches once signalled, so a shared one would
/// already be shutting down for every iteration after the first and the oracle below would
/// read true without any wait having happened.
KeeperDispatcher dispatcher;

std::thread shutdown_signaller(
[&]
{
std::this_thread::sleep_for(std::chrono::milliseconds(signal_after_ms));
dispatcher.signalShutdown();
});

Stopwatch watch;
dispatcher.interruptibleSleep(std::chrono::milliseconds(period_ms));
const auto elapsed_ms = watch.elapsedMilliseconds();
/// Sampled before the join for the same reason as above: the signaller sets the flag
/// unconditionally, so a reading taken afterwards is true whatever ended the wait.
const bool shutdown_was_signalled_when_the_wait_returned = dispatcher.isShuttingDown();
shutdown_signaller.join();

/// An elapsed bound alone accepts any wait shorter than the signal delay, so it cannot say
/// the wait did not happen. This pins the ordering: the call returned while the predicate
/// was still false, so it did not wait at all.
EXPECT_FALSE(shutdown_was_signalled_when_the_wait_returned);
EXPECT_LT(elapsed_ms, static_cast<UInt64>(notify_after_ms));
}
}

/// The bound is a representability bound, not a policy cap: every coordination default, and a value
/// as large as a year, passes through untouched.
TEST_F(KeeperSaturatedWaitTest, CoordinationDefaultsAreUnaffected)
{
CoordinationSettings settings;
std::vector<Int64> values{
settings[CoordinationSetting::operation_timeout_ms].totalMilliseconds(),
settings[CoordinationSetting::session_timeout_ms].totalMilliseconds(),
settings[CoordinationSetting::startup_timeout].totalMilliseconds(),
settings[CoordinationSetting::session_shutdown_timeout].totalMilliseconds(),
settings[CoordinationSetting::dead_session_check_period_ms].totalMilliseconds(),
settings[CoordinationSetting::ttl_gc_period_ms].totalMilliseconds(),
settings[CoordinationSetting::container_gc_period_ms].totalMilliseconds(),
settings[CoordinationSetting::stream_suspect_retry_delay_ms].totalMilliseconds(),
settings[CoordinationSetting::stream_in_flight_drain_timeout_ms].totalMilliseconds(),
365LL * 24 * 3600 * 1000,
};

for (Int64 ms : values)
{
SCOPED_TRACE(ms);
EXPECT_GT(ms, 0);
EXPECT_EQ(saturatedWaitMilliseconds(ms).count(), ms);
EXPECT_EQ(saturatedWaitMillisecondsCountNonZero(ms), static_cast<UInt64>(ms));
}
}

#endif

#endif

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.

Explain relevance of all these tests and why do we need them

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.

This file is gone too. Three of its cases survive, moved into the existing
gtest_coordination.cpp (bd5f747); the other one was a helper-arithmetic case and went with
the rest.

The three that stayed, and the line each pins:

  • KeeperContext.WaitCommittedUptoKeepsHugeTimeout - KeeperContext.cpp:837. Reverting it to
    std::chrono::milliseconds(wait_timeout_ms) makes the case fail with committed=false after
    0 ms: the wrapped deadline is already past, so a long timeout gives up at once.
  • KeeperDispatcher.InterruptibleSleepKeepsHugePeriod - KeeperDispatcher.cpp:430, covering all
    three callers. Same revert, same failure, 0 ms elapsed.
  • KeeperDispatcher.InterruptibleSleepReturnsAtOnceForNonPositivePeriod - the other direction,
    that saturation must not turn "already expired" into a wait. It goes red if that site uses
    saturatedWaitMillisecondsCountNonZero (upper-only) instead of the wait variant, which is the
    realistic mix-up between the two.

Dropping the separate module also let me revert KeeperDispatcher.h to its master content:
that header only changed to friend two test classes, and gtest_coordination.cpp already has
KeeperDispatcherTestAccessor as a friend, so no production file is modified for a test now.

Net test surface: 453 lines removed, 132 added. 402 Keeper/Coordination cases pass with no
failures, and the three new ones passed 45/45 over 15 repeats.

On C++ versus SQL: these are millisecond-to-nanosecond conversions on internal coordination
waits with no SQL surface, and reaching them from a client needs a multi-year timeout setting.
If you would rather see this as an integration test under tests/integration/, or with no test
at all, say which and I will do that.

…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.
Comment on lines +32 to +54
/// For a value that is not a wait and must keep its magnitude and sign: only the multiplication is
/// made total, at the full Int64 range of Poco::Timespan::TimeDiff. The wait bound must not be used
/// here, it would change the value the server acts on and reports.
template <std::integral T>
inline Int64 saturatedMicrosecondsFromMilliseconds(T ms)
{
constexpr Int64 max_ms = std::numeric_limits<Int64>::max() / 1000;
constexpr Int64 min_ms = std::numeric_limits<Int64>::min() / 1000;
if (std::cmp_greater(ms, max_ms))
return std::numeric_limits<Int64>::max();
if (std::cmp_less(ms, min_ms))
return std::numeric_limits<Int64>::min();
return static_cast<Int64>(ms) * 1000;
}

/// Upper-only, for a callee that converts to chrono itself and treats zero as "timer disabled"
/// (NuRaft). Converting to unsigned first, as the callee's uint64_t parameter already does, keeps a
/// nonzero input nonzero.
template <std::integral T>
inline UInt64 saturatedWaitMillisecondsCountNonZero(T ms)
{
const UInt64 unsigned_ms = static_cast<UInt64>(ms);
return std::min<UInt64>(unsigned_ms, static_cast<UInt64>(MAX_WAIT_MILLISECONDS));

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.

After the test cleanup, the surviving cases in gtest_coordination.cpp only exercise saturatedWaitMilliseconds through waitCommittedUpto and interruptibleSleep. Nothing now covers either boundary helper in this range: saturatedMicrosecondsFromMilliseconds on the KeeperTCPHandler session-TTL path, or saturatedWaitMillisecondsCountNonZero on the two open_client_req_stream call sites.

That leaves two contracts from the PR description unproven. A future refactor that clamps session TTLs to the wait bound, or one that maps wrapped negatives to zero and silently disables the NuRaft timer, would still pass the current suite. Please keep one focused regression for each of these non-generic boundary rules.

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 coverage claim is correct: nothing names either helper. But the remedy is not available in a unit test, and the one form that would work is the form the assignee just asked me to remove.

saturatedMicrosecondsFromMilliseconds: min_session_timeout and max_session_timeout are private members of KeeperTCPHandler with no accessor and no friend declaration, dumpStats prints only the negotiated session_timeout, and constructing the handler needs a live StreamSocket and dispatcher. No gtest in the tree references KeeperTCPHandler, and no symbol of it is present in unit_tests_dbms today. A regression for that path is an integration test, not a gtest.

saturatedWaitMillisecondsCountNonZero: the count only reaches anything when the leader is remote. open_client_req_stream passes a null rpc_client when leader == id_ (handle_user_cmd.cxx:457), and the value is read only at client_req_stream.cxx:98. Every dispatcher fixture here is a single-node cluster that is its own leader, so an assertion on those two call sites would pass whatever the helper returned. The zero-disables-the-timer rule you want pinned lives at asio_service.cxx:1715 and :1758, behind that same remote path.

That leaves an exact-value assertion on the helpers as the only unit-test form, and those are exactly the cases removed in bd5f747 at the assignee's request. I am not restoring them. The choice between an integration test and no test is already open with him, and I will do whichever he picks.

One correction to your framing: InterruptibleSleepReturnsAtOnceForNonPositivePeriod goes red if that wait site is switched to saturatedWaitMillisecondsCountNonZero, so it pins the boundary between the two helpers rather than the CountNonZero contract. You are right that the contract itself is unpinned.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — bd5f747

Every failure below has an owner: a fixing PR (ours 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
(none) CI finished with no failing check on this commit n/a

151 checks succeeded, 0 failed, 23 skipped (unchanged Docker images, the master_head performance
baseline, the flaky-check and bugfix-validation gates, Docs check (Mintlify), and the PGO/BOLT
toolchain builds). CIDB reports 0 FAIL/ERROR test rows for this commit.

Session id: cron:our-pr-ci-monitor:20260824-170000

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

Labels

can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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.

4 participants