Repository navigation
Conversation
…duling With `CREATE RESOURCE cpu (MASTER THREAD, WORKER THREAD)` and `cpu_slot_preemption` only `PipelineExecutor` threads held a CPU lease. Index analysis runs while the plan is built, before an executor exists, so its CPU was never reported, throttled or preempted, and a query whose time goes to `filterPartsByPrimaryKeyAndSkipIndexes` ignored the limits of its workload (ClickHouse#88304). `filterPartsByPrimaryKeyAndSkipIndexes` now runs on its own `CPULeaseAllocation` when preemptive CPU scheduling applies and the calling thread is not already on a CPU lease: - the query thread takes the master slot; a worker thread starts only for a granted slot (`tryAcquire`), checked before the first part, after each part and, on the calling thread, at the in-part points; - every thread renews its lease after each part, which reports the CPU and is the downscale point; a preempted thread holds no part; - inside a part, every 256 steps of the generic exclusion search (primary key, text index), of the per-mark skip-index loops, of the minmax granule read and the per-part selection of the top-K path, and of the disjunction merge call `renewInTask`; a thread preempted there waits for a grant without a timeout; - the allocation is registered with `QueryStatus`, so `KILL QUERY` frees it and wakes a preempted thread. This also holds after a failed `replace_running_query`: the replacement sets only `is_killed`, and `cancelQuery` used to return early on it before the allocations were freed, so a later `KILL QUERY` could not wake an analysis preempted inside a task; - `CPULeaseAllocation::release` of a running slot resumes a preempted thread of the same allocation. An executor frees its allocation before its threads release their slots, but the analysis releases slots while its other threads are preempted. Without the resume the preempted thread waits for one more grant while the released slot stays allocated and unused, and a workload whose every slot ends up held this way hangs; - on a thread that already runs on a CPU lease (an executor thread: `mergeTreeAnalyzeIndexes`, which is the replica side of `distributed_index_analysis`, `loop()`, delayed local plans) the existing code runs unchanged, because a second allocation there can hang a one-slot workload; - the allocation is made only on a thread of the analysed query: a dictionary loaded for a waiting `dictGet` runs in the caller's thread group, whose slots the caller can hold. The top-K selection of a part also renews while it drains the tied granules. The workload link lookup of `PipelineExecutor` moves into `WorkloadCPUScheduling`, shared with the analysis. `ISlotLease::renewInTask` and the coroutine-local `CurrentCPULease` are the same as in ClickHouse#126572. The comment of `test_parking_disabled_no_parks` is updated: executors now publish every lease, parking is decided by `isParkingEnabled`. Tests: `05566_index_analysis_cpu_lease` (CPU accounting; preemption inside one part on the primary key, skip-index and top-K paths; five one-slot shapes without a hang, one of them a dictionary load; KILL of a starved analysis, also after a failed replacement) and gtests for a worker preempted inside a task, `free` waking it, and a released slot resuming it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove three comments that restate the code below and shorten two to one line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Six review rounds (own review + a second model per round); the last two found nothing blocking.
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20261107-222900 |
|
Workflow [PR], commit [2466b94] Summary: ✅
AI ReviewSummaryThe PR gives Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Handle the interactive callback's cancellation result and add the focused starvation regression. Obtain completed results from the relevant CI jobs. |
|
cc @shankar-iyer, could you review this and add the |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes28 object files changed (+62.15 KiB total), 1 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1661 translation units recompiled, 8385 s compile time in total, 1660 of them have a recent master baseline. |
…slot The master thread of the index analysis allocation is the query's own thread, for the native protocol the `TCPHandler` thread inside `executeQuery`, before `processOrdinaryQuery` starts polling the connection. When the workload has no free slot (a higher priority query holds it), that thread waits for a grant without a timeout in `CPULeaseAllocation::waitForGrant`, or in `pool->wait()` for workers preempted inside a part, so Ctrl-C and a closed connection were not noticed: only `KILL QUERY` or a free slot ended the query. On master, the same starved query is cancelled by the client in 0.3 s, because it waits in the executor while `TCPHandler` polls. `CPULeaseSettings::on_master_wait` is called every `master_wait_period` (100 ms) while the master thread waits for a slot, without the allocation's mutex (the callback frees the allocation through `QueryStatus::cancelQuery`). Index analysis passes the query context's interactive cancel callback there and also polls it while it joins its workers. The callback reads the `Cancel` packet, kills the query and throws `QUERY_WAS_CANCELLED_BY_CLIENT`; an exception out of the wait is the same path as one from `on_preempt`, and `release` of a preempted lease is already consistent. Running the analysis on a pool thread while the query thread only polls (as `CompletedPipelineExecutor` does) was measured first: it costs a thread per analysis, -9..12% point-query QPS in an unlimited workload, so it was dropped. Reported by the AI review on ClickHouse#130124. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Changes of CPULeaseAllocation allocation interface look too expensive. We have now basically different versions with in-task=true. Interface now looks ugly. Please explain why do we need such complicated thing? Why cannot we use separate class for in-tasks? Or why cannot we reuse existing implementation? |
|
The in-task variant exists for one property: a thread preempted in the middle of a part cannot hand the part to another thread, so it has to wait for a grant with no timeout and without You are right that this needs no new interface. The analysis allocation has its own What stays in
|
The analysis allocation has no on_preempt / on_resume, so with preemption_timeout = max its threads already wait for a grant instead of stopping, which is all the in-task variant did. Remove ISlotLease::renewInTask, the in_task parameter of CPULeaseAllocation::renew / waitForGrant and renewCurrentCPULeaseInTask; the in-part points call renew() on the lease of the analysis thread (skipped while a nested pipeline runs on that thread). A worker preempted between parts now waits for a grant instead of exiting after the timeout; it holds no part, and release() resumes it. Test: the hog reads past the max_rows_to_read of the CI profile, so it is run without it (it stopped at once in CI, the starved queries were never starved); the resource name is fixed so CREATE OR REPLACE replaces the one of a killed run; no-flaky-check, because under the flaky check's thread fuzzer the inserts into the index_granularity = 1 tables alone take longer than the timeout. Co-Authored-By: Claude Opus 5.5 <[email protected]>
While the query thread waits for a CPU slot or for the analysis workers it already read the client's Cancel packet; it now also calls QueryStatus::checkTimeLimit. A killed query (KILL QUERY, replace_running_query) or a THROW time limit stops the wait with the exception; past a BREAK time limit the allocation is freed, so the analysis finishes unthrottled and the executor returns the partial result, as when an executor waits. Before this, a query with max_execution_time = 1, timeout_overflow_mode = 'break' starved by a higher priority query waited until the other query ended (measured 27 s; master returns after 1 s, its analysis is not scheduled). With the poll, the registration of the allocation in QueryStatus is no longer needed, so the ProcessList changes are reverted. The test drops the "KILL after a failed replace" case: replace_running_query now stops the starved analysis itself. It gains a starved case with a BREAK time limit, and the hog also ignores the max_bytes_to_read of the CI profile. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Separate MASTER THREAD and WORKER THREAD resources make every lease not parkable; mergeTreeAnalyzeIndexes in a one-slot workload then hangs unless the executor publishes its lease also when it cannot be parked. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done in 4636bec: |
On the `s3 storage` CI legs the test failed deterministically: the in-part preemption lines printed `0 1` instead of `1 1` (the primary key case on `big`, the skip index case on `bs`), and the accounting line printed 0 in 1 of 25 local runs on an s3-backed server. Both come from object storage, not from the analysis: - Every read of the cached S3 disk parks the analysis lease (`CachedOnDiskReadBufferFromFile`, `AsynchronousBoundedReadBuffer`). Each park finishes or cancels the pending request and the unpark requests a new quantum, so `requested_ns` runs ahead of `consumed_ns` and a thread capped by `max_cpus` is never preempted (ClickHouse#126133). On an s3-backed server the skip index case parked 79 times and ran 129 ms of CPU in 129 ms with 0 preemptions; the same table with leases that cannot be parked (separate MASTER THREAD and WORKER THREAD resources), or on local disk with parkable leases, was preempted 9-10 times and took about 230 ms. - With randomized remote read settings the query spends about 5 s of CPU in the threadpool reader threads, which hold no lease, against 0.5 s on local disk, so the dequeued cost fell to 0.54 of the query CPU. `t`, `big` and `bs` now use `storage_policy = 'default'`. The tables of the one-slot and dictionary cases keep the default policy, so those cases still run on object storage in the s3 legs. Validation (debug build, randomized settings): on an s3-backed server (private MinIO, `cached_s3` policy) the previous test failed 1 of 3 runs and this one passed 30 of 30; on a local-disk server 20 of 20. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 65da937Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261109-043004 |
…ysis-cpu-lease # Conflicts: # src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
|
I ran this PR's test Same in both: the CPU of a multi-threaded analysis is reported to the workload, and plain Missing in #133869:
Missing here, present in #133869:
If you pick #133869, I'll close this PR. If you pick this one, I'll add the |
This should be done separately, we don't need to "implement everything" in one PR, besides I would prefer to wait for https://github.com/ClickHouse/clickhouse-private/issues/86950
I will check Also here I see some unrelated changes, that make sense to submit separately @serxa I will take a look which parts from this is useful, let's keep this as a draft for now @groeneai no action is required for you, if you are alone, you can put some emoji for this comment |
`mergeTreeAnalyzeIndexes` analyzes indexes on a thread of the pipeline executor, which already holds a CPU slot. The analysis took one more and hung in a workload with one CPU slot: the calling thread waited in `renew` (or in `acquire` with `cpu_slot_preemption` disabled) for the slot that it holds. `KILL QUERY` could not stop such a wait either. Now the workload scheduler always provides CPU leases to index analysis (`always_lease` of `allocateCPUSlots`): the calling thread gets one without a wait. The leases are not renewed, so no thread is preempted, and the CPU time is reported when a slot is released. A lease is published for `CPULeaseParkGuard` if parking is enabled. Reported in ClickHouse#130124 (comment) Co-Authored-By: Claude Fable 5.2 <[email protected]>
Closes: #88304
Related: #126572
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Index analysis of
MergeTreetables (primary key and skip indexes) now runs under the workload's preemptive CPU scheduling: its CPU is accounted to the query's workload and limited bymax_cpus,max_concurrent_threads, weights and priorities, its threads can be preempted, andKILL QUERY, the client's cancellation ormax_execution_timeend its wait for a CPU slot. Closes #88304.Description
With
CREATE RESOURCE cpu (MASTER THREAD, WORKER THREAD)andcpu_slot_preemption = 1onlyPipelineExecutorthreads hold a CPU lease. Index analysis runs while the plan is built, before any executor exists, so the scheduler never saw its CPU: a query spending its time infilterPartsByPrimaryKeyAndSkipIndexesignored its workload's limits.Change (option A from the design note on #88304): on a thread of the analysed query,
filterPartsByPrimaryKeyAndSkipIndexesruns on its ownCPULeaseAllocation. The query thread takes the master slot; a worker thread starts only for a granted slot; every thread renews its lease after each part and every 256 steps of the generic exclusion search, the per-mark skip-index loops, the top-K granule read and selection, and the disjunction merge, with no preemption timeout: a preempted thread waits for a grant; while waiting for a slot or the workers, the query thread polls the client's cancellation, the kill flag and the time limit; past a soft limit (timeout_overflow_mode = 'break') the analysis finishes without the allocation. A released slot now resumes a preempted thread of the same allocation. The coroutine-localCurrentCPULeaseduplicates a hunk of #126572.Not covered: analysis on a thread already running on a CPU lease (replica side of
distributed_index_analysis,loop(), delayed local plans), where a second allocation can hang a one-slot workload; a dictionary's source query (it runs in the waiting caller's thread group); one bulksetindex evaluation per part; the cross-part top-K merge; other planning CPU;cpu_slot_preemption = 0.Validation (debug build):
max_cpus = 2workload: CPU rate 3.9-4.7 -> 1.9-2.1, CPU reported to the workload 0.01 -> 0.92-1.03 of the query's; unlimited workload, median wall: 8 parts 0.96x / 0.97x, 64 parts 1.01x / 1.08x,mergeTreeAnalyzeIndexes0.97x; scheduler integration tests 21/21; the new test fails on master, passes 30/30 randomized runs.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/130124]