Skip to content

Fix SELECT slowdown caused by simple INSERTs holding unused CPU slots - #102928

Merged
serxa merged 18 commits into
ClickHouse:masterfrom
seva-potapov:concurrencycontrol-lazy-allocation
Jun 22, 2026
Merged

serxa merged 18 commits into
ClickHouse:masterfrom
seva-potapov:concurrencycontrol-lazy-allocation

Conversation

@seva-potapov

@seva-potapov seva-potapov commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

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 SELECT queries being significantly slower when concurrent INSERTs are running. Previously an INSERT pipeline reserved CPU slots up to max_threads at query start even when most slots were never used, starving concurrent SELECTs. CPU slot allocation is now demand-driven: the pipeline only requests slots as it actually pushes parallelizable work. Applies both to concurrency control and to the preemptive CPU scheduler for workloads. New server setting concurrent_threads_lazy_allocation (default true) acts as a rollback lever.

Details:

#88339 widened INSERT pipelines to use max_threads instead of max_insert_threads when sizing the number of pipeline threads. Simple single-chain INSERTs then requested allocate(1, max_threads) from ConcurrencyControl, the scheduler eagerly granted all slots, and the unused grants counted against the global concurrency limit (concurrent_threads_soft_limit_num / concurrent_threads_soft_limit_ratio_to_cores), starving concurrent SELECTs. The same shape of bug affected queries routed through workload CPU scheduling (CPULeaseAllocation).

The fix has three coordinated parts:

1. InterpreterInsertQuery returns to its simple form. pipeline.setNumThreads(max_threads) for all INSERT pipelines, regardless of materialized views. The workaround merged earlier as #102961 (isViewsInvolved() ? max_threads : max_insert_threads) is reverted — with lazy allocation in place it is no longer needed to prevent slot-reservation waste.

2. ISlotAllocation gains a setMax(N) method. Allocations are now demand-sized: callers pass a small initial ceiling to allocate(min, max) and grow or shrink the ceiling at runtime via setMax. Growing the ceiling re-admits the allocation to the scheduler's waiter list (re-enabling further grants); shrinking only caps future grants — it never reclaims already-granted slots.

  • ConcurrencyControl::Allocation implements setMax for the round_robin, fair_round_robin, and max_min_fair schedulers. max_min_fair preserves its sort-by-allocated invariant by routing grants and re-inserts through intrusive-set helpers.
  • CPULeaseAllocation implements setMax via a new mutable current_max_slots field that gates schedule(). The constructor accepts an optional initial_max_slots argument; the natural grant chain in grantImpl fills out the rest one request at a time after setMax(N).
  • CPUSlotsAllocation is unchanged (the non-preemptive workload allocation; the default setMax no-op preserves its current behavior).

3. PipelineExecutor drives setMax from observed demand. The previous design used eager allocate(1, max_threads) and let the spawning loop decide how many threads to actually start, leaving granted-but-unused slots pinned to the allocation. The new design starts at master_threads (= 1) and the upscaling block in executeStepImpl raises the ceiling whenever pushTasks reports that newly-queued tasks would benefit from additional parallelism. ExecutorTasks::pushTasks now returns a size_t "additional threads to target" and upscale returns remaining-capacity rather than a SpawnStatus enum (the SHOULD_SPAWN / DO_NOT_SPAWN enum is removed).

The server setting concurrent_threads_lazy_allocation (default true) toggles PipelineExecutor between the lazy and eager paths. It is ChangeableWithoutRestart::Yes.

Tests:

  • gtest_concurrency_control — eleven new tests covering lazy + setMax behaviour, eager-allocation backward compatibility, grow/shrink semantics, work-conserving max-min-fair, and a concurrent stress test.
  • gtest_workload_resource_manager — five new tests covering CPULeaseAllocation lazy initialisation, setMax growth, max_threads clamping, shrink-doesn't-reclaim, and eager-default backwards compatibility.
  • 04102_insert_threads_eagerly_spawned — existing test from Use max_insert_threads for plain INSERTs without materialized views #102961; with-MV branch tightened to upper-bound peak_threads_usage (lazy CC correctly produces peak = 1 for trivial MV pipelines now).
  • 04229_lazy_concurrency_control_insert_with_mv — stateless test asserting peak_threads_usage <= 4 for the INSERT-with-MV parallel_view_processing=0 case routed through ConcurrencyControl.
  • 04230_lazy_cpu_lease_allocation_insert_with_mv — same shape as 04229 but routed through CPULeaseAllocation via CREATE RESOURCE … (MASTER THREAD, WORKER THREAD) and CREATE WORKLOAD.

Related:

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.1108

@seva-potapov
seva-potapov requested a review from serxa April 17, 2026 05:24
@clickhouse-gh

clickhouse-gh Bot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e2872a8]

Summary: ✅


AI Review

Summary

The PR implements demand-driven CPU slot allocation for PipelineExecutor, including ConcurrencyControl and preemptive workload CPU scheduling, and reverts the interim INSERT workaround from #102961. The core direction is reasonable, but the current patch still has several contract gaps where lazy allocation is bypassed, over-counts demand, or can hang on the public unlimited sentinel.

Missing context / blind spots
  • ⚠️ The GitHub check rollup still had several jobs in progress when reviewed. Passing CI would close only build/test execution blind spots, not the behavioral issues below.
Findings

⚠️ Majors

  • [src/Common/ConcurrencyControl.cpp:191] allocate(0, UnlimitedSlots) now tries to materialize the infinite ceiling. With the default max_concurrency == UnlimitedSlots, the unconditional schedule call walks the waiter loop until state.cur_concurrency == state.max_concurrency, effectively spinning through 2^64-1 grants. The same pattern exists in the fair_round_robin and max_min_fair allocation paths.
    Suggested fix: special-case max == UnlimitedSlots, or otherwise keep the allocation logically unbounded without eagerly draining the scheduler loop.

  • [src/Interpreters/InterpreterInsertQuery.cpp:837] Reverting all INSERT pipelines to max_threads is only safe when lazy slot allocation actually gates worker creation. With use_concurrency_control=0, PipelineExecutor returns GrantedAllocation(num_threads), so a plain 1-wide INSERT can spawn up to max_threads again despite max_insert_threads=1. The same regression returns when concurrent_threads_lazy_allocation=false makes the ConcurrencyControl path eager.
    Suggested fix: keep the max_insert_threads ceiling for simple INSERTs on non-lazy/non-CC paths, or otherwise prove those modes still keep peak_threads_usage bounded.

  • [src/Processors/Executors/PipelineExecutor.cpp:534] Lazy allocation is still not true for non-preemptive workload CPU scheduling. When cpu_slot_preemption=false, this path returns CPUSlotsAllocation, whose setMax is the default no-op and whose constructor/grant chain requests all master + worker slots eagerly. That leaves a supported workload-scheduler mode with the same slot-hoarding behavior the PR promises to remove.
    Suggested fix: implement a mutable ceiling in CPUSlotsAllocation, or reject/document that concurrent_threads_lazy_allocation does not apply to non-preemptive workload scheduling and route it through the eager contract.

  • [src/Common/Scheduler/CPULeaseAllocation.cpp:469] CPULeaseAllocation::setMax does not cap future grants if a shrink races with an already-enqueued request. The shrink only updates current_max_slots; when the queued request later executes, grantImpl increments allocated and granted beyond the new ceiling before schedule can stop the next request.
    Suggested fix: cancel the pending request on shrink when the new ceiling is already reached, or explicitly document and test that queued-but-not-yet-granted requests may escape the shrunken ceiling.

  • [src/Processors/Executors/ExecutorTasks.cpp:171] pushTasks and fill count async_queue entries as immediate CPU demand, but those tasks are not runnable until processAsyncTasks observes readiness. Workers spawned for those async waits can park in threads_queue while still holding acquired CPU slots, recreating the reserved-but-unused slot shape through async processors.
    Suggested fix: count only immediately runnable tasks for the setMax demand signal and grow the ceiling when async tasks become ready.

Tests
  • ⚠️ Add a focused ConcurrencyControl gtest for allocate(0, UnlimitedSlots) under the default unlimited limit.
  • ⚠️ Add INSERT coverage for use_concurrency_control=0 and for concurrent_threads_lazy_allocation=false to prove simple INSERTs remain bounded by max_insert_threads where expected.
  • ⚠️ Add workload scheduling coverage for cpu_slot_preemption=false, since the current new stateless test covers only the preemptive CPULeaseAllocation path.
  • ⚠️ Add a CPULeaseAllocation test that shrinks while isRequesting is true and verifies no extra slot becomes acquirable after the shrink.
  • ⚠️ Add executor coverage for async-heavy pipelines so async waits do not inflate CPU slot demand before they are runnable.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: fix the UnlimitedSlots scheduling loop, keep simple INSERT thread usage bounded when lazy allocation is bypassed, make the lazy contract true or explicitly unsupported for non-preemptive workload scheduling, fix the CPULeaseAllocation shrink/enqueued-request race, and avoid treating async waits as runnable CPU demand.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 17, 2026
Comment thread src/Common/ConcurrencyControl.cpp Resolved
@serxa serxa self-assigned this Apr 17, 2026
Comment thread src/Common/ConcurrencyControl.h Resolved
Comment thread src/Common/ConcurrencyControl.h Resolved
Comment thread src/Common/ISlotControl.h Resolved
Comment thread src/Core/ServerSettings.cpp Resolved
@seva-potapov
seva-potapov requested a review from serxa April 24, 2026 04:14
Comment thread src/Common/ConcurrencyControl.h Resolved
Comment thread src/Core/ServerSettings.cpp Resolved
@seva-potapov
seva-potapov requested a review from serxa May 12, 2026 12:25
@serxa

serxa commented Jun 1, 2026

Copy link
Copy Markdown
Member

There is another important implementation of ISlotControl interface that we changed in this PR. This is CPULeaseAllocation, which is used for workload CPU scheduling. And it would be nice to fix it as well. At least we should make sure our interface changes won't lead to any contradictions. Let me try to iterate on it with Claude...

serxa added 3 commits June 1, 2026 17:47
- Replace four stale "SHOULD_SPAWN handler" comment references in
  PipelineExecutor with "upscaling block": after the rework, `pushTasks`
  returns `size_t spawn_count` instead of a `SpawnStatus` enum, so the
  block that handles it is no longer a "SHOULD_SPAWN handler".
  `tasks.upscale` in spawnThreads still legitimately uses SpawnStatus
  and is left untouched.

- Add 04229_lazy_concurrency_control_insert_with_mv stateless test
  covering the remaining slice of issue ClickHouse#102947 that PR ClickHouse#102961 did not
  reach: an INSERT with a materialized view asks for max_threads
  because views are involved, but under serial view processing the
  pipeline only needs a handful of threads. Pre-this-PR the eager
  ConcurrencyControl allocation grants all max_threads slots up front,
  inflating peak_threads_usage. Post-this-PR lazy allocation keeps it
  bounded by actual demand.
…tion

ExecutorTasks::upscale now returns size_t — the number of additional threads
the caller may try to spawn next (0 = stop). The two functions that returned
SpawnStatus purely for callers that already ignored it (tryWakeUpAnyOther-
ThreadWithTasks and tryWakeUpAnyOtherThreadWithTasksInQueue) become void. The
SpawnStatus enum is removed.

Semantics are preserved: PipelineExecutor::spawnThreads still spawns one
thread per iteration and re-enters upscale after the next tryAcquire — the
return is informational (current remaining pipeline-width capacity) rather
than a flag. The `> TOO_MANY_IDLE_THRESHOLD` back-pressure brake still maps
to a 0 return.

The with-MV branch of 04102_insert_threads_eagerly_spawned now correctly
upper-bounds peak_threads_usage at 4 instead of requiring >1. With lazy
ConcurrencyControl in place, a trivial INSERT-with-one-MV that pushes only
1 thread of useful work no longer grabs additional CPU slots — peak settles
at 1. The old assertion "MV should add threads" contradicted that and is
replaced with "MV must not eagerly spawn threads", matching the test's
overall intent.
CPULeaseAllocation now honours setMax via a new mutable current_max_slots
field that gates schedule(). The constructor accepts an optional
initial_max_slots argument (default 0 = use max_threads, matching the
previous eager behaviour). PipelineExecutor passes master_threads (1) as
initial_max_slots when lazy allocation is enabled, mirroring the
ConcurrencyControl branch.

Setting a larger ceiling via setMax kicks off scheduling for the
additional capacity; the natural grant chain in grantImpl then fills
out the remaining slots one request at a time. Shrinking does not
reclaim already-granted slots — it only stops the next round of
scheduling, matching the semantics established for ConcurrencyControl
allocations.

The hard cap (vector-sizing) max_threads constant is unchanged. Pre-
existing callers that don't pass initial_max_slots keep the eager
behaviour bit-for-bit.

Also clarify two stale "setMax" comments in ExecutorTasks: spell out
that the value flows through PipelineExecutor into the cpu_slots
allocation's setMax, since the reader of ExecutorTasks doesn't have
that context locally.
@serxa

serxa commented Jun 2, 2026 •

Copy link
Copy Markdown
Member

@CheSema what you think about reverting #102961 ? This PR is basically the lazy slot allocation implementation and your PR says:

Until lazy CC slot allocation is implemented, we have no choice other than to set strict limits on the thread count for insert queries.

But TBH I'm not sure if the revert would be 100% safe. What are your thought on this? Should we keep your PR or revert inside this PR? UPD. We decided to revert it, I checked that tests are good now.

alexey-milovidov and others added 3 commits June 3, 2026 06:10
04230_lazy_cpu_lease_allocation_insert_with_mv routes an INSERT-with-MV
through `CPULeaseAllocation` by binding a workload to a `MASTER THREAD`
+ `WORKER THREAD` resource. Pre-fix the lease eagerly requested
`max_threads` slots from the workload scheduler; the test verifies
`peak_threads_usage <= 4` (lazy on -> peak=4 locally; lazy off -> peak=12).

Mirrors 04102 / 04229 in shape and thresholds.
…ation' into concurrencycontrol-lazy-allocation
@serxa serxa added the can be tested Allows running workflows for external contributors label Jun 18, 2026
// `master_threads` from the workload scheduler at startup and let the
// PipelineExecutor upscaling block grow the ceiling via `setMax` as the
// pipeline actually pushes parallelizable work.
SlotCount initial_max = lazy_allocation ? master_threads : num_threads;

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.

⚠️ The lazy-allocation contract is still not true for the non-preemptive workload scheduler path. When cpu_slot_preemption is disabled, this branch returns CPUSlotsAllocation, which does not override ISlotAllocation::setMax and its constructor immediately starts requesting master_threads + worker_threads slots (CPUSlotsAllocation.cpp:75-83, then grant chains the rest). PipelineExecutor still initializes desired_threads = 1 and later calls cpu_slots->setMax(target), but those calls are no-ops for this backend, so an INSERT with materialized views, or any workload-scheduled query in this supported mode, can still reserve up to max_threads slots while the new setting is true.

Please either implement the same mutable ceiling in CPUSlotsAllocation, or explicitly route this mode through the eager path/document that concurrent_threads_lazy_allocation does not apply when cpu_slot_preemption = false. A focused regression with CREATE RESOURCE ... (MASTER THREAD, WORKER THREAD) and cpu_slot_preemption=false would cover the gap.

…ference

Five new unit tests covering the lazy path of `CPULeaseAllocation`:
- `PreemptiveCPUSchedulingLazyStartsAtInitialMax`
- `PreemptiveCPUSchedulingLazySetMaxGrows`
- `PreemptiveCPUSchedulingLazySetMaxClampedByMaxThreads`
- `PreemptiveCPUSchedulingLazySetMaxShrinkDoesNotReclaim`
- `PreemptiveCPUSchedulingEagerDefaultIsUnchanged`
The names follow the existing `PreemptiveCPUScheduling*` convention used
by the other preemption tests in the file.

`chassert(new_max > 0)` added to all four `setMax` implementations
(three `ConcurrencyControl::Allocation` schedulers + `CPULeaseAllocation`).
Zero is undefined in this codepath -- the upscaling block in
`PipelineExecutor` only grows `desired_threads` upward from
`master_threads`, so a zero ceiling would never be a legitimate request.
The contract is also documented on the `ISlotAllocation::setMax`
interface.

`01275_parallel_mv` reference regenerated: the old display expression
`if(peak_threads_usage >= 10, 1, peak_threads_usage)` exposed any
sub-10 peak verbatim, which made the reference brittle once lazy
allocation lowered the per-variant peak values. Replaced with a binary
`if(peak_threads_usage >= 10, 1, 0) as saturated_max_threads` -- the
test now checks "did the variant saturate max_threads?" which is the
actual behavioral contract (parallel processing should saturate, lazy
serial processing should not). Two variants saturate
(max_insert_threads=5, parallel_view_processing=1); the other six
don't.

The `concurrent_threads_lazy_allocation` server-setting description
also got a cosmetic tighten -- removed the editorialised "emergency
rollback lever" framing per review feedback.
// grant) then naturally fills up to `current_max_slots` one request at a time.
// Shrinking does not reclaim already-granted slots — it simply caps future grants
// because the next `schedule()` will see `allocated >= current_max_slots` and bail out.
if (growing && !shutdown && allocated < current_max_slots && !requests.hasEnqueued())

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.

⚠️ setMax does not actually cap future grants if a shrink races with an already-enqueued request. A concrete sequence is: construct with initial_max_slots = 1, acquire the first slot, call setMax(4) so this branch enqueues one scheduler request, then call setMax(1) before that request is granted. The shrink only updates current_max_slots; the enqueued request is left live, so grantImpl will still increment allocated/granted to 2 after the ceiling was lowered to 1. That violates the new ISlotAllocation::setMax contract that shrinking stops issuing grants beyond the new max, and it can leave a lazy workload allocation holding a slot the caller explicitly stopped asking for.

Please cancel the pending request on shrink when allocated >= current_max_slots (or document and test that already-enqueued-but-not-granted requests are allowed to escape the new ceiling). A focused unit test should shrink while isRequesting() is true and assert that no extra slot becomes acquirable.

/// Measure the parallelism of the push: how many threads could run the new tasks
/// concurrently. Used by `PipelineExecutor` to size the slot-allocation ceiling via
/// `ISlotAllocation::setMax` on the pipeline's `cpu_slots` handle.
const size_t pushed = queue.size() + async_queue.size();

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.

⚠️ Counting async_queue here treats not-yet-runnable async waits as CPU demand, which breaks the lazy-allocation contract for async-heavy pipelines. For example, if initialization or an update produces 16 async tasks and no regular ready tasks, fill/pushTasks report 16, PipelineExecutor raises cpu_slots->setMax(16), and spawnThreads can acquire all those slots. The workers then enter tryGetTask, find only async_task_queue entries, and park in threads_queue while still holding the CPU slots until the file descriptors become ready. That is the same slot-hoarding shape this PR is trying to remove, just through async processors instead of INSERT sinks.

Please count only immediately runnable tasks for the setMax demand signal, and grow the ceiling when async tasks become ready in processAsyncTasks (or otherwise prove that async waits cannot hold acquired CPU slots while idle). The same adjustment is needed for the fill return value, which currently includes initial async_queue entries too.

@serxa

serxa commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Verified that lazy allocation alone is sufficient to bound peak_threads_usage correctly even with the workaround reverted to pipeline.setNumThreads(max_threads). All related stateless tests (01275_parallel_mv, 04102, 04229, 04230, 02350, 02871, 03562) still pass. We will rollback #102961 as part of this PR.

serxa added 2 commits June 19, 2026 16:59
The ternary `isViewsInvolved() ? max_threads : max_insert_threads`
introduced as ClickHouse#102961 was a defensive workaround for the eager-slot
allocation bug. With lazy `ConcurrencyControl` / `CPULeaseAllocation`
in place (this PR), pipeline slot grants are demand-driven;
`setNumThreads(max_threads)` on a 1-wide INSERT pipeline no longer
translates into reserved-but-unused CPU slots.
Use `!workers.empty()` instead of `workers.size() >= 1`
(`readability-container-size-empty`).
}
// Fill the new allocation up to `max` from available capacity (also benefits any other
// waiters that have free room). For lazy callers (allocate(1, 1)), this is a no-op.
parent.schedule(lock);

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.

⚠️ allocate(0, UnlimitedSlots) now tries to materialize the infinite ceiling. With the default max_concurrency == UnlimitedSlots, this unconditional schedule call enters the loop below and keeps granting until state.cur_concurrency == state.max_concurrency, i.e. effectively forever. That is a compatibility regression for the public ISlotControl sentinel: callers used to be able to ask for "unlimited" without spinning through 2^64-1 grants. The same pattern exists in the fair_round_robin and max_min_fair allocate paths.

Please special-case max == UnlimitedSlots (or clamp eager materialization to a finite available capacity) so the allocation can remain unbounded without draining the scheduler loop. A focused gtest with allocate(0, UnlimitedSlots) under the default unlimited limit would catch this.

pipeline.setNumThreads(insert_dependencies->isViewsInvolved() ? max_threads : max_insert_threads);
// Pipeline ceiling: simple upper bound on parallelism. Actual slot grants are
// demand-driven by lazy ConcurrencyControl / CPULeaseAllocation, so a wide ceiling
// does not translate into reserved-but-unused slots.

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.

⚠️ This reintroduces the simple-INSERT thread explosion whenever lazy slot allocation is not actually gating the executor. For example, with use_concurrency_control=0, PipelineExecutor::allocateCPU returns GrantedAllocation(num_threads), so spawnThreads can immediately acquire and start up to this max_threads ceiling even for a 1-wide INSERT pipeline. The same regression appears when the server rollback setting concurrent_threads_lazy_allocation=false makes the ConcurrencyControl path eager again.

That means max_insert_threads=1 no longer bounds plain INSERT execution in these supported modes, undoing the #102961 workaround the moment lazy allocation is disabled or bypassed. Please keep the max_insert_threads ceiling for simple INSERTs on non-lazy/non-CC paths, or add coverage showing those modes still keep peak_threads_usage bounded.

@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.30% +0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.40% 77.50% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 682/700 (97.43%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 9 line(s) · Uncovered code

Full report · Diff report

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