Skip to content

Query-aware scheduling: pluggable scheduler algorithms in a WORKLOAD - #116800

Merged
serxa merged 113 commits into
masterfrom
query-aware-scheduling
Oct 6, 2026
Merged

serxa merged 113 commits into
masterfrom
query-aware-scheduling

Conversation

@serxa

@serxa serxa commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

Related: #106405

Makes the time-shared workload leaf a hub of pluggable scheduling algorithms, selected by a new workload setting scheduler (default fifo). This lets the queries inside a workload be scheduled by different policies, while the workload hierarchy weight/priority still schedules between workloads.

The leaf class RequestQueue (type request_queue, node name queue) replaces FifoQueue as the workload leaf. It owns the cross-cutting concerns (mutex, budget, max_waiting_queries, counters, activation) and delegates ordering to a pluggable ISchedulingAlgorithm:

  • fifo — first-come-first-served (byte-for-byte the previous leaf behaviour).
  • fair — weighted fair queueing (Start-time Fair Queueing). Per-query weight sets the share; the weight can be lowered once a query crosses an age / attained-CPU / attained-IO threshold (weight_lowering_age_seconds, weight_lowering_cpu_seconds, weight_lowering_io_bytes, weight_lowering_factor), biasing scheduling toward shorter/newer queries without starving long ones.
  • las — least-attained-service, MLFQ-bucketed: serves the query that has consumed the least of the resource so far (a query drops one level each time its attained service doubles). Best mean latency for short queries under mixed workloads; can starve long queries (use fair when a no-starvation guarantee is needed).
  • priority — strict priority by the query's workload_priority setting (Int64, lower value means higher priority; 0 is neutral, negatives outrank it), FIFO within a priority.

setScheduler() swaps the algorithm in place on a CREATE OR REPLACE WORKLOAD that changes scheduler, migrating pending requests — no hierarchy rebuild, ResourceLink unchanged, no requests lost. Per-query identity/state lives in a ResourceSchedulingContext that the workload classifier creates from the query's scheduling settings and stamps onto every ResourceLink, so each ResourceRequest carries it — a request only reaches an accounting leaf through a classifier link, so the schedulers always have a context. WorkloadNodeTraits, ResourceLink, queue-limit updates, purge and queue length/cost introspection all go through the ISchedulerQueue interface, and system.scheduler reports the new queue type.

New query settings: weight, weight_lowering_factor, weight_lowering_age_seconds, weight_lowering_cpu_seconds, weight_lowering_io_bytes, workload_priority (all inert by default, so the default fifo scheduler is unaffected).

Design and discussion: RFC #106405.

Performance

Two angles — end-to-end query impact (ClickBench) and raw scheduler-thread request-path cost (an included microbenchmark). Takeaway: the algorithm is a fairness / tail-latency policy, not a throughput lever.

Query level — ClickBench hits (10M rows), 36-core box, release build, CPU workload with cpu_slot_preemption=1, R=5 rounds/point (mean, Welch's t):

  • Homogeneous load (same query, concurrency N=2..32): QPS within ~1% across fifo/fair/las at every N (peak ~41 q/s at N=8; ~38–39 saturated at N=16/32), p50 identical. las adds p99 tail variance under heavy contention (N=32 p99 ≈ 1257 ms vs ≈ 854 ms for fifo/fair) — its re-leveling costs something when all jobs are equal and nothing rewards it.
  • Mixed load (one saturating heavy COUNT(DISTINCT …) + a light interactive query): at mild contention the three are indistinguishable; under deep contention (workload max_concurrent_threads=8) las diverts service to the low-attained (light) query — light throughput +11% / heavy −27% vs fifo — while fair ≈ fifo at equal weights. The intended least-attained-service trade-off.

Scheduler request path — gtest_scheduler_perf (included; SCHED_PERF_STRESS=1) drives a real WorkloadResourceManager (one resource + its scheduler thread, one all workload) with 32 threads issuing requests in a closed loop, measuring raw grants/s. 36-core box, release, 10 rounds, mean ± sd (thousand grants/s):

load fifo fair las priority
cpu-lease-like (cost = 1) 550 ± 12 358 ± 4 359 ± 5 371 ± 6
io-like (cost = 1 MiB) 543 ± 1 360 ± 3 357 ± 4 358 ± 2

fifo's dequeue is a plain pop, so it runs ~1.5× the throughput of the query-aware algorithms (which maintain vruntime / attained-service level / priority order); even the slowest sustains ~350K grants/s — far above the request rate any real workload generates (e.g. a CPU lease re-arbitrates roughly once per 10 ms quantum), so the algorithm choice is not a throughput concern, consistent with the query-level result. Profiling the scheduler thread shows its cost is dominated by the per-grant consumer wakeup and the queue mutex, not the algorithm math (~3% of the thread).

Net: choosing the algorithm costs ~nothing in throughput/median; it changes fairness and tail behaviour under contention. fifo — lowest overhead + tightest tail on uniform load; las — protects short/interactive queries (at heavy-query throughput); fair — weight-proportional sharing.

Changelog category (leave one):

  • New Feature

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

Added query-aware scheduling in workloads: a new scheduler workload setting selects the algorithm used to schedule between the queries of a workload — fifo (default), fair (weighted fair queueing with per-query weights that can be lowered as a query runs), las (least-attained-service), or priority (by the query workload_priority setting). The type of the workload leaf node in system.scheduler is now request_queue instead of fifo.

Documentation entry for user-facing changes

  • Documentation is written (updated workload-scheduling.mdx)

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

Version info

  • Merged into: 26.10.1.1688-master (included in 26.10 and later)

Turn the time-shared workload leaf into a hub of pluggable scheduling
algorithms, selected by a new workload setting `scheduler` (default `fifo`).

The leaf class `RequestQueue` (getTypeName "request_queue", node name "queue")
replaces FifoQueue as the workload leaf. It owns the cross-cutting concerns
(mutex, budget, max_waiting_queries, counters, activation) and delegates ordering
to an ISchedulingAlgorithm strategy:

- `fifo`  - first-come-first-served (byte-for-byte the previous behaviour);
- `fair`  - weighted fair queueing (Start-time Fair Queueing) that can lower a
            query's weight as it runs.

`RequestQueue::setScheduler` swaps the algorithm in place, migrating all pending
requests, so a `CREATE OR REPLACE WORKLOAD` that changes `scheduler` neither
rebuilds the hierarchy nor invalidates the ResourceLink cached by classifiers and
loses no pending requests.

Per-query identity and scheduling state live in a `ResourceSchedulingContext`
(created per query on its ThreadGroup), carried by every ResourceRequest the query
emits (non-owning pointer, cleared on reset). It stores the query start time, its
weight settings, and per-resource attained cost and virtual runtime. Requests
without a context (background operations) are scheduled anonymously.

The `fair` scheduler consumes new query settings (all disabled by default, so the
default `fifo` scheduler is unaffected): `weight`, and threshold-based weight
lowering via `weight_lowering_age_seconds`, `weight_lowering_cpu_seconds`,
`weight_lowering_io_bytes` and `weight_lowering_factor` (the first threshold to
trip applies the full lowering; thresholds do not combine).

WorkloadNodeTraits, ResourceLink, queue-limit updates, purge and queue
length/cost introspection all go through the ISchedulerQueue interface, and
system.scheduler reports the new queue type. Adds unit tests for the fifo/fair
ordering, weight lowering, the scheduler swap, and the queue contracts, plus user
documentation for the `scheduler` and weight settings.
@mintlify

mintlify Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 4, 2026, 11:14 PM

Third scheduling algorithm for the RequestQueue hub: `las` serves the query that
has attained the least service in the resource first, bucketed into geometric MLFQ
levels (a query drops one level each time its attained service doubles). Lowest
level served first, FIFO within a level. Pure, per the design decision: no
starvation guard (a long query can be starved by a continuous stream of short
ones); `fair` remains the non-starving option. Selected by `scheduler = 'las'`.

The IO weight-lowering threshold (`weight_lowering_io_bytes`) counts read and write
attained independently (they are separate resources / leaves) and lowers the weight
when either crosses the single threshold.

Adds a unit test for the least-attained-service ordering and extends the
cancellation / max_waiting_queries contract tests to cover `las`; documents `las`.
@CLAassistant

CLAassistant commented Aug 28, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

…etting)

Fourth scheduling algorithm for the RequestQueue hub: `priority` serves requests
in strict order of the query's priority (lower value first), FIFO within the same
priority. It reuses the existing `priority` query setting (UInt64, 1 = highest,
larger = lower, 0 = no priority) rather than adding a new one — that setting
already means "query priority" and its value is now also used to order queries
inside a workload when `scheduler = 'priority'`. `priority = 0` (the default) and
requests without a query context are treated as lowest precedence, so the default
degrades to FIFO. Like any strict-priority policy it can starve low-priority
queries; `fair` remains the non-starving option.

The per-query `priority` is carried on ResourceSchedulingContext. Adds a unit test
for the strict-priority ordering and documents the `priority` scheduler.
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [758956c]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, azure, sequential) ERROR

AI Review

Summary

This PR adds pluggable per-workload query schedulers (fifo, fair, las, priority) to the RequestQueue leaf, wires the new per-query settings through the classifier/resource-link path, and adds solid tests/docs around the main design. I like the overall shape, but the current head still has one real fairness-accounting bug in the fair cancel/evict path, one live-reconfiguration bug when scheduler and max_waiting_queries change together, and the canonical session-settings reference docs were not regenerated, so I would not approve it yet.

Findings
  • ❌ Blockers
    • [src/Common/Scheduler/Nodes/TimeShared/RequestQueue.h:229] rollbackProjection only subtracts vruntime_increment. If a queued fair request already drained a positive fair.vruntime_correction, then cancelRequest / popWorst drops that request without restoring the drained debt, so the query escapes real service it already consumed. This is still reachable from CPULeaseAllocation::RequestChain::cancel and CPUSlotsAllocation::~CPUSlotsAllocation. Keep the correction pending until some request actually runs, or add it back in rollbackProjection.
  • ⚠️ Majors
    • [src/Common/Scheduler/Nodes/WorkloadNode.h:81] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/116800#discussion_r4169621736] updateQueueLimit still runs before setScheduler. A single CREATE OR REPLACE WORKLOAD that changes both scheduler and max_waiting_queries therefore trims the backlog with popWorst from the old algorithm and can reject a request that the final algorithm would have kept. Install the new algorithm first, or re-trim the backlog after the swap.
  • 💡 Nits
    • [src/Core/Settings.cpp:8399] The new user-visible query settings are declared here, but docs/reference/settings/session-settings/other.mdx still omits weight, workload_priority, and the weight_lowering_* settings. Please regenerate the session-settings reference from this source-of-truth change.
    • [src/Common/Scheduler/Workload/WorkloadEntityStorageBase.cpp:517] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/116800#discussion_r3890018348] A targeted scheduler = ... FOR <resource> clause on QUERY / MEMORY RESERVATION resources is still accepted even though WorkloadNodeTraits::schedulerFor always forces those leaves back to fifo, so the targeted override has no effect anywhere. The new stateless coverage at tests/queries/0_stateless/03232_workloads_and_resources.sql:78 now codifies that silent no-op. Either reject unsupported FOR <resource> targets in storeEntity, or document this behavior explicitly instead of accepting it silently.
Tests
  • ⚠️ gtest_request_queue still lacks a regression where a fair request drains vruntime_correction and is then canceled / evicted before it runs, and there is no focused test for one CREATE OR REPLACE WORKLOAD that changes both scheduler and max_waiting_queries. Those two tests would pin the remaining scheduler edge cases.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: fix the fair cancellation/eviction debt leak, make combined scheduler + max_waiting_queries updates trim under the final algorithm, and regenerate the session-settings reference docs. The FOR <resource> no-op is lower priority, but it should still be either rejected or documented before the feature is declared finished.

LLVM Coverage Report

Measured on commit 758956c.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 510/551 (92.56%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 29, 2026
- Mark the RequestQueue constructor explicit (google-explicit-constructor).
- Rewrite the test's dequeue-all loop without a C++26 structured binding in a
  while-condition (plain for loop; C++23 does not allow it).
- Move the new weight / weight_lowering_* query-setting history entries from the
  26.8 block to the current 26.9 block.
Comment thread src/Common/Scheduler/ResourceGuard.h Resolved
Comment thread src/Interpreters/ThreadStatusExt.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
- Fix the arm_tidy compile error: the gtest ResetClearsSchedulingState built a
  ResourceSchedulingContext with 6 args after the constructor gained a 7th
  (priority) argument.
- Restrict the scheduler setting to CPU/IO leaves. Non-IO/CPU time-shared leaves
  (e.g. QuerySlot admission, enqueued before the query context exists) carry no
  per-query context, so they now always run fifo instead of silently collapsing
  to anonymous FIFO, matching the documented CPU/IO-only scope.
- Inherit the parent per-query scheduling context in borrowed child thread groups
  (materialized views, EXPLAIN ANALYZE, async-insert-queue flush) so their CPU/IO
  requests are accounted to the same query rather than scheduled anonymously.
- Clamp weight_lowering_factor to [0, 1] so it can only lower a query's weight,
  never raise or zero it; document the range and add a unit test.
ResourceBudget::ask() rewrites request->cost queue-wide to smooth cost-estimation
error across the queue. Since the fair/las schedulers use request->cost as the
per-query scheduling currency (virtual runtime and attained service), that
queue-wide adjustment would let one query's estimation error bleed into another
query's fairness state. Capture the declared cost as request->scheduling_cost in
reset() (before any budget adjustment) and use it for the per-query
vruntime/attained-service accounting, while queue-level throughput stats keep
using the budget-adjusted cost. For queues without a budget the two are equal, so
behaviour is unchanged. Adds a regression gtest.
The scheduler setting reorders CPU/IO requests by per-query identity, so it only
applies to time-shared CPU/IO leaves (the QuerySlot leaf already falls back to
fifo). But a 'scheduler = ... FOR <resource>' clause targeting a QUERY or MEMORY
RESERVATION resource was still accepted and then silently ignored. Validate the
FOR-resource target's cost unit in storeEntity and throw BAD_ARGUMENTS for a
non-CPU/IO resource, so the misconfiguration surfaces instead of being a no-op.
Extends the workload DDL test and documents the rejection.
…oups

Following review: only genuinely same-query borrowed thread groups (materialized
views, EXPLAIN ANALYZE) inherit the parent's per-query scheduling context. An
async-insert-queue flush writes a batch aggregated from many independent inserts,
so attributing its IO to a single parent query's fair/las accounting would
over-charge that query; leave its scheduling context null so the flush IO is
scheduled anonymously.
A las request is keyed by levelOf(attained) at enqueue, but a query's attained
service grows as its other queued requests are served, so a waiting request's
stored level goes stale (too low) and would be served ahead of a genuinely
lower-attained query. This is the IO case (concurrent socket ops enqueue
independent requests); CPU (CPULeaseAllocation) has one request so is unaffected.

Since attained service only grows, the stored level can only be too low, so pop()
recomputes the front request's level from the query's current attained service and,
if it exceeds the stored level, re-keys the request to its true level and re-inserts
it before taking the next candidate (self-correcting on every pop). Churn is bounded
by the geometric levels. Adds a regression test.
The structured binding 'resource' in the scheduler FOR-resource DDL validation
loop shadowed the outer 'resource' (the ASTCreateResourceQuery* for the entity
being stored), tripping clang-diagnostic-shadow under -Werror (arm_tidy + Fast
test). Rename the binding to 'res_name'.
…t_queue)

The time-shared workload leaf is now a request_queue (was fifo), so the
system.scheduler integration tests that filter type = 'fifo' to find the leaf are
updated to request_queue, along with the system.scheduler doc example. Per review
this is NOT a backward-incompatible change: system.scheduler is a debug /
introspection table and ClickHouse does not guarantee system-table stability.
The priority query setting is a UInt64, but the priority scheduler stored it in
the double half of scheduling_key, losing ordering above 2^53 (e.g. 2^53 and
2^53+1 collapse to one key, so two distinct priorities fall back to FIFO). Keep
the priority in a dedicated UInt64 field (scheduling_priority) and order by
(priority, sequence) as integers, so ordering is exact across the whole setting
range. Adds a regression test.
…PU priority integration test

- Store the priority ordering key as the scheduler's Priority type (was a bare
  UInt64) for consistency with the rest of the scheduler; still an integer key, so
  it keeps the exact-ordering fix for large values.
- Mint a per-batch scheduling context for async-insert flushes from the flushed
  batch's settings bundle in createForFlushAsyncInsertQueue, so a flush's CPU/IO is
  scheduled under the workload/weight/priority the inserts specified instead of
  anonymously bypassing the query-aware schedulers. The batch is settings-
  homogeneous (async inserts are grouped by table/format/settings/identity), so one
  minted context is well-defined.
- Add an end-to-end integration test (test_scheduler_cpu) that runs higher- and
  lower-priority queries in one scheduler='priority' workload under CPU contention
  and checks the higher-priority ones complete more often, exercising the real
  request path (CurrentThread / ResourceGuard / ConcurrencyControl).
…t collisions

The previous mapping had two edge-case bugs: priority=0 and priority=INT64_MAX
both mapped to Priority{INT64_MAX} (collapsing to FIFO), and a UInt64 priority
above INT64_MAX wrapped to a negative (spuriously high-precedence) key via
static_cast. Now 'no priority' (0) maps to the max key and explicit priorities are
clamped into [1, INT64_MAX-1], so they always sort strictly ahead of 'no priority'
and can never wrap. Priorities beyond INT64_MAX are indistinguishable (the Priority
type is Int64, chosen for consistency), which is far beyond any realistic query
priority. Adds a regression test.
…orkloads

The FOR-resource unit check only ran in storeEntity (the SQL CREATE path), so a
workload defined via config or Keeper (loadEntities -> setLocalEntities, which
bypasses storeEntity) could still set scheduler = ... FOR <QUERY|MEMORY resource>
and have it silently coerced to fifo. Extract the check into a shared helper and
also run it in setLocalEntities over new/changed entities (alongside the existing
cost-unit-change check), so config/Keeper workloads are rejected the same way as
the SQL path. Only new/changed entities are checked, so a pre-existing entity is
not re-validated on every refresh.
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator

Confirmed: the diff is the first LIMIT 1 arm (1 instead of 0), one of the three arms #123815 pins to the local plan, and your new head 758956c already contains it.

@serxa

serxa commented Oct 5, 2026

Copy link
Copy Markdown
Member Author

@groeneai One red on 758956c, unrelated to this PR: Stateless tests (arm_asan_ubsan, azure, sequential) timed out (9000 s wall-clock limit) after running 1160/1164 tests without a single failure — the job was killed by SIGTERM at the end, no test actually failed. Example log: https://github.com/ClickHouse/ClickHouse/actions/runs/37241241022/job/111609322481

Please investigate the sequential timeout and provide a fix in a separate PR. If there is an existing tracking issue, link it here.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

Same capacity kill as the recent master runs: 1160 of 1164 tests ran, none failed, and the tests alone took 143 min of the 150 min budget (job.log). This sequential lane has slowly outgrown its timeout as new sequential tests were added.

The fix is #123849: it splits the lane into 2 hash batches (projected p99 about 88 min per batch on recent CIDB data). Its own CI has not run the new batches yet, because praktika skips them as not affected by a ci/defs-only diff; it needs the ci-force-all label for that.

@serxa
serxa added this pull request to the merge queue Oct 6, 2026
Merged via the queue into master with commit 9b89a34 Oct 6, 2026
147 of 149 checks passed
@serxa
serxa deleted the query-aware-scheduling branch October 6, 2026 17:14
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 6, 2026
ylw510 pushed a commit to ylw510/ClickHouse that referenced this pull request Oct 24, 2026
`IOSchedulingSettings` holds `ResourceLink`s whose raw pointers (`queue`,
`scheduling_context`, `scheduling_state`) are owned by the classifier that
produced them, which lives in the query `Context`. The settings are part of
`ReadSettings`/`WriteSettings`, which remote readers and writers copy and keep.
The filesystem cache hands the reader of a partially downloaded segment to the
background download queue, which keeps reading with it after the query ended,
so each read enqueued a request stamped with the freed per-query
`ResourceQueryState` (added by ClickHouse#116800) and the scheduler thread wrote into it
(ASan heap-use-after-free in `RequestQueue::dequeueRequest`).

`IOSchedulingSettings` now also holds the classifier, set together with the
links in `updateIOSchedulingSettingsImpl`, so every copy keeps what its links
point to alive. This is the ownership contract documented in
`WorkloadResourceManager.h`, applied where the links are copied into a value
type; the scheduler hot path (`ResourceLink`, `ResourceGuard`) is unchanged.

Closes ClickHouse#124305

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch was successfully deployed

1 active deployment
staging - docs — 758956c9 Deployed Oct 4, 2026 by mintlify[bot]
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-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants