Repository navigation
Implement FIFO admission queue with per-waiter wakeup for ProcessList - #115168
alexey-milovidov wants to merge 156 commits into
Conversation
…yield optimization Replace the legacy broadcast-condvar concurrency limiter in ProcessList with a FIFO admission queue using per-waiter condition variables. When all slots (max_concurrent_queries) are occupied, new queries join a deque and each waits on its own CV. On slot release the front waiter is woken directly via notify_one, eliminating thundering-herd overhead. Queries can release their admission slot early (at the same point as QuerySlot) so the slot is not held during query logging and response flushing. A connection-alive check runs periodically while waiting, cancelling queued queries whose clients have disconnected. Additionally, replace the busy-yield loop in ThreadPool worker startup with atomic wait/notify. Under heavy admission load the yield loop caused catastrophic context-switch amplification (25M vs 4M CS at 150 VU) because each sched_yield forced a full reschedule; atomic wait eliminates this entirely. New server settings: - enable_query_admission_queue (default true) — gate for the new path - admission_queue_alive_check_interval_ms (default 5000) — alive-check period New metrics: - CurrentMetric::QueryAdmissionQueueLength - ProfileEvent::QueryAdmissionQueueWaitMicroseconds
… mode-transition races
…ing fail-fast semantics
…ontrol # Conflicts: # src/Interpreters/ProcessList.cpp # src/Server/ArrowFlightHandler.cpp
…ontrol # Conflicts: # src/Server/PostgreSQLHandler.cpp
Workflow files in this branch were stale or had been deleted as a workaround for GitHub's workflow-scope check. Restoring them to match `master` so the PR diff no longer contains those unrelated changes.
…aster merge
The last merge from `master` (`fc0a3466016 Merge master to refresh
merge base`) accepted the master version of `PostgreSQLHandler.h` (which
no longer declares `should_init_system_tables` / `initializeSystemTables`
after the C# postgres client revert), but kept the PR side of
`PostgreSQLHandler.cpp` (which still calls them). The result builds
neither in `Fast test` nor in `Build (arm_tidy)`:
src/Server/PostgreSQLHandler.cpp:634:13: error: use of undeclared
identifier 'should_init_system_tables'
These references were not part of this PR — drop them so the diff is
limited to the FIFO admission queue.
CI report: #101099
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address review feedback on `ProcessList::releaseAdmissionSlotLocked`: the slot-transfer fast path previously handed off to a waiter whenever the queue was non-empty, regardless of the current `max_size`. If `max_concurrent_queries` was reduced at runtime while the queue was non-empty, every release transferred the slot instead of dropping `admission_running`, so the new (smaller) limit never took effect under sustained load. Now, when we are over the current limit (`admission_running > max_size`), we decrement instead of transferring. A later release that brings `admission_running` back to `max_size` will hand the slot to the front waiter as before. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`setMaxSize` updated only the limit, so waiters queued before the reload could be stranded: - When `max_size` is reloaded to `0` (unlimited), `releaseAdmissionSlotLocked` decrements (`admission_running > max_size` branch) instead of transferring to a waiter, and new queries bypass admission entirely because `needs_admission = max_size && ...`. Existing waiters then wait until their `queue_max_wait_ms` timeout. - When `max_size` is raised from `N` to `M > N`, freshly arrived queries observe `admission_running < max_size` and take the fast path past the already-queued waiters, breaking FIFO and again leaving waiters until timeout. Drain the queue inside `setMaxSize` while the new limit (or `0` for unlimited) admits more queries: pop the front waiter, increment `admission_running`, and notify the per-waiter `cv`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Cover the admission-queue behaviour when `max_concurrent_queries` changes at runtime while the queue is non-empty, as requested in review: - `test_runtime_unlimit_drains_admission_queue`: switching the limit to 0 (unlimited) must drain queued waiters via `ProcessList::setMaxSize` even though the running blockers keep holding their slots — exercising the drain path directly (the blockers never finish on their own within the test, so the drain is the only way the waiters can complete). - `test_runtime_increase_preserves_fifo`: raising the limit from 2 to 3 opens exactly one slot, which must go to the oldest queued waiter (FIFO), not a younger one. The reload is driven through the config file and applied by the background `ConfigReloader` thread, not via `SYSTEM RELOAD CONFIG`. `SYSTEM RELOAD CONFIG` is a regular query and is itself subject to admission control, so when the queue is full it would block in that very queue and could not relieve the pressure; the background reloader runs in a separate thread and is not gated by admission. `config_reload_interval_ms` is lowered in the test config so the change is applied quickly. Queue state is observed via the Prometheus `QueryAdmissionQueueLength` metric and `system.processes` (both bypass admission), and the limit transition is confirmed via `system.server_settings` while slots are free. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ontrol # Conflicts: # src/Server/PostgreSQLHandler.cpp
The rollback guard `admission_rollback` was dismissed right after `QueryStatus` was constructed, before any `ProcessListEntry` existed to take over releasing the admission slot. If `processes.emplace`, `CancellationChecker::appendTask`, the `Entry` construction, or a later map insertion threw (for example, on allocation failure), the `QueryStatus` was destroyed without releasing the slot (`~QueryStatus` does not touch it) and no `ProcessListEntry` existed yet, so `admission_running` stayed incremented forever. After enough such exceptions `max_concurrent_queries` would be effectively exhausted. Keep the rollback guard armed until the query is fully registered, and have the guard also clear `QueryStatus::holds_admission_slot` so that a `ProcessListEntry` destructed during unwinding does not release the same slot a second time. Addresses an unresolved review comment on `ProcessList.cpp`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The early `releaseAdmissionSlot` in `executeQuery` only covers the `executeQuery` overload that executes the pipeline itself. Protocols such as native TCP and Arrow Flight use the `BlockIO`-returning overload and rely on `BlockIO::onFinish` / `onException` / `onCancelOrConnectionLoss` to release the query slot via `BlockIO::releaseQuerySlot`. That path did not release the admission slot, so for those protocols the slot was held until `ProcessListEntry` destruction (including result delivery and `BlockIO` teardown) rather than at the same timing as `QuerySlot`, as the PR contract promises. Add `BlockIO::releaseAdmissionSlot`, mirroring `releaseQuerySlot`, and call it from every `BlockIO` release path. `QueryStatus::releaseAdmissionSlot` is idempotent, so this is safe alongside the early release in `executeQuery`. Addresses an unresolved review comment on `executeQuery.cpp`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The periodic alive-check loop in `ProcessList::insert` only verifies the connection while the waiter is still blocked (`!my_turn()`). If the releaser transferred the slot to a waiter between two periodic checks via `releaseAdmissionSlotLocked` (which sets `waiter.granted = true`), a client that disconnected in the meantime would be admitted and execute its query, violating the admission-queue contract that clients disconnected while waiting are cancelled before consuming a slot. Add a final `is_alive` check after the wait succeeds and before setting `got_admission_slot = true`. On failure it throws `QUERY_WAS_CANCELLED`; the existing `SCOPE_EXIT` releases the already-granted slot. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`clang-tidy` (`cppcoreguidelines-init-variables`, treated as error in the `arm_tidy` build) flagged the peek buffer `b` in `makeSocketAliveCheckCallback` as uninitialized. Initialize it to `0`. CI report: #101099 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The admission slot is released early in `executeQuery` (same timing as the resource-scheduler `QuerySlot`), before the finishing query's `ProcessListEntry` destructor decrements `non_internal_processes` and the per-user counter. With the FIFO admission queue enabled and `max_concurrent_queries_for_all_users` (or `max_concurrent_queries_for_user`) equal to `max_concurrent_queries`, a waiter that just received the transferred admission slot could reach the secondary-limit check while the finishing query was still counted and be rejected with `TOO_MANY_SIMULTANEOUS_QUERIES`, whereas the legacy `max_size` path keeps such a query waiting and then runs it. When the query holds an admission slot, wait on `query_finished` (notified by the `ProcessListEntry` destructor) for the in-flight teardown to drain, bounded by the same `queue_max_wait_ms` budget, instead of throwing immediately. The common case where the secondary limit is not binding is unaffected, preserving the early-release latency benefit. Adds `test_secondary_limit_not_rejected_on_early_release`. CI report: #101099 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
When the FIFO admission queue is enabled, a finishing query releases its admission slot early in `executeQuery` (same timing as the resource-scheduler `QuerySlot`), before its `ProcessListEntry` destructor decrements `non_internal_processes` and the per-user counter. A waiter that just received the transferred slot then reaches the `max_concurrent_queries_for_all_users` / `max_concurrent_queries_for_user` checks while the finishing query is still counted. The previous fix made those checks wait on `query_finished` for the teardown to drain, but gated the wait on `queue_max_wait_ms` directly. With the default `queue_max_wait_ms = 0` — which the FIFO admission wait treats as "fall back to `max_execution_time`, then 300s" — the `!queue_max_wait_ms` term short-circuited the condition and threw `TOO_MANY_SIMULTANEOUS_QUERIES` immediately, rejecting a waiter that legitimately held an admission slot. Compute the effective admission budget once up front and derive a single `admission_deadline`. The FIFO admission wait and both post-handoff secondary-limit waits now share that deadline, so the total time a query can spend in `insert` is bounded by the effective budget regardless of how many of these waits it passes through, and the default `queue_max_wait_ms = 0` path waits out the early-release window instead of failing a just-admitted waiter. The legacy (admission-queue-disabled) path is unchanged: without a transferred slot it still uses `queue_max_wait_ms`. Add `test_secondary_limit_not_rejected_on_early_release_default_wait` covering the default `queue_max_wait_ms = 0` path that the existing regression test (which sets `queue_max_wait_ms = 60000`) did not exercise. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The UBSan stateless tests reported `signed integer overflow` at
`ProcessList::insert`:
runtime error: signed integer overflow: 9223372041000 * 1000000
cannot be represented in type 'long long'
src/Interpreters/ProcessList.cpp:178
`effective_wait_ms` is derived from the user-controllable settings
`queue_max_wait_ms` / `max_execution_time`, which fuzzing can set to
enormous values. Computing `steady_clock::now() + milliseconds(effective_wait_ms)`
converts the duration to nanoseconds (multiplying by `1'000'000`), which
overflows `int64_t` for waits beyond ~292 years — undefined behavior that
aborts under UBSan ("Server died"). The deadline is computed unconditionally,
so this triggered even on the legacy admission path where the admission queue
is disabled.
Clamp `effective_wait_ms` to ~100 years, which is effectively infinite for an
admission wait, so the deadline arithmetic and the `wait_until` calls below can
never overflow.
CI report: #101099
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `max_concurrent_select_queries` / `max_concurrent_insert_queries` checks suffered from the same early-release window already fixed for the `max_concurrent_queries_for_all_users` / `max_concurrent_queries_for_user` secondary limits. When a finishing query hands its admission slot to a FIFO waiter, the slot is released in `executeQuery` before the finishing query's `ProcessListEntry` destructor decrements `query_kind_amounts`. A just-admitted waiter then reaches the query-kind check while the previous query is still counted, and is rejected with `TOO_MANY_SIMULTANEOUS_QUERIES` even though legacy admission would have kept it waiting on the `max_size` gate until the counter dropped. Make the query-kind checks follow the same behavior as the secondary limits: when holding an admission slot, wait on `query_finished` for the in-flight teardown to drain, bounded by the shared `admission_deadline`. Without an admission slot (admission queue disabled) the check stays immediate, preserving prior behavior. Addresses review feedback on #101099 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rain A query holding an admission slot that hit a full secondary limit (`max_concurrent_select_queries`, `max_concurrent_queries_for_user`, ...) parked on `query_finished` until the shared admission deadline while still holding a global admission slot, so a query of a different kind/user arriving meanwhile had to queue even though an execution slot was actually idle. The post-handoff wait exists only to cover the early-release window: a finishing query frees its admission slot in `executeQuery` before its `ProcessListEntry` destructor decrements the secondary counters, so a just-admitted query (transferred slot or fast path) can observe it as still counted. Track that window explicitly (`admission_pending_teardowns`) and wait only until it drains: if the limit is still full once no early-released teardown is in flight, it is genuinely full of running queries, and the query is rejected immediately (the rollback guard hands its slot to the next waiter) instead of hoarding the slot until the deadline. Add a regression test where a fast-path query rejected at the per-user limit must not delay a different user's query, and the rejection must be immediate. Co-Authored-By: Claude Fable 5 <[email protected]>
The secondary-limit checks in `ProcessList::insert` wait out the admission early-release teardown window before rejecting, so that a query holding an admission slot is not spuriously rejected on a transient overcount. That wait was bounded by a single global counter `admission_pending_teardowns`, which counts early-released-but-not-yet-destroyed queries of any kind and any user. As a result, an unrelated teardown could keep a query parked at a secondary limit while it hoarded a global admission slot: e.g. with `max_concurrent_queries = 2`, user A's `max_concurrent_queries_for_user = 1`, A1 running, user B finishing (its teardown still in flight), A2 takes the fast path, hits A's per-user limit, and waits because the global teardown counter is nonzero — even though B's teardown cannot decrement A's per-user counter. A third user C then queues although an execution slot is actually idle. Scope the teardown-drain wait to the counter under test: per-query-kind (`query_kind_pending_teardowns`) for `max_insert_queries_amount` / `max_select_queries_amount`, per-user (`ProcessListForUser::admission_pending_teardowns`) for `max_concurrent_queries_for_user`, and the global `admission_pending_teardowns` only for `max_concurrent_queries_for_all_users` (which tests the global `non_internal_processes`). Only a teardown of the same kind/user can decrement the relevant counter, so this is a strict tightening of the previous wait: it cannot introduce spurious rejections the broad condition avoided, and it removes the unrelated-teardown slot hoarding. The counters are maintained symmetrically in `increaseAdmissionPendingTeardowns` / `decreaseAdmissionPendingTeardowns`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Follow-up to the early-release teardown-drain bound (commit `bbe02a8e901`): the `passes_secondary_limit` wait parked a query holding an admission slot while *any* same-scope early-release teardown was in flight, even when draining those teardowns could not bring the counter below the limit. A query arriving with a stricter incoming `max_concurrent_queries_for_user` (or query-kind) limit could then take a global admission slot, park behind a single same-user/kind teardown that still left the counter at the limit, and force unrelated users/kinds into the admission queue while it was not executing — for the whole teardown window (which can be long, e.g. a slow client still receiving results). A completing teardown decrements both the live counter and its pending-teardown count under the same lock (see `~ProcessListEntry`), so `current - pending` — the genuinely running, not-early-released queries of the scope — is invariant as teardowns drain. Wait only while `current - pending < limit` (written `current < limit + pending` to avoid unsigned underflow), i.e. while draining the relevant teardowns can actually make the limit pass; otherwise the limit is full of running queries that no teardown will clear, so reject immediately and let the rollback guard hand the admission slot to the next FIFO waiter. Addresses the `clickhouse-gh` review thread on `ProcessList.cpp`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
🕵 Merged
|
|
🕵 Merged
|
|
🕵 Merged The only red job on @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115168&sha=e2768dd0dcbeb63e53684daf6e231bac211051b9&name_0=PR&name_1=AST%20fuzzer%20(amd_release%2C%20oracle) and provide a fix in a separate PR. If the fix is already in progress (likely #130272), link it here. |
|
The fix is my open #130272. With On its current head both release builds never ran (CI dispatch problem), so its release-build jobs, including this AST fuzzer job, have no result yet and need a re-run. The other four PRs hit a different bug: TLP mismatches where |
|
🕵 Merged The only red check on |
# Conflicts: # src/Interpreters/ProcessList.cpp
|
🕵 Merged The two red jobs on
|
|
🕵 Merged The only red jobs on |
…Info` messages `ByteSizeLong` measures only the serialized contents, but the protobuf parser keeps the capacity of a singular string field overwritten by a later occurrence of the same field. A message with `input_data` set twice (first large, then small) had a tiny `ByteSizeLong` while retaining the large allocation, so a queued streaming query could make the server buffer unbounded memory. Charge `SpaceUsedLong` instead, store the cost with each buffered message, and add a regression case to `test_grpc_streaming_read_ahead_is_bounded_while_waiting_in_queue`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…fferFromPocoSocketChunked::loadNextChunk` `loadNextChunk` requested the rest of the 4-byte frame header with a single socket read and treated any short read as the end of the stream. After `appendWithoutWaiting` leaves the last byte of a chunk with `chunk_left = 1`, normal reading resumes through `loadNextChunk`, and if the end marker arrives in several fragments, the retained data was lost. Read until the header is complete, treating only a zero-byte read as the end of the stream. The focused test now resumes normal reading while the rest of the stream still arrives in small fragments. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Interpreters/ProcessList.h
Fixes the `modernize-use-nodiscard` clang-tidy error in the `arm_tidy` builds: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115168&sha=latest&name_0=PR&name_1=Build%20(arm_tidy%2C%204%2F4) Co-Authored-By: Claude Opus 5.5 <[email protected]>
`Call::startReadingQueryInfo` set the flag before `CallResponder::read`, which allocates the callback before submitting the gRPC `Read`. If that throws, no read is in flight and nothing would reset the flag, so `Call::close` would wait forever. Reset the flag and rethrow. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Server/MySQLHandler.cpp
After `stop` the accepts are not rearmed, so at most `CALL_MAX` responders can be retained in `cancelled_responders`. Reserve that capacity before accepting requests, so that retaining a responder in `onNewCall` does not allocate: an exception there would escape from `Runner::run` and leave the remaining calls without the thread which delivers their completion tags. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Conflict in `src/Server/ArrowFlight/ArrowFlightServer.cpp`: `master` replaced the `arrow::flight` server with its own protocol layer, so the handlers no longer receive the call context. The file is taken from `master`, and the admission queue liveness check is re-applied on top of it: `ArrowFlightServer::handleCall` stores a callback based on `grpc::ServerContext::IsCancelled` in `AuthMiddleware`, and every query context made for a call gets it through `Context::setConnectionAliveCheck`. `pollFlightInfo` drops the callback once the query is admitted, because the query context outlives the call. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ion-queue thread `grpc::Server::Shutdown` without a deadline waits until every call already matched by gRPC is released, including a call whose accept tag is still in the completion queue and has not reached `Runner::onNewCall`. Such a call is in neither `current_calls` nor `cancelled_responders`, so `Runner::stop` could enter `grpc::Server::Shutdown` while holding `Runner::mutex`, and the completion-queue thread, the only one able to cancel and release that call, blocked on the same mutex in `onNewCall`. `Runner::run` could likewise enter it on the completion-queue thread itself with an accept tag still queued. Now `Runner::stop` only sets `should_stop` and starts a dedicated thread for `grpc::Server::Shutdown`, without `Runner::mutex`. The completion-queue thread keeps finishing the current calls and cancelling the calls accepted meanwhile. The completion queue is shut down only after the server is shut down and there are no current calls or cancelled responders left, which is checked by the shutdown thread, by `run`, and by `onFinishCall`. `stop` still does not block, so the server can kill the unfinished queries afterwards. Co-Authored-By: Claude Fable 5.2 <[email protected]>
| protected: | ||
| /// Must be called by `start` before requesting the call. gRPC delivers the tag only for a call | ||
| /// which has actually started, so a responder that never got a call is destroyed freely. | ||
| void notifyWhenDone() { grpc_context.AsyncNotifyWhenDone(&on_done); } |
There was a problem hiding this comment.
[Blocker] Preserve started responders when accept dispatch fails
After a successful accept, Runner::onNewCall moves the started responder into a local at line 2230 and then calls makeResponderForNewCall at line 2243. That call allocates the next responder and its callback entries. If allocation throws, the local responder is destroyed while gRPC still owns the newly registered AsyncNotifyWhenDone tag pointing into it. The exception also exits the sole completion-queue loop, because its catch is outside run.
With another RPC waiting for a read, write, or done callback, that RPC can now remain in current_calls indefinitely and prevent graceful shutdown, including with enable_query_admission_queue = false. Reserving cancelled_responders handles the post-stop branch, but this normal accept path still has the same failure class; constructing/registering the Call and scheduling its worker can also throw before cleanup is established.
Please make the ownership transition exception-safe across these steps: retain and cancel any started responder until its done tag is drained, without allocating on the error path, and contain dispatch failures so the completion queue keeps processing other calls. A focused injected rearming/scheduling failure with another RPC active should verify that the other RPC and shutdown can finish.
Re-authors and updates #101099 by @amosbird, preserving its FIFO
ProcessListadmission queue and integrating it with currentmaster.This update resolves the actionable open review feedback:
replace_running_querywaits before it acquires an admission slot and observes client liveness, while Arrow Flight applies the cancellation callback toGetSessionOptionsand prepared-statement schema inference. The gRPCAsyncNotifyWhenDonelifecycle change remains a design decision explicitly reserved in the original review thread.Related: #101099
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add an optional FIFO admission queue for
ProcessList, with disconnect-aware waiting and per-waiter wakeups.Workflow [PR]
Sync PR [sync-upstream/pr/115168]