Repository navigation
Fix undefined behavior in the workload throttler's postponement delay - #113697
Conversation
ThrottlerConstraint::updateBucket derives a postponement delay from the user's max_bytes_per_second / max_queries_per_second / max_cpus and feeds it into two unguarded signed statements. WorkloadSettings::getFloat64 rejects only non-finite and negative values, so any tiny positive speed passes validation. A cost-1 request drives the token balance negative, and -tokens / max_speed * 1e9 then grows without bound. The static_cast<Int64> of that quotient is undefined once it exceeds Int64, and the following now + delay_ns is a plain Int64 addition on a steady_clock epoch that is already ~1e15 ns into the node's uptime. throttling_duration is a third site: it is initialised once and only ever incremented over the node lifetime, so no bound on a single delay keeps the sum in range. An ASan+UBSan build of master aborts on CREATE RESOURCE r (QUERY); CREATE WORKLOAD all; CREATE WORKLOAD w IN all SETTINGS max_queries_per_second = 1e-30; with "1e+39 is outside the range of representable values of type 'long'" at ThrottlerConstraint.h:175, and on the same statement at 1.5e-10 with "signed integer overflow: 6666666665666666496 + 6666666659630823424" inside duration::operator+=. Both are reachable from plain SQL with no fuzzer and no randomization. The three thresholds are ordered and the narrowing's is the loosest: the sum overflows below max_speed 2.168e-10, the time-point addition below 1.0842691e-10, and the narrowing only below 1.0842022e-10. Clamping the cast alone therefore relocates the undefined behavior into the two consumers instead of removing it, which is why the bound is derived from the addition: the largest representable duration minus the elapsed part of now. The comparison happens in Float64 before the cast, since casting an out-of-range value is exactly what is being avoided. The accumulator saturates rather than wrapping. steady_clock's epoch is unspecified, and a negative one leaves room for a delay longer than the time already elapsed, so two delays that are each in range can still sum out of range. Below the bound (~292 years) the arithmetic is bit-for-bit unchanged, so only delays no real caller uses behave differently. Saturating rather than throwing matters because updateBucket runs on the scheduler thread, where an escaping exception would break every future scheduler event. Without the sanitizer the same defect is user-visible: at 1e-30 system.scheduler.throttling_us reports -9223372036854775. The three cases are separate tests because the sanitizer builds are compiled with -fno-sanitize-recover=all, so the first unbounded statement aborts the process and would hide the other two.
ThrottlerConstraint accounts a postponement in throttling_duration up front, when the delay is computed, not as it elapses. updateConstraints cancels the pending postponement, resets `postponed` to `not_postponed`, and then calls updateBucket(0, false), which re-enters the branch and adds the same, not yet elapsed delay again. Each ALTER or CREATE OR REPLACE of a workload therefore inflates the metric by a whole delay that never happened, and it accrues without limit because nothing resets it. On a debug build with an ordinary max_queries_per_second = 0.001, one in-flight query and three CREATE OR REPLACE WORKLOAD in about eleven wall seconds, system.scheduler.throttling_us went 999000000, 1992985094, 2984949909, 3974892442: nearly 3975 seconds of reported throttling. The column can exceed the server's own uptime, which makes it useless for the rate limiting it describes. Cancelling a postponement now returns the part of the delay that was counted but not served, so the re-postponement replaces it instead of adding to it. The remaining time is derived from the deadline rather than from the delay, so a partly served postponement keeps the part that did elapse: cancelling halfway through a 1000 second delay leaves 500 seconds counted, and re-postponing brings it back to 1000. The only other place `postponed` is cleared is `onPostponed`. It normally runs because the deadline arrived, in which case the whole delay did elapse and there is nothing to give back. `EventQueue::forceProcess` can also fire a postponed event with time to spare, since it ignores the deadline by design, but it is only ever reached from a scheduler's graceful `stop`, and every caller of that is a destructor tearing the scheduler down. So the node and its throttlers are going away and the metric is never read again, the same reason the destructor's own `cancelPostponed` is left alone. Cancelling in the destructor is left alone: the node is going away and its metric is never read again.
Internal second-model review (2 rounds, 1 finding, adjudicated)An independent reviewer model re-reviewed this change cold, against the PR description only. Its
Also fixed in this round, from my own review of the same tree: 💡 The 💡 Two figures in this description were corrected against the artifacts they summarize: the mutation A second review round re-derived the load-bearing properties independently and found nothing further |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-43:20260806-075400 |
|
cc @serxa @alexey-milovidov, could you review this? A tiny positive |
|
Workflow [PR], commit [98f7039] Summary: ✅
AI ReviewSummaryThis PR fixes the undefined-behavior path in Final Verdict
LLVM Coverage ReportMeasured on commit 98f7039.
Changed lines: Changed C/C++ lines covered: 12/12 (100.00%) · Uncovered code |
`ThrottlerConstraint::updateConstraints` declares `new_max_speed` and `new_max_burst`, so the `/*max_speed=*/` and `/*max_burst=*/` comments this change added at three call sites are `bugprone-argument-comment` errors and `Build (arm_tidy)` rejects them. Locally, `clang-tidy-21` on the file reports exactly the four diagnostics CI reports, at the same lines and columns, and none after the rename. The file's other eight argument comments stay as they are. Renaming all of them reddens `parkOneRequest`, whose parameter genuinely is `max_speed`. The seven `t.add<ThrottlerConstraint>` ones reach the constructor through `ResourceTest::add`'s variadic forwarding, where the check has no parameter name to compare against: a comment naming nothing at all is not diagnosed there either. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Both points are fixed in
I deliberately left the file's other fourteen argument comments alone. Renaming them all reddens Coverage on the SHA: you are right that nothing ran on That is the five new arms plus the six pre-existing ones, 0 failed. CI now has a green build to run |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 16 s compile time in total, 8 of them have a recent master baseline. |
CI finish ledger - 2c04985Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
All 175 check-runs completed (149 success, 23 skipped, 1 failure at the time the workflow finished); Fix presence was established per build, not from the merge date: Session id: cron:our-pr-ci-monitor:20260807-130000 |
|
@groeneai Recently you introduced a set of functions to work with saturated time to avoid overflows, is it possible to reuse here? problem seems to be similar, but not quite. That part that check for small values should stay anyway. But let's check if we can make implementation simpler and more understandable |
|
Partially, and the part that reuses cleanly is the bound itself. Both headers postdate this PR ( What does not fit: every helper in either header is What does fit: inline constexpr Int64 MAX_WAIT_NANOSECONDS = MAX_WAIT_MILLISECONDS * 1'000'000;
/// Same bound for a count that arrives as a Float64. The clamp precedes the conversion, because
/// converting an out-of-range Float64 to an integer is itself undefined. NaN takes the zero branch.
inline std::chrono::nanoseconds saturatedWaitNanoseconds(Float64 ns)
{
if (!(ns > 0))
return std::chrono::nanoseconds(0);
if (ns >= static_cast<Float64>(MAX_WAIT_NANOSECONDS))
return std::chrono::nanoseconds(MAX_WAIT_NANOSECONDS);
return std::chrono::nanoseconds(static_cast<Int64>(ns));
}
auto delay_ns = saturatedWaitNanoseconds(-tokens / max_speed * 1e9);Measured rather than argued: Two things cannot move into the shared header. The one consequence is that this PR has to merge master to see the header. |
|
I built it and then measured it, and I am withdrawing the push. Three findings, in the order they came up. The shared bound is a policy cap, not a representable-range limit. Sharing one bound between a single delay and the accumulated total breaks the give-back. A clamped delay then lands exactly on the ceiling, Keeping the ceiling separate instead makes the saturation test unreachable. A delay capped below the debt fires its postponement before the debt is paid, so the request is not servable at its own deadline: So the reusable part is smaller than it looked. Every helper in both headers is If you would still rather have the shared helper, or a different shape for that function, tell me which and I will push it. |
|
@groeneai This is obscure; there is no point in having delays longer than ~1 year. This kind of simple saturation will make the code much easier. Also, it doesn't matter that we show the values in |
As requested in review, bound the postponement with a plain saturation instead of deriving the bound from the time point the delay is added to. A postponement longer than a year is meaningless, and a fixed bound needs neither the elapsed part of `now` nor a record of the pending deadline, so `boundedDelay` and `postponed_until` go away. `now + delay` then stays in range for any `steady_clock` less than 291 years past its epoch, which a monotonic-since-boot clock cannot reach. The accumulated total still needs its own saturation: a bounded delay is re-counted on every re-postponement and `ALTER WORKLOAD` re-postpones without waiting, so 293 of them overrun the Int64 nanosecond range. This also drops the accounting change for a cancelled postponement. Its only consumer is `system.scheduler.throttling_us`, which review calls a debugging surface rather than a contract, and it is no longer load-bearing now that every addition to the total saturates.
|
Done in ce4757d. The delay saturates at one year now, applied before the narrowing since casting the out-of-range Two things I measured rather than assumed:
On the metric, I dropped the accounting commit, since 9 gtests pass, and removing either guard reddens a new arm while all 6 pre-existing arms stay green. |
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) |
the referenced file is 4 lines and all 4 are Cluster: Code: 198. DB::NetException: Not found address of host: <250-byte host>, with 0 lines of any other error. Those hosts are 04725_distributed_async_insert_long_directory_name's deliberately unresolvable Remote targets being resolved by a restarted server's cluster discovery, not a compatibility break |
#117284 (mine, open) |
Docs examples / Documentation examples / Function/toYYYYMM#0 |
the toYYYYMM documentation example pinned its output to a value derived from the current date, so it started failing at the month rollover on every pull request and on master |
#117459 (mine, merged 2026-09-01), absent from this tree |
Bugfix validation (unit tests) |
the harness declined to judge rather than reporting a false result: ci/jobs/unit_tests_bugfix_validation_job.py:828 reports Bugfix validation inconclusive: submodule state differs between the merge-base and the checkout for 16 paths, because the base branch moved submodules after this branch split and the before-worktree can only be populated with the checkout's submodule content. The job is set_allow_failure(True). Trunk-wide rather than specific to this branch: 5 distinct pull requests hit the same refusal in the last 3 days |
a fix task is created (fixing-PR link to follow on this PR) |
None of the rows above is caused by this pull request.
I am not merging master here purely to re-run CI: #117284 is still open, so the Upgrade check
row would red again on the fresh run.
Session id: cron:our-pr-ci-monitor:20260901-190000
|
The fix for the |
|
Dear @serxa, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
@groeneai let's merge master and make sure CI is green |
…t-delay-overflow Co-Authored-By: Claude Opus 5.5 <[email protected]>
…_constraint`. After merging current `master`, `parkOneRequest` from ClickHouse#113697 still instantiates the removed `FifoQueue`, which breaks `Build (arm_tidy, 2/4)`. Use `RequestQueue`, matching ClickHouse#124798. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120225&sha=520b56a12537be7c7c34950caa17a042c6d7ac8d&name_0=PR&name_1=Build%20(arm_tidy,%202/4) ClickHouse#120225
ClickHouse#113697 added `parkOneRequest` using `FifoQueue`, while 322f98b removed `FifoQueue` in favour of `RequestQueue`. The two merged independently, so `unit_tests_dbms` no longer compiles on `master`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a signed overflow in the workload throttler that made
system.scheduler.throttling_usreport a negative value for a workload whosemax_bytes_per_second,max_queries_per_secondormax_cpusis small enough to postpone a request for longer than a year. Such a postponement is now saturated at one year.Description
ThrottlerConstraint::updateBucketderives a postponement delay from a user-supplied throttler speed and feeds it into three unguarded signed statements.WorkloadSettings::getFloat64rejects only non-finite and negative values, so any tiny positive speed passes validation, and-tokens / max_speed * 1e9then grows without bound.Two of those statements are undefined behavior: the
static_cast<Int64>of that quotient and the followingnow + delay_ns. An ASan+UBSan build of master aborts onCREATE WORKLOAD w IN all SETTINGS max_queries_per_second = 1e-30plus one query throughw. Without the sanitizer the narrowing yieldsINT64_MINinstead, andsystem.scheduler.throttling_usthen reports-9223372036854775.Postponing a request for longer than a year is meaningless, so the delay now saturates at one year. The bound is applied before the narrowing, because casting the out-of-range
Float64is itself the undefined behavior.now + delayis then in range for anysteady_clockless than 291 years past its epoch, which a monotonic-since-boot clock does not reach.The third statement,
throttling_duration += delay_ns, accumulates for the node's lifetime, so bounding a single delay cannot bound the sum: a pending delay is counted again on every re-postponement, andALTER WORKLOADre-postpones without waiting, so 293 of them overrun theInt64nanosecond range. That addition saturates as well.Cancelling a postponement still re-counts the part of its delay that never elapsed, so a few hundred
ALTER WORKLOADs pinthrottling_usat that ceiling. The commit that corrected that accounting is dropped from this PR, because that column is its only consumer.Verified with 9 gtests in
gtest_throttler_constraint.cpp, 3 of them new, and a two-mutant matrix in which removing either guard reddens a new arm while none of the 6 pre-existing arms ever reddens. The three statements were also checked standalone under-fsanitize=undefined -fno-sanitize-recover=all: the bounded form is silent, and each unbounded control aborts.Workflow [PR]
Sync PR [sync-upstream/pr/113697]
Version info
26.10.1.1887-master(included in26.10and later)