Skip to content

Fix CPU-slot acquisition latency and add ResourceRequest tracing (#11… - #120614

Draft
ankitxvx wants to merge 2 commits into
ClickHouse:masterfrom
ankitxvx:fix-cpu-slot-latency-118550
Draft

ankitxvx wants to merge 2 commits into
ClickHouse:masterfrom
ankitxvx:fix-cpu-slot-latency-118550

Conversation

@ankitxvx

@ankitxvx ankitxvx commented Sep 17, 2026 •

Copy link
Copy Markdown

Closes: #118550

Changelog category (leave one):

  • Performance Improvement

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

Reduce per-query CPU-slot acquisition latency under concurrency by pipelining in-flight resource requests in CPULeaseAllocation, add OpenTelemetry tracing for ResourceRequest lifecycle, and track ConcurrencyControlSlotsAcquiredNonCompeting events.


Detailed Description

1. Background & Problem

When running multi-threaded queries under concurrency with the Workload Resource Manager (cpu_slot_preemption enabled), queries previously experienced high CPU-slot acquisition latency during initial ramp-up.

Upon investigation, CPULeaseAllocation serialized resource requests through a strict 0-or-1 in-flight constraint (bool enqueued = false; in RequestChain). Acquiring $N$ CPU execution slots required $N$ sequential round-trips through the scheduler thread:

[Query Thread]                          [Scheduler Thread]
      |                                         |
      |-- 1. Enqueue Request #1 --------------->|
      |      (waits for grant)                  |-- Dequeues Request #1
      |<-- 2. Grants Slot #1 -------------------|
      |                                         |
      |-- 3. Enqueue Request #2 --------------->|
      |      (waits for grant)                  |-- Dequeues Request #2
      |<-- 4. Grants Slot #2 -------------------|
      |                  ...                    |

Under high query concurrency, this sequential "ping-pong" caused significant latency simply allocating threads for pipeline execution.

Additionally:

  • Individual ResourceRequest queue wait and grant durations lacked OpenTelemetry tracing.
  • ProfileEvents::ConcurrencyControlSlotsAcquiredNonCompeting was never incremented for CPULeaseAllocation, leaving the event counter at 0.

2. Key Changes

  1. Pipelined In-Flight Requests (RequestChain Refactoring):

    • Converted enqueued from a bool to size_t enqueued_count bounded by static constexpr size_t max_inflight_requests = 4;.
    • Separated single head iterator into next_enqueue and next_grant to manage a 3-region cyclic buffer:
      • [tail, next_grant): Granted / actively consuming slots
      • [next_grant, next_enqueue): In-flight requests pending in scheduler queues
      • [next_enqueue, tail): Free buffer slots
    • Updated constructor and setMax() to pipeline up to $K=4$ requests into the scheduler queue concurrently.
    • As each slot is granted by the scheduler thread, the next request is immediately enqueued, keeping the in-flight window saturated until current_max_slots is reached.
    • Preserved steady-state 1-by-1 renewal flow and cancellation semantics (cancel() drains all pending in-flight requests cleanly).
  2. OpenTelemetry Request Lifecycle Tracing:

    • Added enqueue_time_ns, grant_time_ns, and request_seq to Request.
    • Scheduler callbacks record grant timestamps with negligible overhead directly on the scheduler thread.
    • Emitted CPU_LEASE_REQUEST span upon grant with attributes:
      • workload, lease_id, request_seq, is_master, is_noncompeting, and wait_queue_us (microseconds spent waiting in queue).
    • Emitted CPU_LEASE_REQUEST_FINISH span in RequestChain::finish() when quantum consumption completes.
  3. Non-Competing Profile Event Accounting:

    • Added noncompeting_granted tracking in CPULeaseAllocation.
    • Incremented ProfileEvents::ConcurrencyControlSlotsAcquiredNonCompeting inside acquireImpl() when acquiring non-competing slots, matching CPUSlotsAllocation and ConcurrencyControl.

Verification & Testing

  • Verified state transitions and circular buffer invariants across enqueue, grant, finish, renew, setMax, and cancel.
  • Validated that allocated + enqueued_count <= current_max_slots <= max_threads holds in all branches.
  • Confirmed zero overhead when settings.trace_cpu_scheduling is false.

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

…ckHouse#118550)

- Pipeline in-flight CPU lease requests (up to K=4) during ramp-up and ceiling increases to eliminate serialized single-request round trips.
- Add OpenTelemetry spans (CPU_LEASE_REQUEST, CPU_LEASE_REQUEST_FINISH) with queue wait timestamps, sequence IDs, and slot types.
- Increment ProfileEvents::ConcurrencyControlSlotsAcquiredNonCompeting when noncompeting slots are acquired in CPULeaseAllocation.

Fixes ClickHouse#118550.
@CLAassistant

CLAassistant commented Sep 17, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh clickhouse-gh Bot added comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... external Author is not a member of the ClickHouse organization labels Sep 17, 2026
@serxa serxa mentioned this pull request Sep 19, 2026
24 of 33 tasks
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [846a83e]

Summary: ❌

job_name test_name status info comment
Style check FAIL
ruff FAIL cidb
Fast test FAIL
Build ClickHouse FAIL
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 19, 2026
// This code runs in the scheduler thread, so we have to keep it fast and simple
std::unique_lock lock{mutex};
requests.scheduled();
requests.recordGrantTime();

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 assumes the callback always belongs to next_grant, but CPULeaseAllocation explicitly supports different master_link and worker_link resources (PipelineExecutor mode 3 / the documented master_cpu + worker_cpu setup). Those are different scheduler queues and can execute out of order. Request::execute still only calls lease->grant() and does not identify itself, so if a worker request fires before the older master request, this code advances the wrong node. After that free()/cancel() can call cancelRequest(&*next_grant) on the wrong queue; FifoQueue::cancelRequest explicitly says cross-queue cancellation corrupts the intrusive list. Please thread the Request * through grant/failed (or keep separate in-flight state per queue) before allowing more than one request in flight.

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🔴 AI verdict: degradation — 1 query(s) regressed out of 36 analysed

Q1 on tpch_adapted_1_official shows +26.0% (median 50→63 ms), confirmed by both tests, with CPU time rising 110→178 ms. This PR rewrites the CPU-lease concurrency-control scheduler (CPULeaseAllocation), moving from a single enqueued request to up to 4 in-flight requests plus added grant-time bookkeeping and tracing hooks — all on the per-query execution path, so a regression here is plausible rather than off-target. That said, this query is intrinsically noisy and it is a very short query where scheduler overhead is proportionally largest, so the +13 ms delta warrants a confirmation run before treating it as a firm regression.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🔴 1 regressed

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 1 regression 50 63 +26.0% <0.0001 cpu: This PR reworks the CPU-lease scheduler (RequestChain now allows up to 4 in-flight requests and extra grant-path bookkeeping), which sits on the query-execution hot path, so a +26.0% shift on this fast query is plausible. The query is intrinsically noisy, so treat the magnitude with caution.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: bf0321f3-a5c8-458e-ab22-0c87eafe1a85
  • MIRAI run: 35b8d4fb-88c2-4ba7-a0bc-fcdc34a5f514
  • PR check IDs:
    • clickbench_934811_1789854788
    • clickbench_934817_1789854788
    • clickbench_934839_1789854789
    • tpch_adapted_1_official_934845_1789854789
    • tpch_adapted_1_official_934872_1789854789
    • tpch_adapted_1_official_934886_1789854789

…ouse#120614)

- Pass concrete Request* through execute() and failed() to identify the granted request.
- Add RequestState enum to manage circular buffer states (FREE, INFLIGHT, GRANTED, FAILED, CONSUMING).
- Buffer out-of-order grants and process them in-order from next_grant to maintain FIFO consumption.
- Fix RequestChain::cancel() to target INFLIGHT requests on their matching queue, avoiding intrusive list corruption in FifoQueue.
- Process buffered grants in free() before teardown to prevent scheduler constraint leaks.
- Add regression unit tests in gtest_workload_resource_manager and integration test in test_scheduler_cpu_preemptive.
@ankitxvx
ankitxvx marked this pull request as draft September 26, 2026 04:56

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... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Workload CPU scheduler: high per-query latency under concurrency from serialized slot acquisition

3 participants