Skip to content

Fix undefined behavior in the workload throttler's postponement delay - #113697

Merged
serxa merged 5 commits into
ClickHouse:masterfrom
groeneai:throttler-constraint-delay-overflow
Oct 9, 2026
Merged

serxa merged 5 commits into
ClickHouse:masterfrom
groeneai:throttler-constraint-delay-overflow

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a signed overflow in the workload throttler that made system.scheduler.throttling_us report a negative value for a workload whose max_bytes_per_second, max_queries_per_second or max_cpus is small enough to postpone a request for longer than a year. Such a postponement is now saturated at one year.

Description

ThrottlerConstraint::updateBucket derives a postponement delay from a user-supplied throttler speed and feeds it into three unguarded signed statements. WorkloadSettings::getFloat64 rejects only non-finite and negative values, so any tiny positive speed passes validation, and -tokens / max_speed * 1e9 then grows without bound.

Two of those statements are undefined behavior: the static_cast<Int64> of that quotient and the following now + delay_ns. An ASan+UBSan build of master aborts on CREATE WORKLOAD w IN all SETTINGS max_queries_per_second = 1e-30 plus one query through w. Without the sanitizer the narrowing yields INT64_MIN instead, and system.scheduler.throttling_us then 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 Float64 is itself the undefined behavior. now + delay is then in range for any steady_clock less 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, and ALTER WORKLOAD re-postpones without waiting, so 293 of them overrun the Int64 nanosecond 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 pin throttling_us at 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

  • Merged into: 26.10.1.1887-master (included in 26.10 and later)

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

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 1 finding, adjudicated)

An independent reviewer model re-reviewed this change cold, against the PR description only. Its
finding and my adjudication:

⚠️ gtest_throttler_constraint.cpp — the new tests assert only the duration counter, so a mutant
that skips event_queue.postpone while still updating the counter would pass.
Disagreed, with a
trace.
Both realizations of that mutant are caught. If the postpone call is dropped and
postponed is left at not_postponed, every later updateBucket re-enters the
postponed == not_postponed branch and adds the delay again, so
ThrottlingDurationIsNotDoubleCounted reads twice the delay against an exact EXPECT_EQ — the very
test the finding names. If instead a fake non-zero id is assigned so the give-back still runs, that
test does pass, but no event exists in the queue, so nothing calls onPostponed, nothing refreshes
the token balance, active() stays false, and ResourceTest::process returns before dequeuing;
ThrottlingDurationIsAccumulated then sees 0 consumed against t.consumed("A", 1), which asserts
exactly 1. The release oracle exists as a cross-test pin inside the same suite. The pre-existing
Pacing test also asserts the blocked side directly: its expected-consumption vector requires
exactly 0 consumed at the seconds where the throttler must still be postponing, and it stays green
under all eight mutants.

Also fixed in this round, from my own review of the same tree:

💡 The forceProcess path can fire a postponed event before its deadline, so the commit message's
statement that onPostponed runs only because the deadline arrived was too strong. The conclusion is
unchanged — that path is only ever reached from a scheduler's graceful stop, and every caller of
that is a destructor tearing the scheduler down, so the metric is never read again — and the message
now says so.

💡 Two figures in this description were corrected against the artifacts they summarize: the mutation
matrix is eight-for-eight caught with none of the six pre-existing arms ever reddening (two mutants
redden more than one arm, so the earlier one-to-one phrasing was wrong), and the double-count
measurement had one request parked, not two.

A second review round re-derived the load-bearing properties independently and found nothing further
in the code. The delay bound was re-proven numerically: for 109,657 values of the elapsed part of
now, taking the largest double the guard admits, the narrowing stays in range and
elapsed + delay never exceeds the maximum, with a minimum slack of 1 ns. The reviewer model
returned no findings in that round.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, two. gtest: unit_tests_dbms --gtest_filter='SchedulerThrottlerConstraint.TinySpeedDelayNarrowingIsBounded' on an ASan+UBSan build of master aborts with rc=134. SQL: CREATE RESOURCE r (QUERY); CREATE WORKLOAD all; CREATE WORKLOAD w IN all SETTINGS max_queries_per_second = 1e-30; then one query with ?workload=w.
b Root cause explained? WorkloadSettings::getFloat64 rejects only non-finite and negative values, so any tiny positive throttler speed passes validation. A cost-1 request drives the token balance negative and -tokens / max_speed * 1e9 grows without bound, which is then narrowed to Int64 (ThrottlerConstraint.h:175) and added to a steady_clock time point already ~1e15 ns into the node's uptime (:178). Separately, throttling_duration += delay_ns (:180) accounts a delay when it is scheduled, and updateConstraints cancels the pending postponement and re-postpones, adding the same unelapsed delay again.
c Fix matches root cause? The bound is derived from the consuming addition rather than from INT64_MAX, because the three overflow thresholds are ordered with the narrowing's the loosest: clamping the cast alone relocates the undefined behavior into its two consumers instead of removing it. The comparison happens in Float64 before the cast, since casting an out-of-range value is what is being avoided. The accumulator saturates because no bound on a single delay can keep a lifetime sum in range. The double-count is fixed where it originates, by returning the counted-but-unserved part when a postponement is cancelled. Nothing is guarded at a crash site.
d Test intent preserved / new tests added? 5 new gtests in gtest_throttler_constraint.cpp. The 6 pre-existing SchedulerThrottlerConstraint tests are unchanged and stay green under every mutant, which is the demonstration that arithmetic below the bound is bit-for-bit unchanged. No test weakened, no bound widened, no dataset reduced.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. SQL, base 0ac3a7ca vs fix 7feba8af: at max_queries_per_second = 1e-30, system.scheduler.throttling_us reads -9223372036854775 on base and +9222786351514820 on the fix; at an ordinary 0.001 with one request parked, three CREATE OR REPLACE WORKLOAD take it 1000000000 -> 1995874950 -> 2990602206 -> 3984170406 on base and leave it flat at ~999999993 on the fix. Plus an 8-mutant matrix on ASan+UBSan in which every mutant is caught and none of the six pre-existing arms ever reddens; reverting the delay bound reproduces all three original sanitizer signatures.
f Fix is general across code paths? Censused. postpone has exactly one production call site in src/ (this one; the others are in gtest_event_queue.cpp, and MergeTreeData.cpp's background_*_assignee.postpone() is an unrelated method). duration += / nanoseconds += over src/Common/Scheduler/ has exactly one hit. cancelPostponed has two callers in this class; the destructor's is left alone, since the node is going away and its metric is never read again. SemaphoreConstraint, the sibling node, computes no delay and scores 0 for postpone. getThrottlingDuration has one consumer, StorageSystemScheduler.cpp:236. EventQueue::waitUntil uses condition_variable::wait_until, whose internal cast saturates and performs no addition, so it is not a further carrier, unlike wait_for.
g Fix generalizes across inputs? All four getThrottlerMaxSpeed branches feed the same single max_speed, so max_bytes_per_second, max_queries_per_second and max_cpus are covered by construction; only the scale differs, as CPUNanosecond multiplies by 1e9. Boundaries exercised directly under UBSan with zero reports: delay inf and nan both clamp, 0.0 returns zero, and epochs 1 ns, 1 s, 2^62 ns, -1 s and INT64_MAX all stay in range. Accumulator boundaries 0+0, 0+MAX, MAX+0, MAX+1, MAX+MAX, MAX/2+MAX/2 and a 1000-add chain are all monotone, in range and saturating. Give-back boundaries (nothing elapsed, half elapsed, fully elapsed, overdue, already saturated, remaining greater than the total, total zero, negative epoch) are all non-negative and in range.
h Backward compatible? Yes. No setting, default, format or serialization change, so no SettingsChangesHistory entry is owed. Below the bound of about 292 years the arithmetic is bit-for-bit unchanged; the only behavior that differs belongs to delays no real caller uses, plus a metric that was previously wrong.
i Invariants and contracts preserved? The invariant is that a delay derived from a user-supplied speed must not overflow any signed arithmetic it flows into, and that the throttling metric must be non-negative, monotone and never exceed the largest representable duration. Verified on all paths including the boundary matrix in row g. postponed_until is written immediately before postpone and read only while a postponement is pending, so it is never stale. One guard exists specifically to keep monotonicity: skipping the give-back once the accumulator has saturated, since without it a cancellation would return an unelapsed part of a delay that was only partly counted and the metric would go down.

Session id: cron:clickhouse-impl-slot-43:20260806-075400

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @serxa @alexey-milovidov, could you review this? A tiny positive max_queries_per_second passes validation, so the postponement delay -tokens / max_speed * 1e9 grows without bound and is then narrowed to Int64 and added to a steady_clock time point, which aborts sanitizer builds; separately throttling_duration accounts the whole delay when the postponement is scheduled, so every ALTER WORKLOAD re-counts a delay that has not elapsed.

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

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [98f7039]

Summary: ✅


AI Review

Summary

This PR fixes the undefined-behavior path in ThrottlerConstraint by clamping the postponement delay before the Float64→Int64 narrowing and by saturating the lifetime throttling_duration accumulator separately. The current diff matches that contract, and the added tests cover the three affected edges: out-of-range narrowing, now + delay overflow, and accumulator saturation.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 98f7039.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 12/12 (100.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 Aug 7, 2026
`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]>
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

Both points are fixed in 2c04985daf9d30c343d84b65b59ff622c560629d.

bugprone-argument-comment: renamed the three updateConstraints call sites to
/*new_max_speed=*/ / /*new_max_burst=*/. I kept the comments rather than dropping them, since
the callee takes two bare doubles. Locally clang-tidy-21 on that file reports exactly the four
diagnostics Build (arm_tidy) reported, at the same lines and columns, and none after the rename;
the full repo check set on it is also clean.

I deliberately left the file's other fourteen argument comments alone. Renaming them all reddens
:215, whose callee is the file-local parkOneRequest(..., double max_speed). The other thirteen, on
seven t.add<ThrottlerConstraint> lines, reach the constructor through ResourceTest::add's variadic
forwarding, where the check has no parameter name to compare against: substituting a name that
matches nothing at all there still produces no diagnostic.

Coverage on the SHA: you are right that nothing ran on 0bc34417: 6 checks succeeded, 168
were skipped and the tidy failure dropped the rest. I ran the command you suggested rather than
wait for the next round. After rebuilding unit_tests_dbms (Build ID moved 9d2e1de30e6e204d to
68071124710dcee, so the binary does contain the change):

$ ./build/src/unit_tests_dbms --gtest_filter='SchedulerThrottlerConstraint.*'
[==========] 11 tests from 1 test suite ran. (26 ms total)
[  PASSED  ] 11 tests.

That is the five new arms plus the six pre-existing ones, 0 failed. CI now has a green build to run
them on.

@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 98f703960 with master b2eae7a4e (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2c04985

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
Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6) / test_spark_session_recovery/test.py::test_recovers_dead_gateway_and_reuses_live_one test-harness flake, not PR-caused. ResilientSparkSession.__init__ fails to bring up a replacement py4j gateway (helpers/spark_tools.py:95 from test.py:77). This PR changes ThrottlerConstraint.h and its gtest, nothing in the Spark helper or the integration harness. #113430 (ours, merged 2026-08-05T14:48:42Z) - this build predates it
Sync - CH Inc sync (private, not actionable by me)

All 175 check-runs completed (149 success, 23 skipped, 1 failure at the time the workflow finished);
Config Workflow and Finish Workflow both success. The Build (arm_tidy) failure that was on the
previous head 0bc34417a73b is fixed and green here.

Fix presence was established per build, not from the merge date: gh api compare/<merge commit of 113430>...<this head> reports status=diverged, behind_by=331, so the fix is genuinely ABSENT from
this build and the failure is expected here. Nothing needs picking up onto this branch for it - a
later CI run on a head that includes it will carry the fix.

Session id: cron:our-pr-ci-monitor:20260807-130000

@serxa

serxa commented Aug 31, 2026

Copy link
Copy Markdown
Member

@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

@groeneai

Copy link
Copy Markdown
Collaborator Author

Partially, and the part that reuses cleanly is the bound itself.

Both headers postdate this PR (saturatedDuration.h in #106961, merged 2026-08-21; saturatedWaitDuration.h in #112088, merged 2026-08-25), which is why it re-derives everything locally.

What does not fit: every helper in either header is template <std::integral T>. The delay here arrives as the Float64 quotient -tokens / max_speed * 1e9, and narrowing an out-of-range Float64 is itself the undefined behavior, so no existing signature applies. That is the "not quite", and it is why the range check has to stay, as you say.

What does fit: MAX_WAIT_MILLISECONDS is half the Int64 nanosecond range precisely so the other half covers steady_clock::now() and now() + duration cannot wrap. That is exactly the requirement at :178, and it is what boundedDelay re-derives as max_duration - elapsed. One Float64 sibling covers both statements:

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));
}

ThrottlerConstraint then loses boundedDelay entirely, the bound stops depending on now, and the same constant serves as the accumulator ceiling, so the call site is just

auto delay_ns = saturatedWaitNanoseconds(-tokens / max_speed * 1e9);

Measured rather than argued: MAX_WAIT_NANOSECONDS is 4611686018427000000 ns, 146.2 years, leaving the same headroom for now(); at the largest start my tests use, 2^62 ns, now + delay lands 387903 ns below INT64_MAX. Built with -fsanitize=undefined -fno-sanitize-recover=all, each of the three unguarded statements reports and aborts (1e+39 is outside the range of representable values of type 'long' for the narrowing); with the helper, zero reports.

Two things cannot move into the shared header. throttling_duration accumulates for the node lifetime, so no per-delay bound bounds the sum and the saturating add stays. And the give-back in cancelPostponement is the double-count fix, not an overflow guard.

The one consequence is that this PR has to merge master to see the header. git merge-tree reports 0 conflicts and the two files it currently changes are byte-identical to master, so the merge is mechanical. I will push it together with the simplification.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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. MAX_WAIT_MILLISECONDS is half the Int64 nanosecond range, about 146 years. boundedDelay bounds by the range the clock actually has left instead. Substituting the first for the second changes throttling_duration, which is what system.scheduler.throttling_us reports, and that is the rule saturatedWaitDuration.h already states one function further down: "The wait bound must not be used here, it would change the value the server acts on and reports."

Sharing one bound between a single delay and the accumulated total breaks the give-back. A clamped delay then lands exactly on the ceiling, cancelPostponement reads that equality as saturation and skips the give-back, so max_queries_per_second = 1e-30 followed by dropping the limit left throttling_us at 4611686018427000000 where 0 is correct, permanently. Recording the counted part exactly does fix it, but it costs a member and a second arithmetic case, so that file ends up longer than it started.

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: Expected: (consumed_cost[name]) >= (value - error), actual: 0 vs 1. The existing arm only reaches the ceiling because the first delay is exact and only the second is clamped.

So the reusable part is smaller than it looked. Every helper in both headers is template <std::integral T>, and what this site needs is a narrowing clamp against a caller-supplied bound, which is what boundedDelay already is in four lines. The branch is unchanged and I did not merge master into it.

If you would still rather have the shared helper, or a different shape for that function, tell me which and I will push it.

@serxa

serxa commented Sep 1, 2026 •

Copy link
Copy Markdown
Member

@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 system.scheduler. This is a system table for debugging only; we can change its behavior almost any way we want.

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.
@groeneai groeneai changed the title Fix undefined behavior and a double-counted metric in the workload throttler Fix undefined behavior in the workload throttler's postponement delay Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Done in ce4757d. The delay saturates at one year now, applied before the narrowing since casting the out-of-range Float64 is the undefined behavior itself. boundedDelay, postponed_until and the now-derived bound are gone: the header is +17/-2 where it was +52/-6, and there are 3 new test arms instead of 5.

Two things I measured rather than assumed:

  • The fixed bound covers the addition as well. INT64_MAX minus one year is 9191836036854775807 ns, so now + delay stays in range for any steady_clock less than 291 years past its epoch.
  • The accumulated total still needs a guard of its own: only 292 one-year delays fit in the Int64 nanosecond range, and a pending delay is counted again on every re-postponement, so about 300 ALTER WORKLOADs reach the ceiling. That is one line, throttling_duration += std::min(delay_ns, nanoseconds::max() - throttling_duration). Checked standalone under -fsanitize=undefined -fno-sanitize-recover=all: the bounded form is silent, and each of the three unbounded controls aborts (1e+39 is outside the range of representable values of type 'long', then two signed integer overflow).

On the metric, I dropped the accounting commit, since system.scheduler.throttling_us is its only consumer. That leaves the pre-existing double count in place, so on a throttled node the counter can end up pinned at that ceiling after a few hundred ALTER WORKLOADs. The commit is written and tested if you would rather keep the counter accurate; your call.

9 gtests pass, and removing either guard reddens a new arm while all 6 pre-existing arms stay green.

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ce4757dcfcd17b152b1521791d3af7ee4a20a722

CI is fully finished on this head. 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
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

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

The fix for the Bugfix validation submodule-state refusal noted in the ledger above is open as #117948, which stops the harness reporting a base-branch submodule move as a validation failure.

@clickhouse-gh clickhouse-gh Bot added the comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

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.

@serxa serxa self-assigned this Oct 2, 2026
@serxa

serxa commented Oct 2, 2026

Copy link
Copy Markdown
Member

@groeneai let's merge master and make sure CI is green

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master in 98f7039, no conflicts, and the PR diff is unchanged. The merge also brings in #117284 and #117948, which fix the two failures in the last ledger. The scheduler unit tests pass locally on the merged tree. I'll follow CI here.

@serxa
serxa added this pull request to the merge queue Oct 8, 2026
Merged via the queue into ClickHouse:master with commit 2327fc6 Oct 9, 2026
149 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Oct 9, 2026
cursor Bot pushed a commit to fneves/ClickHouse that referenced this pull request Oct 9, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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