Skip to content

Use CPU slots for index analysis threads - #133869

Open
azat wants to merge 1 commit into
ClickHouse:masterfrom
azat:index-analysis-concurrency-control
Open

azat wants to merge 1 commit into
ClickHouse:masterfrom
azat:index-analysis-concurrency-control

Conversation

@azat

@azat azat commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Use CPU slots for index analysis threads

Threads of max_threads_for_indexes now take CPU slots from ConcurrencyControl or the workload scheduler, like the pipeline executor (allocateCPUSlots, moved out of PipelineExecutor).


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

@azat
azat requested a review from serxa November 23, 2026 21:06
@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4cd189b]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) FAIL
05817_explain_analyze_join_runtime_filter FAIL cidb
Stress test (amd_debug) FAIL
S3_ERROR No such key thrown (see clickhouse-server.log or no_such_key_errors.txt) FAIL cidb
Performance Comparison (arm_release, master_head, 2/8) FAIL Performance dashboard
json_extract_rapidjson #7 FAIL dashboard
json_extract_rapidjson #8 FAIL dashboard
json_extract_rapidjson #12 FAIL dashboard
json_extract_rapidjson #3 FAIL dashboard
Performance Comparison (arm_release, master_head, 5/8) FAIL Performance dashboard
Insert historical data FAIL
Check Results FAIL
Performance Comparison (arm_release, master_head, 6/8) FAIL Performance dashboard
h3_polygon_to_cells #1 FAIL dashboard
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR shares CPU allocation with the pipeline executor and makes parallel index analysis acquire CPU slots from ConcurrencyControl or the workload scheduler. Review of commit 4cd189b02db51fb563f440e072d1d1d49eb2d2dc found two blocking liveness defects in workload scheduling: cancellation cannot interrupt a preempted analysis master, and reusable leases allow endless scheduling after work finishes.

Findings

❌ Blockers

  • MergeTreeDataSelectExecutor.cpp:213: A cancelled analysis can remain blocked indefinitely. CPULeaseAllocation::waitForGrant waits indefinitely for the master slot, but this local allocation has no cancellation registration or call to free. A busy higher-priority workload can therefore leave KILL QUERY ... SYNC waiting indefinitely during planning. Connect allocation waits to query cancellation and abort handling.
  • MergeTreeDataSelectExecutor.cpp:227: Completed work does not terminate the spawn loop. Released workload leases become acquirable again. If workers finish before the master resumes, this loop can repeatedly schedule empty workers, even after a callback sets stopped. Bound spawning by remaining parts and the stop condition. A standalone model using the exact helper exceeded 1000 jobs after two parts; early termination after one part reproduced the same behavior, while one-shot grants completed with one job.
Missing context / blind spots
  • ⚠️ No local ClickHouse build was available. Cancellation was verified by tracing QueryStatus::cancelQuery, ExecutorTasks::finish, and CPULeaseAllocation::waitForGrant. The scheduling model uses mocked allocations and a permitted worker-completion ordering; it is not a full server reproduction.
Tests
  • ⚠️ Add focused workload coverage for cancelling a preempted analysis and for completing finite/early-stop analysis with reusable leases. The new SQL test checks acquisition counters without exercising workload scheduling or these lifecycle paths.
  • ⚠️ The Performance Improvement claim has no supplied before/after measurements. Provide a focused throughput/latency comparison under concurrent index-heavy queries, including the idle-server overhead. The performance report helper could not retrieve measurements because clickhouse was unavailable in PATH.
Final Verdict

Status: ❌ Block

Fix cancellation and spawn-loop termination, add focused workload regression coverage, and provide evidence for the claimed performance improvement.

Threads of `max_threads_for_indexes` now take CPU slots from
`ConcurrencyControl` or the workload scheduler, like the pipeline
executor (`allocateCPUSlots`, moved out of `PipelineExecutor`).
@azat
azat force-pushed the index-analysis-concurrency-control branch from e060468 to 4cd189b Compare November 23, 2026 21:38
stopped.store(true, std::memory_order_relaxed);

/// May wait while the thread is preempted. Only a worker thread is downscaled, the master thread waits for a grant.
if (lease && !lease->renew())

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.

[Blocker] Make CPU lease waits cancellable during index analysis

With workload CPU scheduling, this can enter CPULeaseAllocation::waitForGrant, which waits indefinitely for slot 0. This local allocation is never connected to query cancellation, and nothing calls its free while the master is blocked. QueryStatus::cancelQuery only cancels registered executors; the analysis also runs during planning, before its pipeline executor exists.

For example, with a CPU resource covering MASTER THREAD and WORKER THREAD, max_concurrent_threads = 1, and a continuously busy higher-priority workload, a lower-priority multi-part analysis can exhaust its borrowed quantum and wait here indefinitely. KILL QUERY ... SYNC then cannot complete until the competing workload releases the CPU: setting the query's cancellation flag does not wake this wait. The existing pipeline path explicitly frees its allocation through ExecutorTasks::finish.

Connect this allocation's waits to query cancellation and abort handling, and add coverage for cancelling an analysis while its master lease is preempted.


auto start_threads = [&]
{
while (auto granted_slot = cpu_slots->tryAcquire())

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.

[Blocker] Stop spawning when no index work remains

CPULeaseAllocation::release returns a released slot to the same allocation through downscale, so tryAcquire can return that slot again. If a worker finishes before the master resumes this loop, the master schedules another worker, which immediately exits after finding no parts (or stopped == true) and returns the slot again. This loop checks neither remaining parts nor stopped, so that cycle can continue indefinitely after the analysis has finished. The master also never reaches its next cancellation check or lease renewal while spinning here.

A standalone scheduling model using this exact helper, with workers completing before the scheduling caller resumes, exceeded 1000 scheduled jobs after processing just two parts; returning false from the first part produced the same loop. One-shot grants completed with one scheduled job.

Bound spawning by unclaimed parts and the stop condition as well as available slots, and cover reusable workload leases with finite work and early termination.

@clickhouse-gh clickhouse-gh Bot added the comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... label Nov 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4cd189b02 with master 022011d08 (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

5 object files changed (+62.78 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/allocateCPUSlots.cpp.o new 53.87 KiB +53.87 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp.o 1.26 MiB 1.28 MiB +26.53 KiB (+2.06%)
src/CMakeFiles/dbms.dir/Processors/Executors/Runtime/V1/PipelineExecutor.cpp.o 200.94 KiB 183.32 KiB -17.62 KiB (-8.77%)

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

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

Job report

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

comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant