Repository navigation
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
dc7f371 to
fa3e2b4
Compare
|
Workflow [PR], commit [da8ae47] Summary: ❌
AI ReviewSummaryThis PR replaces the legacy broadcast admission path in Findings
Tests
Final VerdictChanges are much closer, but I would not approve this head yet because the admission-slot lifetime is still inconsistent around LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 393/439 (89.52%) · Uncovered code |
… mode-transition races
…ing fail-fast semantics
|
Hi @serxa, this PR is about resource management. Would appreciate your review when convenient. |
|
Thank you! Description sounds very good, but it will take some time for me to go through the code. Also I'd appreciate if as much code as possible would be reused by QuerySlot and this feature. Because this is basically the same thing, and it would be nice to have the same behaviour. You can improve QuerySlot implementation as necessary. |
|
The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix. |
|
The flaky test failures in this PR ( |
Split flaky check and targeted check into separate roles: Flaky check — runs only new/modified tests from the PR with thread fuzzer enabled. Tests run in parallel with themselves (shared queue) to ensure new tests are parallel-safe under randomized thread ordering. Targeted check — runs previously failed and coverage-relevant tests with per-worker partitioning (--no-self-parallel) so the same test never runs concurrently on multiple workers, avoiding conflicts on shared resources (hardcoded users, roles, settings profiles, etc.). Both use --test-runs 50. Changes: - Add --no-self-parallel flag to clickhouse-test: partitions tests by name hash so all copies go to the same worker - Flaky check: only changed tests, thread fuzzer, shared queue - Targeted check: relevant tests, no thread fuzzer, per-worker queues, 50 runs, single clickhouse-test invocation - Restore original thread fuzzer parameters (reverts reductions from 06c945a and 9790435) - Add amd_binary to flaky check, use AMD_LARGE for targeted debug - Targeted check uses --flaky-check --no-self-parallel PRs affected by tests running in parallel with themselves: #102015 #101093 #99653 #101503 #101108 #101884 #100746 #101447 #100941 #101099 #100203 #96130 #102038
Split flaky check and targeted check into separate roles: Flaky check — runs only new/modified tests from the PR with thread fuzzer enabled. Tests can run in parallel with themselves (shared queue) to ensure new tests are parallel-safe. Targeted check — runs previously failed and coverage-relevant tests with per-worker partitioning (--no-self-parallel) so the same test never runs concurrently on multiple workers, avoiding conflicts on shared resources (hardcoded users, roles, settings profiles, etc.). Both use --test-runs 50. Changes: - Add --no-self-parallel flag to clickhouse-test: partitions tests by name hash so all copies go to the same worker - Flaky check: only changed tests, thread fuzzer, shared queue - Targeted check: relevant tests, no thread fuzzer, per-worker partitioning, 50 runs, single clickhouse-test invocation - Restore original thread fuzzer parameters - Change targeted check to arm_asan_ubsan on ARM_LARGE PRs affected by tests running in parallel with themselves: #102015 #101093 #99653 #101503 #101108 #101884 #100746 #101447 #100941 #101099 #100203 #96130
…ontrol # Conflicts: # src/Interpreters/ProcessList.cpp # src/Server/ArrowFlightHandler.cpp
|
@groeneai, check failures of functions_prop_fuzzer and provide a fix. |
|
@alexey-milovidov — checked PR #101099 head
None of the three are related to PR #101099 (admission control / cc @yakov-olkhovskiy — heads up, your PR #103864 is the live fix for ~71 hits / 55 PRs of |
…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: ClickHouse#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]>
The previous fix made `QueryStatus::releaseAdmissionSlot` all-or-nothing by recording the pending teardown before clearing ownership, so a throwing `increaseAdmissionPendingTeardowns` left the slot owned for the destructor to release. That is not enough: `releaseAdmissionSlot` is also reached from `BlockIO::~BlockIO` (via `BlockIO::reset`), and `increaseAdmissionPendingTeardowns` could still allocate through `query_kind_pending_teardowns[query_kind]`. A `bad_alloc` thrown out of that destructor calls `std::terminate`; the same throw from `BlockIO::onFinish` aborts the finish path before the pipeline is finalized and the memory reservation is released. Fix: make the accounting genuinely non-throwing. `query_kind_pending_teardowns` is now grown in lockstep with `query_kind_amounts` in `increaseQueryKindAmount` (both maps only ever grow there and never erase keys, so they share one key set), which runs on the normal registration path where throwing is safe and handled by the `admission_rollback` guard. An admission slot is only ever held by a non-internal query (`is_unlimited_query = isUnlimitedQuery(ast) || is_internal`, and admission requires `!is_unlimited_query`), and such a query is always counted in `increaseQueryKindAmount`, so the per-kind key is guaranteed to exist by the time the query releases its slot. `increaseAdmissionPendingTeardowns` therefore looks the key up with `find` and only increments integer counters - no allocation, no throw - so `releaseAdmissionSlot` is safe in destructor and finish contexts. Addresses review: ClickHouse#101099 (comment) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A query that has already received an admission slot can still block in the secondary-limit `query_finished.wait_until` (`max_concurrent_queries_for_all_users` / `max_concurrent_queries_for_user` / `max_insert_queries_amount` / `max_select_queries_amount`), waiting for an early-released-but-not-yet-destroyed query to finish its teardown. That wait had no client-liveness check, so a client that disconnected while parked there kept holding `admission_running` until the teardown drained or the admission deadline expired - up to the 300s fallback - forcing other clients to queue behind an abandoned request. Fix: hoist the connection alive-check callback and its interval out of the FIFO admission block so the secondary-limit wait can use them too, and replace the single `wait_until` with the same periodic-chunk loop the FIFO wait uses. If the client disconnects, throw `QUERY_WAS_CANCELLED`; the `admission_rollback` guard then hands the slot to the next waiter. Reaching the deadline is not treated as an error here - the loop falls through to `under_limit()` so the caller still throws the precise `TOO_MANY_SIMULTANEOUS_QUERIES` message. When no alive-check callback is available (or checks are disabled), the behavior is unchanged. This reuses the existing socket-based disconnect detection (TCP/HTTP/MySQL/PostgreSQL); gRPC remains as discussed in the open thread. Addresses review: ClickHouse#101099 (comment) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous teardown-accounting fix moved the `query_kind_pending_teardowns` key creation into `increaseQueryKindAmount`, which runs during `ProcessList::insert` after the query is already registered in `processes` and the `non_internal_processes` / `query_kind_amounts` counters are incremented. The `admission_rollback` guard releases only the admission slot, so a `bad_alloc` from that `try_emplace` (or from `appendTask` / the `Entry` construction) left the query registered in `processes` with inflated concurrency counters and no owning `ProcessListEntry` to clean it up, so `system.processes` and the secondary-limit counters could stay inflated indefinitely. Fix it in two parts: - Pre-seed both `query_kind_amounts` and `query_kind_pending_teardowns` keys before the query is registered in `processes`. Both maps grow in lockstep and never erase keys, so seeding them before registration makes the subsequent `increaseQueryKindAmount` allocation-free; throwing during the pre-seed is safe because nothing has been registered yet. - Add a `registration_rollback` scope guard covering the window between `processes.emplace` and the `Entry` construction. If `appendTask` or the `Entry` allocation throws, it erases the `processes` entry and restores the counters; it is dismissed as soon as the `ProcessListEntry` takes ownership of the cleanup. This also closes the pre-existing leak on a throwing `appendTask`. Addresses the AI review blocker: ClickHouse#101099 (comment) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
|
||
| const auto replace_running_query_max_wait_ms = settings[Setting::replace_running_query_max_wait_ms].totalMilliseconds(); | ||
| if (!replace_running_query_max_wait_ms || !have_space.wait_for(lock, std::chrono::milliseconds(replace_running_query_max_wait_ms), | ||
| if (!replace_running_query_max_wait_ms || !query_finished.wait_for(lock, std::chrono::milliseconds(replace_running_query_max_wait_ms), |
There was a problem hiding this comment.
replace_running_query can now hoard a FIFO admission slot while it is only waiting for the old query id to disappear. Concrete trace with max_concurrent_queries = 2: a victim query V and an unrelated blocker B hold both slots, a replacement R with replace_running_query = 1 queues behind them, then B finishes and transfers its slot to R. R reaches this wait while V is still in user_process_list, so it can block for replace_running_query_max_wait_ms with admission_running still at 2. During that whole wait only V is actually executing, but an unrelated query C still queues or times out because the replacement is occupying the freed global slot. This regresses the legacy behavior where the replacement wait happened before the new query was counted against max_concurrent_queries. Please either perform the replace-running wait before claiming/transferring an admission slot, or release the slot and re-enter admission after the old query disappears; add a regression where a third query can use the freed slot while the replacement is waiting.
…ontrol # Conflicts: # src/Core/ServerSettings.cpp # src/Interpreters/executeQuery.cpp
…ailure The `registration_rollback` guard was released right after the `ProcessListEntry` was constructed, but the per-user registration (`user_process_list.queries` and `queries_to_user` maps, plus `non_internal_queries`) was populated *after* that release. A `bad_alloc` there left `~ProcessListEntry` unable to find the query (`std::terminate`), or decrementing `non_internal_queries` that was never incremented. Move the per-user registration before constructing the `ProcessListEntry`, inside the same rollback guard, so registration is complete and self-consistent by the time the `Entry` takes over cleanup. The map erases in the guard are idempotent (no-ops when the key was never inserted, so a partial registration rolls back exactly once), and `non_internal_queries` is only undone once it was actually incremented. Register the per-user query map with `query` directly instead of `res->getQueryStatus()` (they are the same `QueryStatusPtr`), so the population no longer depends on the constructed `Entry`. Addresses the review blocker on ClickHouse#101099 (comment) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed Merged latest
Addressed AI ❌ blocker #1 (registration exception-safety, #discussion_r3487701945) — AI ❌ blocker #2 left for a design decision ( CI on the previous head (
Fresh CI will run on the new head. |
The `enable_query_admission_queue` and `admission_queue_alive_check_interval_ms` server-setting descriptions were authored indented by four columns inside their `R"(...)"` literals. Markdown (as rendered by the `/docs` Web UI) turns a line indented by four or more columns and preceded by a blank line into a code block, so the paragraph "The value is clamped to `[500, 10000]` ms internally." in `admission_queue_alive_check_interval_ms` rendered as accidental code. This tripped the `04413_documentation_no_indented_lines` stateless test, which became visible on this branch after the latest merge from `master` brought the test in. De-indent both descriptions to column 0, matching every other setting in the file. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101099&sha=d2616ccac7ec935f20e8b2a8cb136508420a8ef6&name_0=PR&name_1=Fast%20test PR: ClickHouse#101099 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed Fixed the only real CI failure (Fast test → Unresolved threads recheck against current code:
|
|
The AST fuzzer finding Root cause: with the old analyzer, an |
…tration Two fixes after merging master: 1. `gtest_cancellation_checker.cpp`, added on master while this branch was behind, constructs `QueryStatus` directly. This branch adds the `holds_admission_slot_` constructor parameter, so the merged tree failed to compile in `Build (arm_tidy)` (the only build configuration that compiles this unit test without a cached object) with `no matching constructor for initialization of 'DB::QueryStatus'`. Pass `holds_admission_slot_ = false`. 2. Address review finding on `ProcessList.cpp:724`: `registration_rollback` did not undo a successful `CancellationChecker::appendTask`. If `appendTask` inserted the query into the checker's set and the following `std::make_shared<Entry>` threw, no `~ProcessListEntry` would ever run `appendDoneTasks`, so the checker kept the `QueryStatus` - and with it the acquired `QuerySlot` and `MemoryReservation` - alive until `max_execution_time` expired. The guard now calls `appendDoneTasks` when the registration reached that point. It runs under the same `ProcessList` mutex and `OvercommitTrackerBlockerInThread` that `appendTask` was called under, so the lock order is unchanged. The happy path is unaffected.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 386/432 (89.35%) · Uncovered code |
…wait time Addresses two AI review majors on the current head. `SYSTEM RELOAD CONFIG` is the documented way to raise `max_concurrent_queries` at runtime, but it went through the FIFO admission queue like any other query, so under a saturated limit it queued behind the very limit it was about to raise and the relief path was unavailable exactly when it was needed. It is now exempt from admission, in the same spirit as `KILL QUERY`, which `isUnlimitedQuery` already exempts. The exemption is scoped to the admission queue - an opt-in feature - so the legacy `max_concurrent_queries` path keeps its current behavior. `QueryAdmissionQueueWaitMicroseconds` was incremented only on the path where the slot was granted. A waiter that timed out or was cancelled left through one of the earlier throws and contributed zero, hiding exactly the overload cases that spend the most time queued. The increment now happens in a `SCOPE_EXIT`, so every queued exit path contributes. Both are covered by new cases in `test_fifo_admission_queue`: `test_reload_config_bypasses_admission_queue` runs `SYSTEM RELOAD CONFIG` while both slots are busy and checks that the raised limit admits the queued waiter, and `test_timed_out_waiter_records_wait_time` checks that a timed-out waiter grows the global counter by roughly its timeout. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
| UInt64 alive_check_interval_ms = 0; | ||
| if (admission_tracked) | ||
| { | ||
| is_alive = query_context->getConnectionAliveCheck(); |
There was a problem hiding this comment.
is_alive is threaded through the FIFO wait and the post-handoff secondary-limit waits, but the later replace_running_query wait still ignores it. If a replacement query receives an admission slot, reaches the duplicate-query_id wait at ProcessList.cpp:582, and the client disconnects before the old query disappears, admission_running stays occupied until replace_running_query_max_wait_ms expires. Unrelated queries then queue behind an abandoned replacement even though no second query is executing.
Please apply the same periodic alive-check loop here, or release and re-enter admission around this wait, so a disconnected replacer drops the slot immediately.
| auto query_context = session->makeQueryContext(); | ||
| query_context->setCurrentQueryId(""); /// Empty string means the query id will be autogenerated. | ||
| if (alive_check) | ||
| query_context->setConnectionAliveCheck(std::move(alive_check)); |
There was a problem hiding this comment.
This helper only makes queued Flight SQL requests disconnect-aware when the caller remembered to pass alive_check, but DoAction still has query paths that do not. GetSessionOptions calls executeSQLtoTable(session, "SELECT name, value FROM system.settings") without a callback at ArrowFlightServer.cpp:1448, and CreatePreparedStatement builds a fresh query_context / executeQuery pair without any setConnectionAliveCheck at ArrowFlightServer.cpp:1512 / 1539.
That means a Flight client that disconnects while either action is queued behind max_concurrent_queries will sit in the admission queue until timeout instead of being cancelled early, so the protocol-level disconnect contract is still incomplete. Please thread !context.is_cancelled() through those action paths as well.
|
🕵 Superseded by #115168. It re-authors the work onto current |
|
🕵 Closing in favor of #115168, which supersedes this conflicting fork PR. |
Split flaky check and targeted check into separate roles: Flaky check — runs only new/modified tests from the PR with thread fuzzer enabled. Tests run in parallel with themselves (shared queue) to ensure new tests are parallel-safe under randomized thread ordering. Targeted check — runs previously failed and coverage-relevant tests with per-worker partitioning (--no-self-parallel) so the same test never runs concurrently on multiple workers, avoiding conflicts on shared resources (hardcoded users, roles, settings profiles, etc.). Both use --test-runs 50. Changes: - Add --no-self-parallel flag to clickhouse-test: partitions tests by name hash so all copies go to the same worker - Flaky check: only changed tests, thread fuzzer, shared queue - Targeted check: relevant tests, no thread fuzzer, per-worker queues, 50 runs, single clickhouse-test invocation - Restore original thread fuzzer parameters (reverts reductions from 06c945a and 9790435) - Add amd_binary to flaky check, use AMD_LARGE for targeted debug - Targeted check uses --flaky-check --no-self-parallel PRs affected by tests running in parallel with themselves: ClickHouse#102015 ClickHouse#101093 ClickHouse#99653 ClickHouse#101503 ClickHouse#101108 ClickHouse#101884 ClickHouse#100746 ClickHouse#101447 ClickHouse#100941 ClickHouse#101099 ClickHouse#100203 ClickHouse#96130 ClickHouse#102038
Summary
This PR adds a FIFO admission queue to
ProcessListas an alternative to the existingcondvar-based admission (have_space→notify_all) and theQuerySlotresource scheduler. Whenenable_query_admission_queueis enabled, queries that exceedmax_concurrent_queriesenter a per-waiter FIFO queue instead of thundering-herdnotify_allwakeups or immediate rejection.Each waiter gets its own
std::condition_variable, so exactly one query is woken when a slot becomes available — O(1) wakeup with strict FIFO ordering. The queue includes a periodic alive-check that detects disconnected clients viaMSG_DONTWAIT | MSG_PEEKon the socket, preventing slot leaks from abandoned connections.As a secondary optimization,
ThreadPool::workerreplacessched_yieldspin in thePreparing→Runninghandshake withstd::atomic::wait/notify_one, eliminating a context-switch amplification loop that degraded throughput under high concurrency.Why not just use
CREATE RESOURCE ... (QUERY)/CREATE WORKLOAD?The resource scheduler's query slot mechanism achieves similar throughput and latency, but requires DDL setup (
CREATE RESOURCE,CREATE WORKLOAD). This PR simply extends the existingmax_concurrent_queries+queue_max_wait_msbehavior — one server setting to enable, no DDL needed. It also adds client disconnect detection and observable metrics (QueryAdmissionQueueLength,QueryAdmissionQueueWaitMicroseconds) out of the box.Changes:
enable_query_admission_queue(default false) andadmission_queue_alive_check_interval_ms(default 5000, clamped to [500, 10000])ProcessList::insertusingstd::deque<AdmissionWaiter>with per-waiterstd::condition_variableandnotify_oneQueryStatus::holds_admission_slottracks whether a query holds an admission slot, released inexecuteQuery(same timing asQuerySlot) or~ProcessListEntryreleaseAdmissionSlotLocked(Lock &)follows ClickHouse's lock-proof pattern (likeMergeTreeData::Transaction::commit(DataPartsLock &))SocketAliveCheck.h) registered per protocol handler (TCP, HTTP, MySQL, PostgreSQL, gRPC, Arrow Flight)QueryAdmissionQueueLengthand profile eventQueryAdmissionQueueWaitMicrosecondsThreadPool::workerusesstd::atomic::wait/notify_oneinstead ofsched_yieldfor thread startup handshakehave_spacerenamed toquery_finishedto reflect its actual semantics (not admission-specific)LockAndOverCommitTrackerBlockerinQueryStatus::releaseAdmissionSlotto prevent deadlock withOvercommitTrackerREPLACE RUNNING QUERY, no slot leak on timeout, client disconnect detection, wait-time profile event,max_execution_timefallback, and no-timeout-when-both-zeroBenchmark Results
Tested on a 96-core machine with k6 HTTP load testing, 5 scenarios, 3 rounds each with rotation for fairness. All three variants (FIFO, QuerySlot, Legacy) use the same binary — only server config differs.
Throughput (total iterations in 20s, avg of 3 rounds):
p95 Latency (avg of 3 rounds):
Tail spread (p95 - median, avg of 3 rounds):
FIFO matches
QuerySlotthroughput and latency across all scenarios while being significantly simpler to configure. Both dramatically outperform Legacy under contention — up to 65% higher throughput and 78% lower p95 latency at extreme bottleneck (500 concurrent connections, 10 slots).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add FIFO admission queue for
ProcessListwith per-waiter wakeup, configurable viaenable_query_admission_queueserver setting. Provides strict FIFO ordering, automatic client disconnect detection, and eliminates thundering-herd wakeups under high concurrency.Documentation entry for user-facing changes
New server settings:
enable_query_admission_queue(Bool, defaultfalse): When enabled, queries exceedingmax_concurrent_querieswait in a FIFO queue instead of being rejected. Requiresqueue_max_wait_ms > 0on the query side.admission_queue_alive_check_interval_ms(UInt64, default5000): Interval in milliseconds for checking if queued clients are still connected. Clamped to [500, 10000].New metric:
QueryAdmissionQueueLength— current number of queries waiting in the admission queue.New profile event:
QueryAdmissionQueueWaitMicroseconds— time spent waiting in the admission queue.Note
Medium Risk
Changes core query admission/concurrency paths in
ProcessListand adds early-release/disconnect checks across multiple protocol handlers, which could affect fairness, timeouts, or query lifecycle under load. Mitigated by being gated behind a new server setting and covered by new integration tests.Overview
Adds an optional FIFO query admission queue for
max_concurrent_queries(gated by new server settingenable_query_admission_queue) so excess queries wait in a per-waiter queue withnotify_onewakeups instead of the legacy broadcastcondvarpath.Introduces disconnect-aware waiting via a new per-query
Contextcallback (setConnectionAliveCheck) with a tunable server settingadmission_queue_alive_check_interval_ms, plus new observability (CurrentMetrics::QueryAdmissionQueueLengthandProfileEvents::QueryAdmissionQueueWaitMicroseconds) and early admission-slot release inexecuteQuery.Separately replaces a ThreadPool startup busy-yield with
std::atomic::wait/notify_one, and adds integration tests/config to validate FIFO ordering, timeouts/fallback behavior, replace-running-query interaction, disconnect cleanup, and metric/event reporting.Reviewed by Cursor Bugbot for commit fc0a346. Bugbot is set up for automated code reviews on this repo. Configure here.