Repository navigation
Query-aware scheduling: pluggable scheduler algorithms in a WORKLOAD - #116800
Conversation
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.
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
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`.
…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.
|
Workflow [PR], commit [758956c] Summary: ❌
AI ReviewSummaryThis PR adds pluggable per-workload query schedulers ( Findings
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 758956c.
Changed lines: Changed C/C++ lines covered: 510/551 (92.56%) · Uncovered code |
- 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.
- 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.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@groeneai One red on 758956c, unrelated to this PR: Please investigate the sequential timeout and provide a fix in a separate PR. If there is an existing tracking issue, link it here. |
|
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 |
`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]>
Related: #106405
Makes the time-shared workload leaf a hub of pluggable scheduling algorithms, selected by a new workload setting
scheduler(defaultfifo). 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(typerequest_queue, node namequeue) replacesFifoQueueas the workload leaf. It owns the cross-cutting concerns (mutex, budget,max_waiting_queries, counters, activation) and delegates ordering to a pluggableISchedulingAlgorithm:fifo— first-come-first-served (byte-for-byte the previous leaf behaviour).fair— weighted fair queueing (Start-time Fair Queueing). Per-queryweightsets 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 (usefairwhen a no-starvation guarantee is needed).priority— strict priority by the query'sworkload_prioritysetting (Int64, lower value means higher priority;0is neutral, negatives outrank it), FIFO within a priority.setScheduler()swaps the algorithm in place on aCREATE OR REPLACE WORKLOADthat changesscheduler, migrating pending requests — no hierarchy rebuild,ResourceLinkunchanged, no requests lost. Per-query identity/state lives in aResourceSchedulingContextthat the workload classifier creates from the query's scheduling settings and stamps onto everyResourceLink, so eachResourceRequestcarries 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 theISchedulerQueueinterface, andsystem.schedulerreports 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 defaultfifoscheduler 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 withcpu_slot_preemption=1, R=5 rounds/point (mean, Welch's t):fifo/fair/lasat every N (peak ~41 q/s at N=8; ~38–39 saturated at N=16/32), p50 identical.lasadds p99 tail variance under heavy contention (N=32 p99 ≈ 1257 ms vs ≈ 854 ms forfifo/fair) — its re-leveling costs something when all jobs are equal and nothing rewards it.COUNT(DISTINCT …)+ a light interactive query): at mild contention the three are indistinguishable; under deep contention (workloadmax_concurrent_threads=8)lasdiverts service to the low-attained (light) query — light throughput +11% / heavy −27% vsfifo— whilefair≈fifoat equal weights. The intended least-attained-service trade-off.Scheduler request path —
gtest_scheduler_perf(included;SCHED_PERF_STRESS=1) drives a realWorkloadResourceManager(one resource + its scheduler thread, oneallworkload) with 32 threads issuing requests in a closed loop, measuring raw grants/s. 36-core box, release, 10 rounds, mean ± sd (thousand grants/s):fifofairlaspriorityfifo'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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added query-aware scheduling in workloads: a new
schedulerworkload 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), orpriority(by the queryworkload_prioritysetting). Thetypeof the workload leaf node insystem.scheduleris nowrequest_queueinstead offifo.Documentation entry for user-facing changes
workload-scheduling.mdx)Workflow [PR]
Sync PR [sync-upstream/pr/116800]
Version info
26.10.1.1688-master(included in26.10and later)