Skip to content

Implement FIFO admission queue with per-waiter wakeup for ProcessList - #115168

Open
alexey-milovidov wants to merge 156 commits into
masterfrom
continue-pr-101099
Open

alexey-milovidov wants to merge 156 commits into
masterfrom
continue-pr-101099

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 17, 2026 •

Copy link
Copy Markdown
Member

Re-authors and updates #101099 by @amosbird, preserving its FIFO ProcessList admission queue and integrating it with current master.

This update resolves the actionable open review feedback: replace_running_query waits before it acquires an admission slot and observes client liveness, while Arrow Flight applies the cancellation callback to GetSessionOptions and prepared-statement schema inference. The gRPC AsyncNotifyWhenDone lifecycle change remains a design decision explicitly reserved in the original review thread.

Related: #101099

Changelog category (leave one):

  • Improvement

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]

amosbird and others added 30 commits March 30, 2026 01:32
…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
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (e73957fea74) and pushed f31200578fe. clickhouse builds.

  • Conflict in src/Server/GRPCServer.cpp: this PR moved BoolState earlier in the file, and master (Bound the waits of the gRPC fatal error callback on the signal listener thread #129608) added BoolState::waitFor to the old copy. I kept the single moved class and added waitFor to it.
  • Conflict in src/QueryPipeline/BlockIO.cpp: onCancelOrConnectionLoss now calls this PR's releaseAdmissionSlot and then master's new cancel_callbacks. Both run after the pipeline has been stopped.
  • CH Inc sync was the only red check. The last sync run (job 127407500333) was rejected as non-fast-forward for 12 PRs at once, and the private sync branch has no manual commits, so it looks like a race in the sync job rather than a conflict. The test_shutdown_cancels_queued_queries failures on the private sync PR are from an older head (b6168b0f); e6303d4e3188 already fixed them by creating node with stay_alive. This push starts a fresh sync.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (fedcee81b4c, clean merge, clickhouse builds) and pushed e2768dd0dcb.

  • Build profile diff on f31200578fe failed with LogClusterNotReady: the endpoint never became ready. That is a CI infrastructure failure: the job could not reach its log cluster and never compared anything. The new push reruns it.
  • CH Inc sync was Failed. Needs manual intervention: the sync branch had not taken a public head since c594f9fe37b (2026-10-31), because merging private master into it conflicted in BlockIO.cpp, GRPCServer.cpp and MySQLHandler.cpp. I rebuilt the sync merge as a fresh overlay of the PR's 47 files on private master. There were no conflicts. The previous sync's manual resolutions of SocketPeerClosed.{cpp,h} and its gtest were kept, with private master's Silk include rename applied. Per-file numstat against private master equals the public PR's numstat, except for those three files. A Cloud-mode -fsyntax-only of the touched translation units passes. The result, edd1a5d976d, is now on sync-upstream/pr/115168, and the sync PR is MERGEABLE.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (4faf44db0e6, clean merge; every translation unit this PR touches compiles) and pushed c63a8ba3172.

The only red job on e2768dd0dcb is AST fuzzer (amd_release, oracle): a query_plan_enable_optimizations oracle mismatch for SELECT count() FROM tab__fuzz_3 WHERE hasToken(name, 'HELLO'). That table has a text index with preprocessor = lower(name) on an ALIAS column (name LowCardinality(String) ALIAS ifNull(provider, ...)). This PR does not touch query planning or text indexes. The same kind of hasToken oracle mismatch has also shown up on unrelated PRs (#128433, #114142, #121230, #126862). The bug matches the open fix #130272 ("Fix text-search functions on an ALIAS column ignoring the text index preprocessor and tokenizer").

@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.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is my open #130272. With query_plan_enable_optimizations = 0 the Compute alias columns step stays below the filter as a separate step, and the text index optimization did not look through it, so hasToken(name, ...) was never matched to the index on name and its lower preprocessor was not applied (0 rows instead of 1). The same happens at default settings when the ALIAS column is read through a subquery. #130272 composes the steps below the filter before matching.

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 NOT hasToken over a text index on a Nullable column returns the NULL rows (#106922, open fix #113332).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (f9e6c60e784, clean merge; every translation unit this PR touches compiles) and pushed 901a415b3c0.

The only red check on c63a8ba3172 was CH Inc sync (tests failed): 05345_hash_join_row_store_strings in Stateless tests (amd_jemalloc_uaf, meta in keeper, s3 storage, parallel) failed with TOO_MANY_ROWS when its check query scanned system.text_log (more than 20 million rows read). That test does not exercise anything this PR changes. The open fix is #130490 (Filter system.text_log by event_time in tests). The new push re-syncs the private PR and runs its CI again. There are no unresolved review threads.

# Conflicts:
#	src/Interpreters/ProcessList.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (756f8bdeb19) and pushed d6c6107b564. There was one conflict in src/Interpreters/ProcessList.cpp, where this PR's isAdmissionExemptQuery and master's new isMetadataQuery were added at the same place, and I kept both. Master also split QueryStatus::watch into total_watch and execution_watch, so admission time is excluded from max_execution_time. That fits this PR, because the FIFO wait happens in ProcessList::insert before QueryStatus is built. Every translation unit this PR touches passes a syntax check.

The two red jobs on 901a415b3c0 are unrelated to this PR:

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (a33e1c1612b, clean merge; clickhouse builds) and pushed 8047ed5113b.

The only red jobs on d6c6107b564 were five Performance Comparison (arm_release, master_head, N/6) shards. None of them ran a test: performance test selection stopped with GitHub API 403 Client Error: rate limit exceeded while fetching sources through the GitHub contents API (job log). This is a CI infrastructure failure. It is being fixed in #131332, which makes test selection read sources from git instead. There are no unresolved review threads.

Comment thread src/Server/GRPCServer.cpp Resolved
alexey-milovidov and others added 3 commits November 16, 2026 10:22
…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
@clickhouse-gh clickhouse-gh Bot added comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 16, 2026
Comment thread src/Server/GRPCServer.cpp Resolved
alexey-milovidov and others added 3 commits November 19, 2026 07:42
`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
Comment thread src/Server/GRPCServer.cpp Resolved
alexey-milovidov and others added 2 commits November 21, 2026 21:55
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]>
Comment thread src/Server/GRPCServer.cpp Resolved
alexey-milovidov and others added 2 commits November 24, 2026 18:49
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]>
Comment thread src/Server/GRPCServer.cpp
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); }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants