Skip to content

Fix query not upscaling to CPU slots released by other queries (granted slots stayed unused) - #129072

Closed
melvynator wants to merge 1 commit into
ClickHouse:masterfrom
melvynator:fix/executor-upscale-on-queued-work
Closed

melvynator wants to merge 1 commit into
ClickHouse:masterfrom
melvynator:fix/executor-upscale-on-queued-work

Conversation

@melvynator

@melvynator melvynator commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

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):

Fix a query that started while CPU slots (concurrent_threads_soft_limit_*) were exhausted never using the slots freed later by other queries: it stayed on the few threads it got at start, and the slots granted to it stayed unused and blocked other queries until it finished. Regression since 25.6 (#79570).

Documentation entry for user-facing changes

  • Documentation is written (mention the docs PR or section if applicable)

No user-facing changes other than the bug fix.


The problem

Reproduced on 26.7.2.59, 26.3 LTS and current master; 25.3 LTS behaves correctly.

  1. Q1/Q2 hog every CPU slot (concurrent_threads_soft_limit_ratio_to_cores=2).
  2. Q3 — a scan over many object storage files (Parquet on S3, 16 streams) — starts and only gets its noncompeting master slot plus a couple of slots (3 threads).
  3. Q1/Q2 finish and release all their slots. ConcurrencyControl grants them to Q3's allocation (ConcurrencyControlSlotsGranted goes up, cur_concurrency is charged), but Q3 keeps running on 3 threads until it ends.
  4. Any Q4/Q5 started during that window see no free slots either: Q3 holds them granted-but-unacquired.

Timings from the repro (c6a.4xlarge, 16 vCPU, 100 Parquet files behind a slow fake S3 with 250 ms/request):

binary Q3 threads after release Q3 wall time
25.3 LTS 1 → 16 1.27 s
26.7.2.59 3 2.6–2.9 s
master (unpatched) 3 2.81 s
master + this PR 3 → 10 (~60 ms after release) 1.31 s

Root cause

CPUSlotsAllocation::tryAcquire() is only called from PipelineExecutor::spawnThreads(), and since #79570 ("Optimize thread spawning in PipelineExecutor", 25.6) spawnThreads() is only called when ExecutorTasks::pushTasks() reports a positive demand, i.e. when the step that just finished pushed new tasks into the global queue. #102928 (lazy allocation, 26.7) kept that gate.

Per-stream ISimpleTransform chains (which is what an object storage scan is: source → transforms → resize) produce exactly one Ready task per step, and that task is executed as a local task by the same thread. pushTasks() therefore reports a demand of 0 on every step, spawnThreads() is never called again, and slots that were granted to the allocation after the query started are never acquired. The other source tasks sit in the global task_queue with nobody to run them.

The only thing that eventually breaks this is the max_scheduled_local_tasks = 128 valve, which forces a step through the global queue every 128 local steps; with I/O-bound sources that takes seconds, or longer than the query itself.

The fix

ExecutorTasks keeps a lock-free hint (uncovered_hint) of min(queued tasks − idle threads, num_threads − total_slots), updated wherever the queues / threads_queue / total_slots change (already under mutex). In executeStepImpl, when the step pushed nothing itself (spawn_count == 0), the executor uses that hint as the demand, so spawnThreads() → tryAcquire() is retried on the next step and granted slots are picked up immediately.

The hint is zero in the steady state (all queued tasks covered by threads, or no headroom), so the hot path stays a relaxed atomic load; no behaviour change when slots are not constrained.

Test

test_concurrent_threads_soft_limit/test.py::test_concurrent_threads_soft_limit_upscale_after_release: a background query takes all slots on a node with concurrent_threads_soft_limit_num=10, a sleep-bound 8-stream query starts (gets 1 thread), the background query is killed, and the test checks the victim finishes within 1.5 s of the release (fixed: ~0.5 s; unpatched: ~2.6 s because the 128-step valve only fires at ~3.2 s).

Verified with the integration runner: fails on unpatched master, passes (3/3) with the fix, the rest of the file still passes.


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

…ries

Since ClickHouse#79570 the executor only calls spawnThreads() (the sole consumer of
CPUSlotsAllocation::tryAcquire) when a step pushed new tasks into the global
queue. Pipelines made of per-stream ISimpleTransform chains (e.g. object
storage scans) yield exactly one Ready task per step, which is executed as a
local task, so pushTasks() reports zero demand on every step and tryAcquire()
is never retried. A query that started while CPU slots were exhausted therefore
stays on the threads it got at start even after other queries release their
slots; the slots granted to its allocation stay unused and are unavailable to
every other query until it finishes.

Keep a lock-free hint in ExecutorTasks of how many queued tasks could run on
additional threads and, on steps that pushed nothing, retry spawnThreads() for
that many threads so granted slots are picked up immediately.

Adds an integration test that fails without the fix.
@melvynator
melvynator requested a review from serxa November 3, 2026 18:20
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d3c63af]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, sequential) FAIL
01275_parallel_mv FAIL cidb
Stateless tests (arm_binary, sequential) FAIL
01275_parallel_mv FAIL cidb

AI Review

Summary

PR #129072 retries CPU slot acquisition when queued work remains, allowing queries to use slots released by other queries. Changes are required because the retry also repeatedly increases allocation demand for the same work, and the new regression test can stall until its timeout.

Findings

⚠️ Majors

  • [P1] Repeated retries inflate slot demand. PipelineExecutor.cpp:501: getUncoveredHint reports outstanding work, but its value is added to pending_demand and then desired_threads on every local step. With an eight-thread ceiling, two ready chains, one acquired slot, and one queued chain, six retries raise the requested ceiling from two to eight without new parallel work. Subsequent grants can produce idle workers or remain unacquired while blocking other queries. Separate acquisition retries from additive demand, or use an idempotent allocation target that accounts for existing requests.
  • [P2] The foreground-start poll can miss completion and stall. test.py:392: if the foreground query completes before its transient system.processes entry is observed, or fails before registration, polling cannot succeed. Background cancellation is after the loop, so the test waits for its 900-second timeout with the load still running. Bound the wait, detect worker completion/errors, and cancel/join workers in finally.
Tests
  • ⚠️ Add coverage for a narrow stage with a wider pipeline ceiling while CPU slots are exhausted: repeated local steps must not repeatedly increase allocation demand, and releasing slots must leave unused capacity available to other queries. The added test starts with demand already at its full ceiling and misses this regression.
  • ⚠️ A mocked execution of the actual added test reproduced continued polling after foreground completion with no background cleanup. No local ClickHouse binary/build was available for a server reproduction of the allocation issue; that finding follows a concrete trace of the current hint, demand, and spawning logic.
Final Verdict

⚠️ Request changes. Separate retry signaling from demand growth, add the narrow-stage regression coverage, and make the test's polling and cleanup bounded.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 3, 2026
/// CPU slots granted to this allocation after other queries released theirs are only consumed by
/// `spawnThreads()`, so without this retry they would stay granted-but-unused until the query ends.
if (pool && spawn_count == 0)
spawn_count = tasks.getUncoveredHint();

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.

[P1] Retry acquisition without adding the same queued work to demand repeatedly

getUncoveredHint measures outstanding work, but assigning it to spawn_count feeds it into the additive pending_demand / desired_threads calculation below. For example, with an eight-thread pipeline ceiling, two initially ready chains, one acquired slot, and the other chain queued, the hint stays at one while slots are exhausted. Six local processor steps then grow desired_threads from two to eight without any new parallel work. When slots become available, setMax has already requested all eight: spawnThreads can start idle workers, and any unacquired grants still count against other queries. This defeats lazy allocation for narrow stages of wider pipelines and recreates slot hoarding.

Keep the acquisition retry separate from additive demand, or derive an idempotent allocation target that accounts for slots already requested. Please cover a narrow stage with a wider pipeline ceiling under slot contention; the added test starts with demand already at its full ceiling, so it cannot expose this inflation.

== "1"
)

while not foreground_started():

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.

[P2] Bound the foreground-start wait and clean up on failure

This loop requires observing a transient entry in system.processes. If the foreground query completes before the polling thread observes it, or raises before registration, every subsequent check returns zero and the loop cannot terminate. The background query is killed only after the loop, so this consumes the integration test's 900-second timeout while leaving the CPU load running. Executing the actual test function with foreground completion forced before its first poll confirms that polling continues and no cleanup runs.

Use a bounded wait that also detects foreground completion/errors, and put cancellation and thread cleanup in finally so a missed observation fails promptly.

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Nov 3, 2026
serxa added a commit that referenced this pull request Nov 3, 2026
The test is taken from #129072 by Melvyn Peignon.

Co-Authored-By: Melvyn Peignon <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@serxa

serxa commented Nov 3, 2026

Copy link
Copy Markdown
Member

#125901 fixes the same problem. The difference is in how the missing demand is tracked. Here the number of uncovered queued tasks is added to pending_demand on every step that pushes nothing, so the same tasks are counted again and again and setMax grows up to max_threads, as without lazy allocation. In #125901, ExecutorTasks remembers the thread requests that found no CPU slot (threads_to_spawn) and every thread starts threads for them once slots are granted, so setMax grows only by what pushTasks requested. The same counter also covers threads downscaled by CPU preemption, and spawn_mutex is removed. The integration test from this PR is included there, and it passes.

@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d3c63af15 with master 18430ef4a (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

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

Median compile-time ratio to the baselines is ×0.93 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +0.0 s (+0%) in total before that adjustment.

Job report

@serxa

serxa commented Nov 5, 2026

Copy link
Copy Markdown
Member

#125901 covers the issue

@serxa serxa closed this Nov 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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