Skip to content

Budget-aware cost for CPU lease requests, so parking does not extend a slot - #126336

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-cpu-lease-budget-aware-request-cost
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-cpu-lease-budget-aware-request-cost

Conversation

@groeneai

@groeneai groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #126133

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...

Description

Implements the proposal from #126133. A query whose CPU lease parked N times kept its CPU slot for about N x cpu_slot_quantum_ns of CPU, so other workloads waited seconds. A park gave a slot back unconsumed while requested_ns kept its cost, and the unpark asked for a full quantum on top. Every request expired at requested_ns, so each park/unpark moved the next expiry one quantum further.

Now each ResourceRequest is sized from the lease state:

  • it expires one quantum after the latest-expiring held slot (after consumed_ns when none is held), so the horizon is one quantum per acquired slot and a partially consumed slot is not paid twice;
  • it costs only what the budget (requested_ns - consumed_ns) does not cover yet, down to 1 ns.

Preemption (consumed_ns >= requested_ns) is unchanged. A park now gives back the latest expiry instead of the earliest, and a cancelled request's cost leaves requested_ns, as it was never granted. A query that never parks gets the same costs and expiries. While threads stay parked, the budget they gave back is still credit for the running thread (at most one quantum per parked thread), but no longer holds a slot.

Not for changelog: parking (#117711) is unreleased.

Validation: the issue's reproducer, added to test_scheduler_cpu_parking, fails on master 6/6 (~490 parks, the other workload waits 4.6-4.8 s) and passes 50/50 with the fix (up to 31 ms). Its threshold is 2 s, not 0.5 s: with the fix that wait follows the other query's CPU time (~0.4 s on ASan). A gtest covers the multi-thread park and the cancel; it fails on master and with either park-side change reverted. Giving a slot back walks at most allocated requests, ~130 ns per park at 256 slots. Existing scheduler tests pass.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 16, 2026 16:06
A query that parked its CPU lease N times kept its slot for about N quanta
of CPU without renewing it, so queries of other workloads waited for seconds
(issue ClickHouse#126133). `parkLease` gave a not yet consumed slot back (it finished
the oldest request early or cancelled the pending one) without touching
`requested_ns`, and `unparkLease` -> `schedule` asked for a full quantum on
top. The new request expired at the new, higher `requested_ns`, so every
park/unpark cycle moved the expiry of the next slot one quantum further.

Implement the proposal from the issue: a new request expires one quantum
after the latest held slot (or after the current consumption when none is
held), and costs only the part of that horizon the budget
(`requested_ns - consumed_ns`) does not cover yet, down to 1 ns. The
preemption check `consumed_ns >= requested_ns` is unchanged.

Two park-side changes keep the budget exact:
- a park still finishes the oldest request, but gives back the latest
  expiry, so the remaining slots keep the earliest ones;
- the cost of a request cancelled before the scheduler processed it leaves
  `requested_ns`, because it was never granted.

For a query that never parks, the expiry and the cost of every request are
the same as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`test_parked_query_still_renews_cpu_slot` discarded every exception of
query `a`. If `a` stopped early for another reason, its slot was free,
query `b` waited only a few ms and the test passed without checking
that the slot is renewed.

Record the errors of `a`, require `a` to still be running when `b`
finishes, and accept only the cancellation caused by the test's own
`KILL QUERY`.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; round 1: 2 findings, round 2 on the fix: 0) plus my own cold review (nits only).

# Sev Finding Verdict Evidence / action
1 ⚠️ The regression test swallowed any exception of query a, so an early stop of a would also give a short wait for b AGREE, fixed in 4f3abe1 a must still be running when b finishes, and its only error must be the test's own kill; killing a before b now fails the test
2 ⚠️ Returning a parked slot walks all held requests under the allocation mutex AGREE, measured, no change ~130 ns per park at 256 held slots; under 256-thread contention the mutex handoff dominates and the walk is not slower than an O(1) step. Moving head back is not safe: a pending request can occupy *head in that loop
3 💡 Budget given back by parked threads is still credit for the running thread AGREE Stated in the description; the preemption check is unchanged on purpose
4 💡 The integration test bound is an absolute 2 s Noted With the fix the wait follows the other query's CPU (0.2-0.45 s on the sanitizer builds); master waits 4.6-4.8 s

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The gtest ParkingDoesNotExtendSlotLease fails on master every run (the master burns its 15-quantum cap before another query gets a slot); the issue's reproducer fails 6/6 on master (other workload waits 4.6-4.8 s).
b Root cause explained? A park gives a slot back without lowering requested_ns, the unpark asks for a full quantum on top, and each request expired at requested_ns, so every park/unpark moved the next expiry one quantum further.
c Fix matches root cause? Yes. The expiry no longer follows requested_ns: a new request expires one quantum after the latest held slot and costs only what the budget does not cover. The park side gives back the latest expiry and undoes a cancelled request's cost.
d Test intent preserved / new tests added? Yes. The issue's reproducer is added to test_scheduler_cpu_parking; one gtest covers the multi-thread park and the cancel, which the single-thread reproducer cannot reach.
e Both directions demonstrated? Yes. Both tests fail on master and pass with the fix (gtest 50/50, integration test 50/50); the gtest also fails with either park-side change reverted.
f Fix is general across code paths? Yes. All six schedule() callers use the one formula; both early-release paths of parkLease (finish, cancel) are fixed. Only CPULeaseAllocation overrides ISlotLease::park.
g Fix generalizes across inputs (params/datatypes/wrappers)? Single- and multi-thread queries, shared master/worker resource (the only mode with parking); a query that never parks gets the same cost and expiry as before. Minimal cost is 1 ns, accepted by every scheduler node.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format; internal accounting of a feature that is only on master.
i Invariants and contracts preserved? Expiries stay non-decreasing along the chain, requested_ns stays at or above every live request's expiry (the finishConsumedRequests assertion relies on it), and the pending request is never touched by the park; all under the allocation mutex.

Session id: cron:clickhouse-impl-slot-6:20261016-152000

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a0888fa]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_release, oracle) FAIL
AST fuzzer oracle mismatch FAIL cidb

AI Review

Summary

The PR makes CPULeaseAllocation reuse unused CPU budget across parking cycles, preserve the earliest held-slot expiries, and subtract cancelled request costs. This prevents repeated parking from delaying CPU-slot renewal and starving competing workloads. No unresolved findings remain at a0888fa749a7dc6e9b6b5a42eac3c22d02cfa3f4; the earlier test teardown finding is fixed. The focused regression tests and reported before/after measurements support the change. Validation here consisted of source and discussion review plus inspection of the CI reports; no local build or tests were run.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... labels Oct 16, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4f3abe1

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

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, 3/4) / test_backward_compatibility/test_custom_s3_disk_remote_url_allow_hosts.py (both tests) master break since 2026-10-16 09:59Z, not from this PR (it changes only the CPU scheduler and its tests): the floating 26.8 old-server image moved to a release that checks SQL disks against remote_url_allow_hosts, so the setup CREATE fails with Code: 491; the tested merge tree f71cb5fc726c was created before the fix merged #126289 (mine, merged)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05024_autopr_plan_based_parallel_replicas flaky (7 of 73 reruns with the same settings), not from this PR: 05024_autopr_plan_based_query_1 reports pr_used 0 instead of 1; the same diff is on 12 PRs and master in 30 days #125544 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the rows above #126289 and #125544 (the owners of the first two rows)

Session id: cron:our-pr-ci-monitor:20261017-083009

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

serxa commented Oct 17, 2026

Copy link
Copy Markdown
Member

@groeneai please do more extensive performance testing against master and against master w/o cpu slot parking. Focus on use cases that you suspect can be impacted by parking you can also add the new performance test specifically for this corner case because it's quite important to make sure that scheduling-related stuff does not impact query performance as much as we can in any kind of load. Specifically, it's important for workloads with concurrent query execution, with mixed query types, and other things that look like a production workload and not just benchmarking.

@serxa

serxa commented Oct 17, 2026

Copy link
Copy Markdown
Member

These tests can be done in a separate pull request if necessary.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'm benchmarking this PR against master and against master with cpu_slot_parking = 0 under concurrent mixed loads: short and long queries in competing workloads, queries whose executor threads idle and park a lot, throttled reads, and high-QPS short queries. I'll post the numbers here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I benchmarked this PR (4f3abe1) against its master base (67e362e), each with cpu_slot_parking on and off. Setup: RelWithDebInfo builds without LTO, one server on 16 cores / 32 hyperthreads, 10 ms quantum, CREATE RESOURCE cpu (MASTER THREAD, WORKER THREAD), root workload with max_concurrent_threads = 16, a 60M-row hits-like MergeTree table. Every load ran 3 times (loads 1 and 3: 5 times, fixed work) in rotated order. Parks come from executor idle waits, max_local_read_bandwidth throttling and cluster() async socket waits.

Load master master, parking off PR PR, parking off
1. Mixed: 13 query types (aggregations, JOIN, window, LIKE scan, throttled read, cluster()), 8 clients x max_threads = 8, ~10 parks and ~23 preemptions per query: QPS 14.05 14.09 14.15 14.17
2. Sibling workloads: interactive (4 clients) / heavy + throttled + cluster() (4 clients, max_threads = 16) / INSERT SELECT loop: interactive QPS, p99 501, 41 ms 504, 41 ms 499, 41 ms 506, 41 ms
2. Same run, heavy workload: QPS, p99 5.2, 2.18 s 4.5, 2.48 s 4.9, 2.11 s 4.8, 2.30 s
3. Short queries, 32 clients x max_threads = 4 (they never park): QPS 9195 9105 9117 9280
4. max_threads = 32 over 16 slots, 4 clients: per-query-type median latency vs master 1 0.98-1.02 0.98-1.02 0.98-0.99
5. One client, scheduler not saturated: QPS, p99 6.2, 327 ms 6.4, 333 ms 6.1, 327 ms 6.1, 328 ms
6. Sub-workload with max_concurrent_threads = 2: throttled-read-then-CPU queries (2 clients, ~1700-2100 parks each) and short CPU queries (2 clients) in sibling workloads. Short queries: max, p99.9, count above 1 s 2.7-2.9 s, 345 ms, 15 0.18-0.21 s, 151 ms, 0 0.20-0.32 s, 161 ms, 0 0.18-0.26 s, 156 ms, 0
6. Same run, short queries completed (3 x 40 s) 25221 25806 28785 25431
6. Same run, throttled queries completed per 40 s, p99 24, 3.9 s 18-20, 12.2 s 24, 3.9 s 17-21, 17.2 s

Loads 1-5 show no regression: throughput within 1%, per-query medians within 2%, interactive p99 unchanged. Load 6 is the corner case in a production shape: on master the short queries stall for up to 2.9 s behind parked credit; with the PR the worst is 0.32 s while the throttled queries keep the throughput parking gives them (24 per 40 s, vs 17-21 with parking off).

One trap for anyone repeating this: most of the PR binary's page-cache pages first sat on another NUMA node than the server, which alone made it 10% slower on load 3, with parking off too. The runs above are after migrating both binaries' pages to the server's node.

The CI performance tests run one query at a time, so they cannot reproduce load 6; the integration test in this PR covers it. I'll add a performance test for park-heavy single queries under a CPU workload (idle workers in a window step, throttled reads, cluster() waits) in a separate PR, so CI keeps measuring the scheduler overhead.

Load 6 queries

Throttled reads use max_local_read_bandwidth = 4000000, max_read_buffer_size_local_fs = 4096, min_bytes_to_use_direct_io = 1, local_filesystem_read_method = 'pread'.

-- workload small_io, max_threads = 2
SELECT count() FROM numbers(200000000) WHERE cityHash64(number) NOT IN (SELECT cityHash64(URL) FROM hits WHERE CounterID BETWEEN 2000 AND 2100);
SELECT sum(cityHash64(URL)) FROM hits WHERE CounterID BETWEEN 2000 AND 2400;
-- workload small_cpu, max_threads = 2
SELECT count() FROM numbers(10000000) WHERE cityHash64(number) % 3 = 0;
SELECT sum(cityHash64(number)) FROM numbers(5000000);
SELECT * FROM hits WHERE CounterID = 42 ORDER BY EventTime DESC LIMIT 10;

@groeneai

Copy link
Copy Markdown
Collaborator Author

The performance test is in #126515. A correction to my earlier comment: a shell item can run a concurrent case, so the test includes one like load 6 (a CPU query sharing a slot with a sibling workload's query that parks), and this PR makes it 30% faster. A remote() query in a workload with fewer slots than max_threads hung on master, so that shape is not in the test; the fix is #126512.

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 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 Nov 16, 2026

@serxa serxa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is good enough. Lets resolve conflicts. Ping me when its ready to be merged

…t-aware-request-cost

Resolve the conflict in CPULeaseAllocation.h: keep master's [[nodiscard]]
on the RequestChain getters and add it to the two getters this branch adds.

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

Copy link
Copy Markdown
Collaborator Author

Merged master in 75415bd. The only conflict was master's [[nodiscard]] sweep in CPULeaseAllocation.h; the two getters this PR adds now have it too. Scheduler gtests and test_scheduler_cpu_parking pass on the merged tree. I'll ping you when CI on this head is finished.

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a0888fa74 with master 463f45f5f (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, 10 s compile time in total, 8 of them have a recent master baseline.

Job report

…sNotExtendSlotLease

`CPULeaseAllocation::release` computes the last consumption report from
`CLOCK_THREAD_CPUTIME_ID` of the calling thread minus `last_report_ns`, which
`startConsumption`/`renew` took on `master_thread`. The test destroyed the
master lease on the gtest thread, so the report mixed two thread clocks:
measured with gdb, it charged 374.5 ms of the gtest thread's CPU to the query
(thread_time_ns 385594101 vs last_report_ns 11052820), and it would trip
`chassert(thread_time_ns >= lease.last_report_ns)` if the gtest thread had
used less CPU than `master_thread`.

Reset `master_slot` inside the async task after its last renewal. The release
then reports 1071 ns on the same clock. The later assertions are unaffected:
`downscale` does not cancel the pending renewal and `effectiveMaxSlots` does not
depend on the master lease. Mutation (drop the cancelled-cost undo in
`parkLease`) and master's `CPULeaseAllocation` still fail the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review approves this commit, see the AI Review comment.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@serxa CI on 68b9887 is finished and green. Since your approval the only changes are the master merge (75415bd) and a one-line gtest teardown fix for the clickhouse-gh finding (68b9887). Ready to merge from my side.

@serxa
serxa added this pull request to the merge queue Nov 19, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 19, 2026
groeneai and others added 2 commits November 20, 2026 01:38
…speed

The merge queue dropped this PR after the test saw `parks = 0`
(MergeQueueCI, `Integration tests (amd_binary, targeted)`, sha 59fd0a7).
Query `a` read its set with O_DIRECT 4 KiB `pread`s, so the read throttler
only sleeps (and parks the CPU lease) when the device serves those reads
faster than `max_local_read_bandwidth` (1 MB/s, about 250 IOPS). On that
runner the 740 reads took 6.65 s (DiskReadElapsedMicroseconds, OSReadBytes
3.03 MB) and ThrottlerSleepMicroseconds was 0.

Without O_DIRECT, `pread` skips the block-device throttler for page cache
hits, so the test switches to `local_filesystem_read_method = 'read'`, which
throttles every read. The just-written part is read from the page cache and
the throttler sleeps regardless of the device.

Measured locally with the node container capped at 100 read IOPS on its data
device while query `a` runs: the old settings give 0 parks (the CI failure),
the new ones 491-492 parks with OSReadBytes 0. At 50 IOPS: 324-492 parks,
pass 3/3. Uncapped: whole module 50/50. Master's CPULeaseAllocation still
fails the test (b waits 4.36-4.69 s with 491 parks), so it still covers the bug.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test checked how long a slot lives after many parks, but not what each
unpark asks the scheduler for. A `schedule` that kept the new expiry but
charged a full quantum per request passed it, while `max_cpus` and fair
scheduling would still bill a parking query one quantum per park.

Count the requests and the cost the queue dequeues during the 20
zero-consumption park/unpark rounds: 20 requests, less than one quantum in
total. With `cost = settings.quantum_ns` in `schedule` the test fails 3/3 on
exactly this check (200000000 vs 10000000) and on nothing else; with the
PR's `schedule` it passes 20/20, and `Scheduler*` passes 174/174.

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

Copy link
Copy Markdown
Collaborator Author

The merge queue removed this PR because test_parked_query_still_renews_cpu_slot saw 0 parks (report). Its O_DIRECT reads park only when the disk serves 4 KiB reads faster than the 1 MB/s throttle, and that runner did 740 reads in 6.65 s, so the throttler never slept.

  • f2e61f5 reads with local_filesystem_read_method = 'read', which throttles page cache hits too. Locally, with the node capped at 100 read IOPS, the old settings give 0 parks and the new ones 491. Master's code still fails the test (b waits 4.4-4.7 s).
  • a0888fa adds a gtest check that the unparks reuse the budget instead of asking for a quantum each.

It can be queued again once CI on a0888fa is green.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a0888fa

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
AST fuzzer (amd_release, oracle) / AST fuzzer oracle mismatch wrong result, not from this PR (it changes only CPULeaseAllocation and its tests): the Subquery wrap oracle changed the qualified join columns of SELECT t1.a, a, t2.a FROM t1 FULL OUTER JOIN t2 USING (a), the shape of issue #118986 #107127 (mine, open)
PR / Mergeable Check praktika rollups of the row above #107127 (the owner above)

Session id: cron:our-pr-ci-monitor:20261120-050026

This branch has not been deployed

No deployments
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... pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

parkLease never lowers requested_ns; competing workloads starve for seconds

3 participants