Skip to content

Run MergeTree index analysis under the workload's preemptive CPU scheduling - #130124

Draft
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/index-analysis-cpu-lease
Draft

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/index-analysis-cpu-lease

Conversation

@groeneai

@groeneai groeneai commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #88304
Related: #126572

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Index analysis of MergeTree tables (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 by max_cpus, max_concurrent_threads, weights and priorities, its threads can be preempted, and KILL QUERY, the client's cancellation or max_execution_time end its wait for a CPU slot. Closes #88304.

Description

With CREATE RESOURCE cpu (MASTER THREAD, WORKER THREAD) and cpu_slot_preemption = 1 only PipelineExecutor threads 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 in filterPartsByPrimaryKeyAndSkipIndexes ignored its workload's limits.

Change (option A from the design note on #88304): on a thread of the analysed query, filterPartsByPrimaryKeyAndSkipIndexes runs on its own CPULeaseAllocation. 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-local CurrentCPULease duplicates 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 bulk set index evaluation per part; the cross-part top-K merge; other planning CPU; cpu_slot_preemption = 0.

Validation (debug build): max_cpus = 2 workload: 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, mergeTreeAnalyzeIndexes 0.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]

groeneai and others added 2 commits November 7, 2026 22:53
…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]>
@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
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.

Finding Verdict Action
❌ A released slot did not resume a preempted thread of the same allocation AGREE CPULeaseAllocation::release resumes preempted threads; new gtest
❌ The top-K granule read and selection (incl. the tie drain) and the disjunction merge had no in-part renewal point AGREE in-part points added; the cross-part top-K merge is listed as not covered
❌ A lazy dictionary loaded for a dictGet runs in the caller's thread group, so its source query's analysis took slots of the caller's workload while the caller waited holding them (hang in a one-slot workload) AGREE allocate only on a thread of the analysed query; one-slot dictionary case in the test
❌ After a failed replace_running_query, KILL QUERY returned before freeing the analysis's allocation AGREE cancelQuery frees registered allocations also when the query is already killed; test case
⚠️ One bulk set index evaluation of a part (getPossibleGranules) has no renewal inside DISAGREE its CPU is reported at the part's renewal and kept in the consumed total, so max_cpus still holds over time; it is one vectorized step, the granularity at which executors are preempted too; a point inside needs a callback in a virtual index interface. Listed as not covered
⚠️ Waking the analysis from the replacement path itself DISAGREE the replacement runs under the ProcessList mutex, where cancellation work is not done (sendCancelToQueryImpl); a preempted executor thread is not woken by it either, and the replacing query waits at most replace_running_query_max_wait_ms
⚠️ No test showed that the skip-index loops renew inside a part; the preemption and one-slot oracles could pass when a random draw moved the work out of the analysis path AGREE one-part skip-index and top-K cases; every preemption case also asserts SelectedMarks; the one-slot set-index and projection cases force iv / pv
⚠️ Preemption thresholds measured on a debug build only AGREE analysis CPU of each case measured on a release build
💡 Separate test for the disjunction-merge point DISAGREE its loop cannot dominate the per-mark loop before it; same renewal helper as the tested points
💡 Test hang cleanup, analyzing spelling, a stale comment in test_scheduler_cpu_parking (the executor now publishes every lease) AGREE fixed
💡 The coroutine-local CurrentCPULease starts empty inside a stackful coroutine, so a Throttler sleep in an async remote read no longer parks the executor's lease (bounded sleep, no hang) AGREE noted, not changed: same design as #126572

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 8 parts x 1M rows, index_granularity = 1, filter on b: in a max_cpus = 2 workload master runs at 3.9-4.7 CPUs and reports 0.01 of its CPU to the workload (3/3 runs). The new test's accounting, one-part preemption (PK, skip index, top-K) and KILL checks fail on master every run; its one-slot dictionary load hangs the previous head every run; the new gtest fails without the release change every run.
b Root cause explained? Only PipelineExecutor creates a CPU lease, and index analysis runs while the plan is built, before any executor exists; its threads hold no slot, so the scheduler never sees, throttles or preempts that CPU.
c Fix matches root cause? Yes. On a thread of the analysed query, the analysis gets its own CPULeaseAllocation: master slot on the query thread, workers only for granted slots, renewal after each part and in-task every 256 steps inside every long per-part loop, freed by KILL QUERY through QueryStatus; a released slot resumes a preempted thread of the same allocation. No limit is widened, no work skipped.
d Test intent preserved / new tests added? New 05566_index_analysis_cpu_lease: accounting, preemption inside one part on the primary key, skip-index and top-K paths, five one-slot shapes without a hang (the set-index and projection shapes force their index / projection; one loads a dictionary whose source query has a long analysis), KILL of a starved analysis; three new gtests (preempted inside a task, woken by free, resumed by a released slot). Existing scheduler tests unchanged.
e Both directions demonstrated? New test: fails on master, the one-part checks fail with every in-part point removed, and the dictionary case hangs without the own-query check; passes 50/50 randomized runs on the fix. gtest: fails after 30 s without the release change, 200/200 with it. A/B: CPU rate 3.9-4.7 -> 1.9-2.1 with 21-26 preemptions; reported share 0.01 -> 0.92-1.03.
f Fix is general across code paths? All three callers of filterPartsByPrimaryKeyAndSkipIndexes (read step, projection candidates, local part of distributed index analysis) and every per-mark loop of the analysis (exclusion search, skip-index loops, top-K read, selection and tie drain, disjunction merge). Not covered, stated in the PR: an analysis on an executor thread, a dictionary's source query, one bulk set index evaluation per part, the cross-part top-K merge, other planning CPU, cpu_slot_preemption = 0.
g Fix generalizes across inputs (params/datatypes/wrappers)? 1 to 64 parts, max_threads 1 to 16, PK, minmax (exclusion, per mark, top-K with and without ties), set index with an IN subquery, projections, disjunctions, max_cpus, max_concurrent_threads, priorities; unlimited workloads: wall 0.96-0.97x (8 parts), 1.01-1.08x (64 parts), mergeTreeAnalyzeIndexes 0.97x. Type wrappers: N/A (no type-dependent code).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; without a CPU resource or with cpu_slot_preemption = 0 the existing code runs. By design a CPU-capped query's index analysis is now throttled.
i Invariants and contracts preserved? Every part's CPU is reported while the allocation is alive; a preempted thread holds no part; only the query thread starts workers; a released slot is handed to a preempted thread under the allocation mutex, as grants and parks already do, and not after free(); no lock is held at a renewal or spawn point; errors free the allocation and join the pool in a scope guard.

Session id: cron:clickhouse-impl-slot-41:20261107-222900

@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2466b94]

Summary: ✅


AI Review

Summary

The PR gives MergeTree index analysis a workload CPU lease, adds renewal points within parts, and services cancellation and deadlines while waiting for CPU slots or workers. One previously reported cancellation hang remains in the current code, so the verdict is to block. There are no new inline findings; author-resolved threads are left unchanged.

Missing context / blind spots
  • ⚠️ The current-head CI workflow is still RUNNING; the relevant stateless, scheduler unit, and integration jobs are pending. Completed results for those jobs would close the runtime-validation gap. No local tests were run because this review job has no ClickHouse binary.
Findings

❌ Blockers

  • src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp:1897–1900: The first client cancellation can still leave analysis waiting indefinitely. [dismissed by author -- https://github.com/Run MergeTree index analysis under the workload's preemptive CPU scheduling #130124#discussion_r4506220337] The callback's boolean result is still discarded, so the cancellation request does not release the analysis allocation.

    With partial_result_on_first_cancel = 1, TCPHandler::processCancel consumes the first Cancel packet and sets stop_read_return_partial_result; the interactive callback returns true without throwing or killing the query. poll_while_waiting ignores that result, and checkTimeLimit remains successful when no deadline has expired. If a higher-priority query holds the workload's only slot, neither the master lease wait nor the worker-join wait ends. The query retains its memory and table locks until another cancellation, an external KILL QUERY, or a CPU grant.

    Handle the callback's true result in the shared poll, releasing the allocation and propagating the requested stop, or explicitly make cancellation during planning terminate the query. The soft-deadline fix already handles its separate false result and is no longer a finding.

Tests
  • ⚠️ Extend 05566_index_analysis_cpu_lease with partial_result_on_first_cancel = 1: send one native client cancellation to a starved analysis and verify it finishes while the higher-priority query continues holding the slot. The existing cancellation case exercises only the throwing callback path.
Final Verdict

Status: ❌ Block

Handle the interactive callback's cancellation result and add the focused starvation regression. Obtain completed results from the relevant CI jobs.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 8, 2026
@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @shankar-iyer, could you review this and add the can be tested label so CI runs? Index analysis in filterPartsByPrimaryKeyAndSkipIndexes now runs on its own CPULeaseAllocation under preemptive workload CPU scheduling, renewing after each part and every 256 steps of the per-part index loops (exclusion search, skip-index marks, minmax top-K), so its CPU counts against the workload limits.

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... labels Nov 8, 2026
@shankar-iyer shankar-iyer self-assigned this Nov 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2466b949b with master ecc78fd5f (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.

Object file sizes

28 object files changed (+62.15 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp.o 1.26 MiB 1.29 MiB +37.59 KiB (+2.92%)
src/CMakeFiles/dbms.dir/Interpreters/WorkloadCPUScheduling.cpp.o new 24.94 KiB +24.94 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1661 translation units recompiled, 8385 s compile time in total, 1660 of them have a recent master baseline.

Job report

…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]>
@serxa serxa self-assigned this Nov 8, 2026
@serxa

serxa commented Nov 8, 2026

Copy link
Copy Markdown
Member

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?

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

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 on_preempt / on_resume. Plain renew() stops a preempted worker after cpu_slot_preemption_timeout_ms.

You are right that this needs no new interface. The analysis allocation has its own CPULeaseSettings without on_preempt / on_resume, and those two callbacks plus the worker timeout are the only things in_task changes in renew / waitForGrant. With preemption_timeout = max on that allocation the existing renew() already does what renewInTask does, so a separate class is not needed either. I'm changing the PR to that: in_task, ISlotLease::renewInTask and renewCurrentCPULeaseInTask go away, and the in-part points call renew() on the analysis's own lease. The one behaviour difference: a worker preempted between parts waits for a grant instead of exiting after the timeout. It holds no part, and release() hands it the next freed slot.

What stays in CPULeaseAllocation:

  • release() resumes a preempted thread (3 lines). The analysis releases slots while its other threads may be preempted; without this they wait for a new grant while the allocation holds an idle slot, which hangs a workload whose slots are all held that way. Executors are not affected: they free() the allocation before their threads release slots.
  • on_master_wait: the query thread is the analysis master, and TCPHandler reads the client's Cancel packet on that same thread, so while it waits for a slot it has to keep polling it. Running the master on a pool thread instead cost 9-12% point-query QPS in my measurement. If you prefer a different shape for this, tell me which one.

groeneai and others added 3 commits November 8, 2026 16:45
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]>
@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

Done in 4636bec: in_task, ISlotLease::renewInTask and renewCurrentCPULeaseInTask are removed. The analysis allocation sets preemption_timeout = max, and the in-part points call renew() on the analysis lease. In 6c244cf the waiting query thread also checks the kill flag and the time limit, so the allocation no longer needs registering in QueryStatus, and the ProcessList changes are gone. In CPULeaseAllocation only two changes remain: release() resumes a preempted thread, and on_master_wait.

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]>
@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 65da937

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Logical error: Inconsistent KeyCondition behavior (STID: 5182-728c) logical error, not from this PR (it only adds CPU lease renewal points to index analysis, KeyCondition is unchanged): intDiv(a, toInt8(-2)) < 100 over a Nullable(Int128) key ORDER BY (b DESC, a DESC) holding NULLs aborts the same way on master 7b5f2bf (debug build), a decreasing function of a Nullable key #124111 (mine, open)
PR / Mergeable Check praktika rollups of the row above #124111 (the owner above)

Session id: cron:our-pr-ci-monitor:20261109-043004

…ysis-cpu-lease

# Conflicts:
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
@serxa

serxa commented Nov 24, 2026

Copy link
Copy Markdown
Member

@groeneai please check #133869

I think we need either this PR or PR from @azat. Highlight the difference here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I ran this PR's test 05566_index_analysis_cpu_lease (timeouts cut to 60 s) against #133869 (4cd189b) applied to the same master as this PR (c9994aa, debug build), with a master snapshot as the baseline where it matters.

Same in both: the CPU of a multi-threaded analysis is reported to the workload, and plain SELECT, a set index, a projection and a dictionary source do not hang in a one-slot workload.

Missing in #133869:

  • An analysis waiting for a CPU slot cannot be stopped. With a higher-priority query holding the only slot, KILL QUERY, replace_running_query, Ctrl-C and max_execution_time = 1, timeout_overflow_mode = 'break' had no effect: the four queries ended 90-240 s later, when the analysis got a slot again (three of them only when the higher-priority query was killed). The query thread waits in CPULeaseAllocation::waitForGrant without a timeout and polls nothing. Here they stop within 0.5 s (break: 1.5 s), via on_master_wait.
  • mergeTreeAnalyzeIndexes, which distributed_index_analysis runs on the replicas, hangs in a max_concurrent_threads = 1 workload, with parkable and non-parkable leases (master and this PR: 0.3 s). The executor thread holds the only slot and its analysis waits for a second one: executeSingleThread -> MergeTreeAnalyzeIndexSource::generate -> filterPartsByPrimaryKeyAndSkipIndexes -> CPULeaseAllocation::renew -> waitForGrant. This PR does not allocate on a thread that already runs on a CPU lease.
  • No preemption inside a part, and no slot for a single-threaded analysis: renew() runs only between parts, and with one part or max_threads = 1 no slot is taken. The test's three one-part cases get 0 preemptions (here 10-41), and with max_threads = 1 only 2% of the query's CPU reaches the workload (here all of it).

Missing here, present in #133869:

  • ConcurrencyControl and the non-preemptive mode (cpu_slot_preemption = 0). This PR only covers the preemptive workload path, so 05838_index_analysis_concurrency_control fails here.
  • The statistics probe (hasFewerMarksToReadThan).
  • CPULeaseAllocation is unchanged there. This PR adds on_master_wait, and release() resuming a preempted thread (needed because a thread preempted inside a part waits without a timeout).
  • It is smaller: source +253/-200 against +344/-64 here (both move the allocation code out of PipelineExecutor).

If you pick #133869, I'll close this PR. If you pick this one, I'll add the ConcurrencyControl path and the statistics probe here.

@azat

azat commented Nov 24, 2026

Copy link
Copy Markdown
Member

An analysis waiting for a CPU slot cannot be stopped. With a higher-priority query holding the only slot, KILL QUERY, replace_running_query, Ctrl-C and max_execution_time = 1, timeout_overflow_mode = 'break' had no effect: the four queries ended 90-240 s later, when the analysis got a slot again (three of them only when the higher-priority query was killed). The query thread waits in CPULeaseAllocation::waitForGrant without a timeout and polls nothing. Here they stop within 0.5 s (break: 1.5 s), via on_master_wait.

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

mergeTreeAnalyzeIndexes, which distributed_index_analysis runs on the replicas, hangs in a max_concurrent_threads = 1 workload, with parkable and non-parkable leases (master and this PR: 0.3 s). The executor thread holds the only slot and its analysis waits for a second one: executeSingleThread -> MergeTreeAnalyzeIndexSource::generate -> filterPartsByPrimaryKeyAndSkipIndexes -> CPULeaseAllocation::renew -> waitForGrant. This PR does not allocate on a thread that already runs on a CPU lease.

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

@azat
azat marked this pull request as draft November 24, 2026 10:59
azat added a commit to azat/ClickHouse that referenced this pull request Nov 25, 2026
`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]>

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-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Workload] Preemptive CPU scheduling doesn't apply for index analysis

4 participants