Repository navigation
Fix signed integer overflow in Keeper coordination timeouts - #112088
Conversation
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.
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 Round 0 (
|
Pre-PR validation gate
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 |
|
cc @antonio2368 @Michicosun - could you review this? It makes the millisecond-to-nanosecond conversion total at the Keeper coordination waits: a large |
|
Workflow [PR], commit [bd5f747] Summary: ✅
AI ReviewSummaryThis PR makes Keeper timeout conversions total by saturating the Tests
Final VerdictNeeds focused regression coverage for the two non-generic boundary rules before I would treat the fix as fully validated. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 119/140 (85.00%) · Uncovered code |
CI finish ledger — 3f27c2bEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260727-180000 |
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.
Bugfix validation (unit tests): fixed on the test sideThe Fixed in The cases that name the helper, and the two that reach Nothing is weakened. The same 14 cases run on the PR binary, and the reproduction is measured rather
Six of the seven assertions fail without the fix and all pass with it, so the check has something to
I also corrected one sentence in the description. It said the linked UBSan report carries no The remaining red on the previous head, |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 244/263 (92.78%) · Uncovered code |
CI finish ledger - b1a5100Every 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
Not caused by this PR, whose diff is confined to Keeper coordination and Context confirms the nested-aggregate-state half of this family: the message is
#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.
CI finish ledger — af75432Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
None of these are caused by this PR's diff: it changes only Keeper millisecond-to-nanosecond wait Session id: cron:our-pr-ci-monitor:20260805-013000 |
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]>
CI finish ledger - b6c6c7dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The LeakSanitizer red is the
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units12 translation units recompiled, 46 s compile time in total, 12 of them have a recent master baseline. |
CI finish ledger - 9f3808fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Neither failure is caused by this PR: the diff clamps On the second row, note it is not the family that the just-merged #112484 ("Do not deserialize a Session id: cron:our-pr-ci-monitor:20260815-193000 |
|
Follow-up on the STID 6726-6449 ledger line (the It did not reproduce across every arm I ran on a debug build at If the signature recurs on this PR or on master with a coredump, that write-up is where it should be picked up. |
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger - 414012dCI 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 One clarification, because a raw CIDB query at this commit is not empty: the 6 non-green CIDB Session id: cron:our-pr-ci-monitor:20260823-180000 |
| 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); | ||
| } |
There was a problem hiding this comment.
How are these tests relevant to this PR? can we remove them?
There was a problem hiding this comment.
| 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 |
There was a problem hiding this comment.
Explain relevance of all these tests and why do we need them
There was a problem hiding this comment.
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 withcommitted=falseafter
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 mselapsed.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.
| /// 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)); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger — bd5f747Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
151 checks succeeded, 0 failed, 23 skipped (unchanged Docker images, the Session id: cron:our-pr-ci-monitor:20260824-170000 |
Related: #106961
Changelog category (leave one):
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_msorstartup_timeoutis 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::chronoexpression whose common type isnanoseconds, held in anInt64. Both thecount() * 1000000conversion and the deadline additionsteady_clock::now() + dcan 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 acrossKeeperServer,KeeperContext,KeeperDispatcherand both request dispatchers, two at theopen_client_req_streamboundary into NuRaft; the three boundaries keep different rules, detailed below. The three sites reached throughConcurrentBoundedQueueare fixed onmasterby #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 declaresKeeperDispatcherTestAccessora friend ofKeeperDispatcher.Not in this PR.
contrib/NuRaft/src/asio_service.cxx, a submodule needing its own pull request against the fork. Converging withmaster'sDB::saturatedMilliseconds, whose one year policy cap is the wrong bound for a coordination timeout. Andsrc/Coordination/Changelog.cpp, which builds twosteady_clockdeadlines from rawUInt64settings (: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
wait_fordoes with a non-positive duration anyway, so no shutdown path can newly block. The two dispatchers already read this setting into different types onmaster,int64_tinKeeperRequestDispatcheranduint64_tinKeeperRequestDispatcherOld, so a negative count saturates to zero on the signed sites and to the bound on the unsigned ones. Those declarations are untouched; onmasterboth are undefined behaviour instead.min_session_timeout/max_session_timeoutinKeeperTCPHandleronly get their* 1000made safe, at the fullPoco::Timespan::TimeDiffrange. This is not a wait: it is copied into the replicated request, stored insession_and_timeoutand the expiry queue, and compared at full microsecond value, so clamping it would change expiry policy. The wait on this path is bounded insidegetSessionID. The handshake reply is a protocolint32, so asession_timeout_msaboveINT32_MAXalready diverges between server and client onmaster, identically; widening that field is separate.uint64_tparameter 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_forwithout 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_foris unsafe regardless, beingwait_until(now() + rel)with no checked cast.sleep_foris safe, so the two Keepersleep_forsites are untouched, andKeeperServer.cpp'soperation_timeout_ms * 2never entersstd::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
26.9.1.94(included in26.9and later)