Skip to content

Fix a hang of remote() queries in a CPU workload with fewer slots than max_threads - #126512

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-cpu-lease-all-parked-keeps-slots
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-cpu-lease-all-parked-keeps-slots

Conversation

@groeneai

@groeneai groeneai commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117711
Related: #123640

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 hang of a remote() query whose shard runs on the same server in the same CPU workload when the workload's max_concurrent_threads is lower than the query's max_threads. The coordinator's idle threads kept every CPU slot, so the shard never got one and the query ended only at max_execution_time.

Description

On 26.10.2.9, with CREATE RESOURCE cpu (MASTER THREAD, WORKER THREAD) and a workload w1 with max_concurrent_threads = 1, SELECT number % 10 AS k, count() FROM remote('127.0.0.2', numbers(20000000)) GROUP BY k SETTINGS workload = 'w1', max_threads = 2 never finishes (5/5 TIMEOUT_EXCEEDED). Master still hangs the same way with cpu_slot_parking on.

CPULeaseAllocation::effectiveMaxSlots() is current_max_slots - parked_count, where current_max_slots is the number of threads the query wants. When the query holds fewer slots than that and all its threads park, allocated equals effectiveMaxSlots(), so parkLease gives nothing back. No thread runs, so nothing reports consumption or uses the slots, while the shard waits in renew for one of them.

Now effectiveMaxSlots() is 0 while no thread is running or preempted and at least one is parked, so the last park returns every slot. grantImpl also returns a grant that arrives in that state (a worker that timed out in preemption leaves a request pending), through the surplus loop of parkLease, moved to finishSurplusRequests. This is the parking counterpart of #123640.

Tests: a stateless test (times out at 60 s before the change, 50/50 after) and a unit test for the late grant; each fails without its half of the change. A park-heavy local query in capped and wide workloads has the same median time before and after (177 vs 178 ms, 102 vs 103 ms). With cpu_slot_parking = 0 the query still hangs, as before; async_socket_for_remote = 0 is fixed by #126524.

This touches the same parkLease loop as #126336; whichever lands second moves its body into the helper.

🤖 Generated with Claude Code


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

@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; 3 rounds, 2 findings) plus my own cold review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The give-back in grantImpl ran in any state, so a grant after a setMax shrink would reclaim granted slots (ISlotControl.h:114-115) AGREE, fixed @ 1f9ed2d Limited to the all-parked state with allParked(). Not reachable from a query today (production setMax only grows).
2 ⚠️ The stateless test checks only result rows, which are the same without CPU scheduling AGREE, fixed @ c7c4094 The test also checks ProfileEvents['ConcurrencyControlParks'] > 0 of the query and pins async_socket_for_remote = 1.
3 💡 After the last park gives every slot back, the first unparked thread runs on credit until its new request is granted AGREE, noted Same as master whenever a query holds every slot it wants; requested_ns not being lowered is the existing TODO.
4 💡 A gtest beside the stateless test AGREE, noted Only coverage of the grantImpl half (the late grant after a preemption timeout cannot be ordered from SQL).
5 💡 No test for a grant after a setMax shrink AGREE, noted No production caller shrinks; kept out to limit test volume.
6 💡 cpu_slot_parking = 0 and async_socket_for_remote = 0 still hang AGREE, noted Out of scope: without parking idle threads keep their slots by design; the synchronous remote read is not a park site.

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. SELECT number % 10 AS k, count() FROM remote('127.0.0.2', numbers(20000000)) GROUP BY k SETTINGS workload = 'w1', max_threads = 2, max_execution_time = 5 in a workload with max_concurrent_threads = 1: 5/5 TIMEOUT_EXCEEDED on master before the change, 5/5 on 26.10.2.9. The new stateless test fails 6/6 at 60 s before the change.
b Root cause explained? effectiveMaxSlots() = current_max_slots - parked_count. With fewer granted slots than wanted threads, parking every thread leaves allocated == effectiveMaxSlots(), so parkLease keeps all slots; no thread runs, so nothing consumes or returns them, and the same-server shard waits in renew for one of them.
c Fix matches root cause? Yes. The demand formula is 0 while every thread is parked (none running or preempted), so the last park returns every slot; grantImpl returns a grant that arrives in that state. No timeouts or test-only knobs.
d Test intent preserved / new tests added? New stateless test 05406_cpu_lease_parked_initiator_remote (the user-visible hang; it also checks ConcurrencyControlParks > 0 of the query, so a run without CPU scheduling cannot pass) and a unit test for the late grant after a preemption timeout, which SQL cannot order.
e Both directions demonstrated? Stateless test: 6/6 FAIL before, 50/50 randomized + forced use_hedged_requests 0/1 PASS after; with use_concurrency_control = 0 it fails on the parks check only. Unit test: FAIL without the grantImpl call and without the effectiveMaxSlots change, PASS 20/20 with both.
f Fix is general across code paths? Every reader of effectiveMaxSlots() checked (parkLease, unparkLease, setMax, schedule, grantImpl); the non-park entries into the all-parked state (preemption timeout, a thread exiting) are covered by the grantImpl give-back. Other slot allocations do not park.
g Fix generalizes across inputs (params/datatypes/wrappers)? 1 and 2 shards, 127.0.0.2 and 127.0.0.1 with prefer_localhost_replica = 0, max_threads 2/8, workload limits 1/4/64: no timeouts after the change. cpu_slot_parking = 0 and async_socket_for_remote = 0 still hang, as before (no park happens there). Data types N/A.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; behaviour differs only while every thread of a query is parked.
i Invariants and contracts preserved? granted == allocated - leased kept (the moved loop is unchanged), allocated >= 0, requests finished in order, all paths under the allocation mutex. Unpark re-requests after leaving the state, as in the uncapped case. Scheduler integration tests 20/20, scheduler unit tests 227/227.

Session id: cron:clickhouse-impl-self-slot-57:20261017-164200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @serxa, could you review this? With cpu_slot_parking on, a query that holds fewer CPU slots than max_threads keeps all of them when every thread parks (allocated == current_max_slots - parked_count), so a remote() shard on the same server in the same workload waits forever; now effectiveMaxSlots() is 0 while every thread is parked, and a grant that arrives in that state is given back.

@clickhouse-gh

clickhouse-gh Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f0fa18a]

Summary: ✅


AI Review

Summary

The PR returns CPU slots when every thread of a CPULeaseAllocation is parked and returns late grants received in that state, preventing same-server remote queries from waiting on slots retained by their idle initiator. Reviewed the full diff at f0fa18a4bd119e9cf88480b11985b09dbcddf448, surrounding scheduler and executor lifecycles, both regression tests, and all prior discussion. No actionable findings. Tests were not run locally; regression evidence is provided in the PR description and discussion.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 17, 2026
@serxa serxa self-assigned this Oct 17, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... label Oct 17, 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 - ed9e688

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
Stateless tests (amd_tsan, s3 storage, targeted) / 03821_drop_workload_during_query_race flaky, not from this PR: the test prints the stack trace of an expected error from a query racing DROP WORKLOAD, here the RESOURCE_ACCESS_DENIED that CPULeaseAllocation::renew throws when the CPU resource request failed (master code, the same stack failed on one other PR); the same failure is on 65 other PRs and twice on master since 2026-10-16 #126345 (mine, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log not from this PR: the upgraded server logs two errors for ON CLUSTER entries left in the previous release's DDL queue (TABLE_ALREADY_EXISTS for test_5.ddl_test_for_opentelemetry, and a cancelled BACKUP of 02907), the replayed-DDL-backlog class #125562 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #126345 and #125562 (the owners of the rows above)

The only other FAIL rows on this head are the Config Workflow / Pre Hooks and Finish Workflow / Post Hooks rows of the two earlier attempts, which stopped on the missing can be tested label.

Session id: cron:our-pr-ci-monitor:20261018-073006

@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 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 17, 2026
@serxa

serxa commented Nov 17, 2026

Copy link
Copy Markdown
Member

@groeneai, let's update this PR. A few other fixes have been merged around the existing algorithm. Take a look to see if the problem is still there, and if so, how to fix it properly

groeneai and others added 4 commits November 17, 2026 15:20
`effectiveMaxSlots()` is `current_max_slots - parked_count`, and
`current_max_slots` is the executor's desired thread count. When the
workload grants a query fewer slots than it wants (`max_concurrent_threads`
below `max_threads`), parking all of its threads leaves `allocated` equal to
`effectiveMaxSlots()`, so `parkLease` keeps every slot. With no running
thread nothing reports consumption or spawns a thread, so the slots stay
idle. A `remote()` query whose shard runs on the same server under the same
workload then hangs: the coordinator waits for the shard, and the shard's
thread waits in `renew` for a slot the coordinator holds.

Make `effectiveMaxSlots()` zero while no thread is running or preempted and
at least one is parked, so the last park gives back every held slot. A
worker that times out in preemption while the others are parked enters the
same state with a request still pending; `grantImpl` now returns a grant
that arrives then (the surplus loop of `parkLease` is moved to
`finishSurplusRequests` and called from both). This is the parking
counterpart of ClickHouse#123640.

Tests: a stateless test with a one-slot workload and a loopback `remote()`
GROUP BY (times out at 60 s without the change), and a unit test for the
late grant after a preemption timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A grant that arrives in any other state is kept, so a `setMax` shrink still does not reclaim granted slots.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The result rows are the same without CPU scheduling, so the test also checks `ConcurrencyControlParks` of the query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove two comments that restate the code below them (the allParked() doc and the grantImpl give-back note).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai
groeneai force-pushed the fix-cpu-lease-all-parked-keeps-slots branch from ed9e688 to f0fa18a Compare November 17, 2026 15:44
@groeneai

Copy link
Copy Markdown
Collaborator Author

I rebased this on master (now f0fa18a, the change itself is the same) and re-measured: the problem is still there.

  • Official master build 26.11.1.2575 (ab23bdd4e08b, has Start executor threads for CPU slots granted after the request #125901, Choose the effective max_threads once per query #125946 and Fix a hang of a query that lazily loads a dictionary in a CPU workload #130133), 1-slot workload: SELECT number % 10 AS k, count() FROM remote('127.0.0.2', numbers(20000000)) GROUP BY k SETTINGS workload = 'w1', max_threads = 2, max_execution_time = 10 hit the limit in 4/10 runs, 5/10 with the default max_threads, and the 2-shard query from the report (4-slot workload, max_threads = 8) in 1/10. The same query in a 64-slot workload: 0/10.
  • Debug builds, the same three queries, 10 runs each: master 9b107508c683 hit the limit in 21/30, this PR in 0/30 (0.1 s, two shards 0.4-0.5 s). The stateless test fails at 60 s on master and passes 20/20 here with randomized settings.
  • While stuck, the shard's executor thread waits in CPULeaseAllocation::renew -> waitForGrant, the initiator's executor thread is parked in ExecutionThreadContext::wait, and its pulling thread is in PollingQueue::getTask.

Why the merged changes don't reach it: CPULeaseAllocation has not changed since October apart from [[nodiscard]], so effectiveMaxSlots() is still current_max_slots - parked_count, and the setMax target from #125901 only grows. A query that got fewer slots than it asked for and parks all its threads has allocated == effectiveMaxSlots(), so parkLease keeps every slot. They are used only when a parked thread comes back, and here that thread waits for the shard, which waits for one of those slots.

How to fix it: I think the allocation is the right layer, with the rule "keep a slot only while a thread of the query can use it now". A running thread can (it spawns a thread for a granted slot after its task), and so can a preempted one (resumePreempted). With every thread parked none can, so effectiveMaxSlots() is 0 in that state, and a grant that arrives in it is given back (a worker that timed out in preemption can leave a request pending). The cost is that the next unpark requests a slot again instead of finding one.

This conflicts with #126336 in the parkLease surplus loop: whichever merges second moves finishKeepingEarliest into finishSurplusRequests. I'll resolve it here if #126336 lands first.

@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f0fa18a4b with master 204d73c05 (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, 15 s compile time in total, 8 of them have a recent master baseline.

Job report

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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants