Skip to content

Fix a hang of remote() queries with async_socket_for_remote = 0 in a CPU workload - #126524

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:cpu-lease-park-sync-remote-read
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:cpu-lease-park-sync-remote-read

Conversation

@groeneai

@groeneai groeneai commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117711
Related: #126512
Related: #126336

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 with async_socket_for_remote = 0 whose shard runs on the same server in the same CPU workload. The thread waiting for the shard's data kept its 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 = 1, async_socket_for_remote = 0 never finishes (3/3 TIMEOUT_EXCEEDED). Master hangs the same way, hedged or not, also for a two-replica parallel_replicas_mode = 'sampling_key' read.

#117711 parks the CPU lease while the asynchronous remote read waits in PollingQueue, and lists the synchronous path as not covered. There, RemoteSource blocks in RemoteQueryExecutor::read -> connections->receivePacket() with the lease running, so it keeps the slot while the shard on the same server waits for it in CPULeaseAllocation::renew.

Now only that call runs in a CPULeaseParkGuard. No RemoteQueryExecutor or connection mutex is held there, so parking adds no lock-order edge; the finish() drain and the synchronous sendQuery hold was_cancelled_mutex and stay unparked. The guard also covers the call's CPU work (decoding; on a hedged failover, resending external tables), so a workload can run one thread per synchronous remote source above its limit, the over-subscription #117711 already documents.

A synchronous read of several shards asks for one slot per source, so it also needs #126512: two shards hang with either PR alone and finish with both.

It also needs #126336 first: parks keep their returned quanta in requested_ns and unparks request new ones (#126133), and this site parks once per packet, so max_cpus stops applying after the read (debug build, 1 thread, max_cpus = 0.1: 0.72 s, 0 preemptions; master 7.5 s, 66; with #126336 8 s, 70).

Tests: a stateless test (times out at 60 s before, 50/50 randomized runs after). Parks equal unparks on the initiator. A 300M-row synchronous remote read keeps its median time (5392/5417/5398 vs 5400/5390/5405 ms: no workload, 8-slot workload non-hedged and hedged).

🤖 Generated with Claude Code


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

With `async_socket_for_remote = 0`, `RemoteSource` blocks inside
`RemoteQueryExecutor::read` -> `connections->receivePacket()` while the
shard computes. Nothing parked the thread's CPU lease there (the async
path waits in `PollingQueue`, which parks), so the initiator kept its CPU
slot. When the shard runs on the same server in the same CPU workload
and the initiator holds every slot of that workload, the shard waits in
`CPULeaseAllocation::renew` for that slot forever, and the query ends
only at `max_execution_time` (or `receive_timeout`).

Put only the `receivePacket` call in a `CPULeaseParkGuard`. At that point
no `RemoteQueryExecutor` or connection mutex is held (`was_cancelled_mutex`
is released just above, `cancel_mutex` is taken inside `receivePacket`),
so park/unpark add no lock-order edge. The `finish()` drain and the
synchronous `sendQuery` run under `was_cancelled_mutex` and stay unparked:
parking under it closes a cycle with `ExecutorTasks::mutex` (via
`processParallelReplicaPacketIfAny`) and the lease mutex (via `on_resume`).

The guard also covers decoding the packet inside `receivePacket`, so a
workload can briefly run one thread per synchronous remote source above
its limit, the over-subscription that ClickHouse#117711 already documents.

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; 2 findings) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ❌ A synchronous read of several shards still hangs without the allocator fix DISAGREE In that hang the initiator is parked in receivePacket; the slot is kept by CPULeaseAllocation::effectiveMaxSlots, which this PR does not touch and which hangs the asynchronous path the same way. Fixed by #126512: two shards hang with either PR alone and finish with both (0/5 timeouts). Stated in the description.
2 ⚠️ The test checks rows, not that the lease was parked DISAGREE Without the guard the test fails (TIMEOUT_EXCEEDED at 60 s, 2/2), so it discriminates the fix. Parks equal unparks on the initiator was checked separately (8/8 hedged, 8/8 non-hedged, 19/19 two replicas).
3 💡 Packet decoding runs while parked noted CPU time is still billed at the next renew; only the concurrency limit is not applied while a packet is decoded. Stated in the description. Same median time on a 300M-row read.
4 💡 On a failing run the test leaves its workload and resource behind noted The leading DROP ... IF EXISTS makes a rerun clean; only an already-failing run is affected.

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

Session id: cron:clickhouse-review-self-slot-58:20261017-192900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. In a 1-slot CPU workload, SELECT number % 10 AS k, count() FROM remote('127.0.0.2', numbers(20000000)) GROUP BY k SETTINGS workload = 'w1', max_threads = 1, async_socket_for_remote = 0, max_execution_time = 5 times out 5/5 on master (hedged and use_hedged_requests = 0), 3/3 for a two-replica sampling_key read.
b Root cause explained? The synchronous read blocks in RemoteQueryExecutor::read -> connections->receivePacket() without parking, so the initiator keeps the workload's only CPU slot while the shard on the same server waits for it in CPULeaseAllocation::renew.
c Fix matches root cause? Yes: that wait now runs in a CPULeaseParkGuard, as the asynchronous path already does in PollingQueue. No timeout or limit changes.
d Test intent preserved / new tests added? New stateless test, hedged and non-hedged queries in a 1-slot workload.
e Both directions demonstrated? Yes: the test fails on master (TIMEOUT_EXCEEDED at 60 s, 2/2) and passes with the fix (20/20 plain, 50/50 randomized, 20/20 with parallel replicas enabled).
f Fix is general across code paths? One guard covers the hedged epoll, the socket recv and the multiplexed select (each measured). The finish() drain and the synchronous sendQuery stay unparked: they hold was_cancelled_mutex, and parking there closes a lock cycle. A read of several shards also needs #126512 (measured: hangs with either PR alone, finishes with both).
g Fix generalizes across inputs (params/datatypes/wrappers)? No data types involved. Measured over use_hedged_requests 0/1, one shard / two shards / two replicas, max_threads 1-8, 1-slot and 8-slot workloads, async 0/1 controls, parking disabled (integration test).
h Backward compatible? (maintainer-approved exception only) Yes: no setting, default, format or protocol change.
i Invariants and contracts preserved? The guard holds no other lock; park never blocks, unpark borrows a slot and never blocks, nesting is safe, and an exception unparks in the destructor. The cancel check and processPacket sequence in read are unchanged. Same median time on a 300M-row synchronous read before and after.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @serxa, could you review this? With async_socket_for_remote = 0 the remote read blocks in RemoteQueryExecutor::read -> connections->receivePacket() without parking, so in a 1-slot workload the shard on the same server never gets the slot; this parks the lease around that call only, as PollingQueue does for the asynchronous path since #117711.

@clickhouse-gh

clickhouse-gh Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [88c505f]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR parks the CPU lease around synchronous RemoteQueryExecutor::read packet reception, allowing a shard on the same server to use a workload's only CPU slot. The added test covers hedged and non-hedged reads. Request changes: the previously reported CPU-budget regression remains in the current head (88c505f10d41f8d61beef0ce7332a11460fe8198), and its prerequisite fix is still unmerged.

Findings

⚠️ Majors

  • CPU credit accumulates on every packet, bypassing workload CPU limits. src/QueryPipeline/RemoteQueryExecutor.cpp:891 introduces a park/unpark pair for every packet. CPULeaseAllocation::parkLease cancels pending requests and returns granted quanta without reducing requested_ns (src/Common/Scheduler/CPULeaseAllocation.cpp:461–478); unparkLease calls schedule, which adds another quantum to requested_ns (:798–800). Repeated packet reads therefore accumulate credit that delays renew preemption during subsequent CPU-bound work, defeating max_cpus and delaying competing workloads. The earlier inline reproduction measured 2.248 CPU seconds in 2.258 elapsed seconds with max_cpus = 0.1, zero preemptions, and only 30 ms charged; disabling parking took 23.722 seconds with 207 preemptions. Those measurements are from the prior review, not a rerun. Both accounting paths remain unchanged in the current head. Required: land the budget-accounting correction in Budget-aware cost for CPU lease requests, so parking does not extend a slot #126336 before this park site, or include an equivalent correction with regression coverage. Existing unresolved finding; no duplicate inline comment posted.
Tests
  • ⚠️ Add a focused regression that receives many synchronous remote packets and then performs CPU-bound work under a small max_cpus budget, verifying that the accumulated reads do not postpone preemption. The new 05406_cpu_lease_park_sync_remote_read test passes in Fast Test for this head, but checks completion and results under max_concurrent_threads = 1; it cannot detect the CPU-budget regression. Existing parking tests check park/unpark counts rather than this invariant. No local tests were run.
Final Verdict

Status: ⚠️ Request changes

Merge the CPU-budget accounting correction and verify CPU-limit enforcement after repeated synchronous packet reads before landing this change.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... labels Oct 17, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 17, 2026
Packet packet;
{
/// Non-CPU wait for the remote side: park the CPU lease while blocked
CPULeaseParkGuard cpu_park;

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.

⚠️ Major — fix CPU-budget accounting before parking every packet

This adds a park/unpark pair for every received packet, but the current CPULeaseAllocation::parkLease leaves returned/cancelled quanta in requested_ns, and unparkLease adds another quantum. A stream of packets therefore accumulates CPU credit that survives into subsequent CPU-only work, preventing renew from enforcing workload limits.

I reproduced this with the PR's Fast Test binary, a resource covering MASTER THREAD and WORKER THREAD, and workload settings max_concurrent_threads = 8, max_cpus = 0.1, max_burst_cpu_seconds = 0.01:

SELECT count()
FROM numbers(30000000)
WHERE cityHash64(number) NOT IN
    (SELECT cityHash64(number)
     FROM remote('127.0.0.2:19845', numbers(500000)))
SETTINGS workload = 'review_wl', max_threads = 1, max_block_size = 1000,
    async_socket_for_remote = 0, async_query_sending_for_remote = 0,
    use_hedged_requests = 0, use_concurrency_control = 1;

With parking enabled, the initiator parks 507 times, consumes 2.248 CPU seconds in 2.258 elapsed seconds, and never preempts; the scheduler charges only 30 ms. Disabling parking gives 23.722 elapsed seconds and 207 preemptions, respecting max_cpus = 0.1. The excess credit thus bypasses CPU limits after the remote set has been built and can also delay competing workloads.

Please land the budget-accounting correction before this new park site and add coverage for CPU renewal after the synchronous read.

Related: #126133

Related: #126336

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed on the mechanism, but the extra credit comes from parkLease keeping requested_ns (#126133), and #126336 fixes it there: with #126336 applied your query keeps the limit (debug build: 69-72 preemptions, 7.8-8.1 s, vs 0 and 0.72 s without it). The description states that this PR needs #126336 to land first, and the renewal-after-park coverage is in #126336 (ParkingDoesNotExtendSlotLease, test_parked_query_still_renews_cpu_slot).

…-remote-read

# Conflicts:
#	src/QueryPipeline/RemoteQueryExecutor.cpp
@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a2f86c33d with master bdbd1b837 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of b02fbee24; 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

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

Job report

…-remote-read

# Conflicts:
#	src/QueryPipeline/RemoteQueryExecutor.cpp

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.

2 participants