Repository navigation
Fix SELECT slowdown caused by simple INSERTs holding unused CPU slots - #102928
Conversation
|
Workflow [PR], commit [e2872a8] Summary: ✅
AI ReviewSummaryThe PR implements demand-driven CPU slot allocation for Missing context / blind spots
Findings
Tests
Final VerdictStatus: Minimum required actions: fix the |
|
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... |
- 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.
|
@CheSema what you think about reverting #102961 ? This PR is basically the lazy slot allocation implementation and your PR says:
|
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
| // `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; |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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.
|
Verified that lazy allocation alone is sufficient to bound |
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); |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
LLVM Coverage Report
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 |
Changelog category (leave one):
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_threadsat 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 settingconcurrent_threads_lazy_allocation(defaulttrue) acts as a rollback lever.Details:
#88339 widened INSERT pipelines to use
max_threadsinstead ofmax_insert_threadswhen sizing the number of pipeline threads. Simple single-chain INSERTs then requestedallocate(1, max_threads)fromConcurrencyControl, 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.
InterpreterInsertQueryreturns 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.
ISlotAllocationgains asetMax(N)method. Allocations are now demand-sized: callers pass a small initial ceiling toallocate(min, max)and grow or shrink the ceiling at runtime viasetMax. 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::AllocationimplementssetMaxfor theround_robin,fair_round_robin, andmax_min_fairschedulers.max_min_fairpreserves its sort-by-allocated invariant by routing grants and re-inserts through intrusive-set helpers.CPULeaseAllocationimplementssetMaxvia a new mutablecurrent_max_slotsfield that gatesschedule(). The constructor accepts an optionalinitial_max_slotsargument; the natural grant chain ingrantImplfills out the rest one request at a time aftersetMax(N).CPUSlotsAllocationis unchanged (the non-preemptive workload allocation; the defaultsetMaxno-op preserves its current behavior).3.
PipelineExecutordrivessetMaxfrom observed demand. The previous design used eagerallocate(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 atmaster_threads(= 1) and the upscaling block inexecuteStepImplraises the ceiling wheneverpushTasksreports that newly-queued tasks would benefit from additional parallelism.ExecutorTasks::pushTasksnow returns asize_t"additional threads to target" andupscalereturns remaining-capacity rather than aSpawnStatusenum (theSHOULD_SPAWN/DO_NOT_SPAWNenum is removed).The server setting
concurrent_threads_lazy_allocation(defaulttrue) togglesPipelineExecutorbetween the lazy and eager paths. It isChangeableWithoutRestart::Yes.Tests:
gtest_concurrency_control— eleven new tests covering lazy +setMaxbehaviour, eager-allocation backward compatibility, grow/shrink semantics, work-conserving max-min-fair, and a concurrent stress test.gtest_workload_resource_manager— five new tests coveringCPULeaseAllocationlazy initialisation,setMaxgrowth,max_threadsclamping, 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-boundpeak_threads_usage(lazy CC correctly producespeak = 1for trivial MV pipelines now).04229_lazy_concurrency_control_insert_with_mv— stateless test assertingpeak_threads_usage <= 4for the INSERT-with-MVparallel_view_processing=0case routed throughConcurrencyControl.04230_lazy_cpu_lease_allocation_insert_with_mv— same shape as 04229 but routed throughCPULeaseAllocationviaCREATE RESOURCE … (MASTER THREAD, WORKER THREAD)andCREATE WORKLOAD.Related:
Documentation entry for user-facing changes
Version info
26.6.1.1108