Skip to content

Do not hold thread pool slots for idle QueryRunner tables - #114506

Closed
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:query-runner-no-idle-threads
Closed

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:query-runner-no-idle-threads

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Closes: #114367

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixes a QueryRunner table occupying threads global thread pool slots for its whole lifetime, even while completely idle. A few tables created with a large threads setting could exhaust the server's thread pool, after which every query failed with CANNOT_SCHEDULE_TASK until the tables were dropped. Queries are now scheduled on demand, so an idle table holds no threads. Closes #114367.

Description

CREATE TABLE ... ENGINE = QueryRunner SETTINGS threads = N started N worker threads immediately and kept them blocked on an empty queue until the table was dropped. A ThreadPool thread is itself a job on the global pool, so those workers held N global slots permanently, and threads is settable per table up to 1024 with no server-wide budget.

Measured on a table that received no inserts: GlobalThread goes from 2 to 1027 right after CREATE ... threads = 1024. Twelve such idle tables exceed the 10000-slot pool, the next ordinary query fails with Code: 439 ... no free thread (threads=10000, jobs=10000) (CANNOT_SCHEDULE_TASK), and the server does not recover until they are dropped. After this change the same script leaves QueryRunnerThreads at 0.

The dispatcher reimplemented a concurrency cap, a bounded queue and on-demand worker startup on top of ThreadPool, and that reimplementation is what broke thread reclamation. This deletes the private queue and the blocked-worker layer and submits each query to the pool directly, so the pool supplies all three. threads keeps its documented meaning and the capacity bound stays threads + max_queue_size. No new or changed settings.

In CI this surfaced as AST fuzzer (amd_debug, targeted, old_compatibility) failing with a bare Received signal 15 on any branch whose corpus reached 04337_query_runner.sql: report.

Thread pool occupancy is server-global, so the idle-table property and the reclamation of threads after real work are asserted in tests/integration/test_query_runner, which gets a server to itself. A new stateless test covers the reworked disposal paths on its own tables: a query refused at capacity, a query still queued at DROP, and a failing query leaving the table usable.

groeneai and others added 7 commits August 11, 2026 21:54
A QueryRunner table used to start its `threads` workers at CREATE and ATTACH
time and keep them blocked on an empty queue for the table's whole lifetime. A
ThreadPool worker thread is itself a job on the global pool, so those blocked
workers held `threads` global slots permanently, and `threads` is validated only
per table (range [1, 1024]) with no server-wide budget. Because the workers
never returned, the pool's idle-reclaim path was never reached.

Measured on a table that received no inserts: GlobalThread goes from 2 to 1027
right after CREATE ... threads = 1024. Twelve such idle tables exceed the
10000-slot pool, and the next ordinary query fails with

  Code: 439 ... no free thread (threads=10000, jobs=10000) (CANNOT_SCHEDULE_TASK)

after which the server does not recover until the tables are dropped. In CI this
surfaced as an AST fuzzer job failing with a bare "Received signal 15" on any
branch whose corpus reached 04337_query_runner.sql, because the fuzzer mutates
the `threads = 2` literal in that test.

The dispatcher was reimplementing, on top of ThreadPool, a concurrency cap, a
bounded work queue and on-demand worker startup, and that reimplementation is
what broke thread reclamation. Submit each query to the pool directly and delete
the private queue and the worker loop, so the pool supplies all three:
max_free_threads = 0 keeps no thread for an idle table, queue_size is the
saturating sum of `threads` and `max_queue_size` (which counts running plus
scheduled jobs, matching the previous total capacity), and
shutdown_on_exception = false keeps one failing user query from disabling the
table.

Completion accounting has to fire exactly once however the pool disposes of a
task: it may run it, refuse it, dequeue it unrun at shutdown, or destroy the
copy it makes of the task. A shared, non-copyable completion state held by the
task covers all four. The window before that state exists keeps its own
exception guard, because a throw there would otherwise leave the sequence number
pending and block SYSTEM WAIT QUERY RUNNER, which polls without a timeout. An
explicit admission boundary replaces the queue's finish flag: shutdown closes
admission before waiting on the pool, so an insert racing a drop cannot schedule
a task that outlives the dispatcher.

Closes: ClickHouse#114367
Review round 1: three of the five arms in
04892_query_runner_threads_not_held_when_idle could not fail for the reason
they were named for.

The idle-thread arm asserted a count below 512 where both the contract and the
measurement are exactly zero, so a regression retiring only some workers would
have passed. It now measures a delta across the CREATE, which is tighter than
any absolute bound and immune to QueryRunner tables held by tests running in
parallel.

The queue-refusal arm printed an unconditional literal, so its output was
identical whether the surplus queries were refused, all of them ran, or the
pool's queue silently became unlimited - the last being the regression the
saturating sum exists to prevent. The submitted queries now have a counted side
effect and the arm asserts a two-sided bound on it.

The dropped-table arm used synchronous mode, where the INSERT waits for its
whole batch, so nothing was ever still outstanding when the DROP ran. It is now
asynchronous, proves by metric that jobs are outstanding at DROP time, and
asserts that the abandoned ones did not execute.

Each new oracle was verified by mutation: forcing the pool's queue to be
unlimited reddens the refusal arm, and removing the early return that abandons
jobs of a shut-down table reddens the drop arm.

Also drops QueryRunnerJob::seq, which no longer has a reader or a writer.
QueryRunnerThreads and QueryRunnerThreadsScheduled are single counters shared by
every QueryRunner table in the process, so a stateless test cannot own them. The
functional test carries no no-parallel tag, its number puts it in range of
--repeat-newly-modified-tests, and 04337_query_runner creates QueryRunner tables
too, so copies of it can be inside a measured window at the same time. That
contaminates the assertions in both directions: a neighbour's worker can make the
idle-thread reading positive when this table holds nothing, and can satisfy a
"work is outstanding" reading when this table has submitted nothing.

Move both metric assertions to tests/integration/test_query_runner, where each
xdist worker gets a dedicated server, and pin them exactly there: an idle table
holds no threads, a table that has finished its queries also holds none, a table
accepts exactly threads + max_queue_size queries at a time, and the queries still
outstanding at DROP are abandoned rather than run. What stays in the functional
test reads only its own tables.

The reclamation-after-work assertion is new. Every previous arm inspected a table
that had never run a query, so raising max_free_threads left all of them green
while workers persisted after real work completed.
…uling refusal

Every query submitted to a QueryRunner table is now scheduled on a ThreadPool, and
ThreadPool::scheduleImpl consults the thread-allocation fault injector that stress runs enable, so
the pool can refuse a query that the engine would otherwise have run. Such a query is accounted for
without being executed, which makes an exact effect count in a functional test dependent on the
injector rather than on the engine.

The two functional arms that asserted exact effect counts now assert an exact upper bound and a
loose lower one, matching the shape the capacity arm already used, and the arm covering a failing
query submits two follow-up queries so that its lower bound survives a single refusal. The exact
counts move to tests/integration/test_query_runner, which runs on a private server with the
injector disabled: test_failing_query_leaves_table_usable pins the post-failure count there.
Arms 1 and 3 assert count() > 0, which is falsified only when *every* effectful
submission in the arm is refused. A submission can be refused by thread-allocation
fault injection (stress CI installs it at 1e-4) or by global thread pool saturation,
and a refused query is accounted for without failing the INSERT, so a fully-refused
arm legitimately yields 0.

Both arms submitted two queries, so a single pair of refusals falsified the lower
bound: measured 1/40 at an injection probability of 0.02. Four submissions per arm
survive three refusals; the same sweep now measures 0/40, while the pre-reshape exact
counts still fail 4/40, so the sweep still discriminates.

The upper bounds move from 2 to 4 accordingly. The reference file is unchanged: every
assertion still yields 1. No source change.
…lsify them

The two liveness arms of 04892 asserted count() <= 4 AND count() > 0. The upper
bound is the engine's exactly-once promise and is refusal-proof: a refused query
never runs, so refusal can only lower the count. The lower bound is not. The
thread pool refuses a submission both when thread allocation is being fault
injected and when the whole server is saturated, and the saturation source is
not probability-bounded and refuses consecutive submissions, so under sustained
saturation every submission in an arm is refused whatever the sample size and
count() > 0 is falsified.

Measured directly against every reachable post-refusal state: at count() = 0 the
old form fails and the new one passes, and count() = 0 was the most common single
outcome (8 of 22 readable iterations) when the arm's shape was run against a
server injecting refusals at p = 0.1. count() <= 4 still falsifies double
execution, the other half of the exactly-once property, so nothing is lost: it
returns 0 at counts 5 and 8.

Each arm keeps two blocking oracles that a lost query falsifies with a hang
rather than a count, both of which a bound cannot express: a synchronous INSERT
waits on a CountDownLatch that a job disposed of without its completion never
counts down, and SYSTEM WAIT QUERY RUNNER polls until every issued seq retires.
The exact counts are pinned in tests/integration/test_query_runner, which never
installs the fault injector, by test_dispatching,
test_threads_released_after_work and test_failing_query_leaves_table_usable.

Arm 2 keeps its lower bound: 32 submissions against a capacity of 2 would need
all 32 refused. The comments are updated so the file no longer claims an oracle
it does not have. The reference file is unchanged.
…w comment

The capacity arm of 04892 also required at least one query to have run. That
lower bound is not sound: a submission is refused whenever starting its worker
thread fails, which includes the whole server's thread pool being saturated, and
every submission in that arm needs a new thread because max_free_threads leaves
no parked worker to reuse. Saturation is a sustained state rather than an
independent per-submission draw, so all 32 submissions can legitimately be
refused together and submitting more buys nothing. Measured against a server
with thread allocation fault injected at p=0.1, an empty table was the single
most common outcome, 15 of 40 runs, and the lower bound failed on every one of
them.

The arm keeps the upper bound, which is the engine's promise, and keeps
asserting that every refused query is accounted for: a lost submission hangs the
synchronous INSERT and SYSTEM WAIT QUERY RUNNER forever. test_capacity_bound in
tests/integration/test_query_runner pins the accepted count exactly, on a server
no other test shares.

Also correct the comment above saturatingAdd. It named both operands as
unbounded, but threads is validated to [1, 1024]. The overflow is still
reachable through max_queue_size, which is validated only as at least 1, so the
guard stays.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Reviewed cold against the code on disk, then adjudicated with the recorded validation evidence.

# Finding Verdict
❌ The stateless test's lower bound (count() > 0) can be falsified by correct code: a query refused because the thread pool is saturated, or because thread allocation is being fault injected, is discarded without failing the INSERT, so an arm can legitimately observe zero effects. Agreed, fixed. The clause is deleted; the arm asserts count() <= threads + max_queue_size only. Measured over 40 paired draws at injection p=0.1, count() = 0 was the single most common outcome (15/40) and reddened the old form 15 times. A mutation control on the same draws shows the surviving bound is not vacuous (tightening it to <= 1 fails 8/40, to <= 0 fails 25/40). The exact accepted count is pinned in tests/integration/test_query_runner, which gets a server to itself.
⚠️ Dropping the bound could leave the arm passing on a table that runs nothing. Addressed by what the arm still asserts. A lost query hangs the synchronous INSERT and SYSTEM WAIT QUERY RUNNER forever, which no refusal can fake, so the arm remains a termination oracle. Execution counts are asserted exactly in the integration suite.
💡 The local saturatingAdd helper overlaps common::addOverflow. Noted, not changed. Correct as written; max_queue_size is the unbounded operand and the guard is live.
💡 pool is declared before the completion bookkeeping it touches, and the refusal log no longer names max_queue_size. Noted, not blocking. shutdown() drains the pool before either is destroyed, and refusals can now originate outside the table, so naming the table-local limit would misattribute the cause.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4deab47]


AI Review

Summary

This PR replaces QueryRunner's eager parked workers with on-demand ThreadPool scheduling, while keeping the threads + max_queue_size admission bound and releasing global pool slots when a table is idle. I traced the scheduling, shutdown, and pending-retirement paths against the new stateless and integration coverage and did not find a correctness, concurrency, or compatibility issue in the current code.

Final Verdict

✅ No material findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A single CREATE TABLE r1 (query String) ENGINE = QueryRunner SETTINGS threads = 1024 takes GlobalThread from 2 to 1027 and QueryRunnerThreads to 1024, on a table with zero inserts. 100% reproducible, no fuzzer.
b Root cause explained? Yes. A ThreadPool worker thread is itself a job on the global pool, and the dispatcher eagerly scheduled threads workers that each parked forever in a blocking queue.pop, so the pool's idle-reclaim path was never reached and the slots were held for the table's lifetime. startup() runs at CREATE and at ATTACH, so they were claimed before any insert, and threads is validated only per table ([1, 1024]) with no server-wide budget.
c Fix matches root cause? Yes. The thread-holding model is removed: each query is scheduled on the pool directly and the private queue plus the parked-worker layer are deleted, so the pool supplies the cap, the queue and on-demand start/retire. No widened bound, no lowered cap, no new setting, no guard at the failure site.
d Test intent preserved / new tests added? Yes. 04337_query_runner and the 13 pre-existing cases of tests/integration/test_query_runner are unmodified and green. The thread pool occupancy is asserted by four new cases in that integration suite, where each worker gets a server of its own, because QueryRunnerThreads and QueryRunnerThreadsScheduled are process-wide counters that a parallel functional test cannot own: an idle table holds no threads, a table that has finished its queries also holds none, a table accepts exactly threads + max_queue_size queries at a time, and the queries outstanding at DROP are abandoned. A fifth case pins the one remaining exact oracle there: a query that throws must not stop the table from running the next one. New functional test 04892_query_runner_threads_not_held_when_idle covers the completion accounting using only its own tables, and bounds rather than pins the number of queries that ran, because the thread-allocation fault injection stress runs enable can make the pool refuse a query the engine would otherwise have run. Every oracle was checked by an executed mutation, not by inspection: unlimited pool queue, capacity raised tenfold, max_free_threads made positive, the shutdown early-return deleted, the arm's own submission deleted, and a failing query made to disable the table. Each reddens the arm it is meant to, and only that arm.
e Both directions demonstrated? Yes. Twelve idle threads = 1024 tables then one ordinary query: pre-fix Code: 439 ... no free thread (threads=10000, jobs=10000) (CANNOT_SCHEDULE_TASK), post-fix the query succeeds. All four new integration cases FAIL on the pre-fix binary, each for its own reason (CANNOT_SCHEDULE_TASK on the threads = 1024 create, 4 != 0 threads left after work, 1 > 1 and 1 == 2 on the scheduled-job counts) and pass on the fixed one. The post-failure usability case reads 0 rows when a failing query is made to disable the table and 1 on the fix. The functional arms are the other direction of the same measurement: over 40 paired draws under injected scheduling refusal, a lower-bounded count fails 15 of 40 at p=0.1 and 2 of 40 at p=0.02, while the bounded form that ships fails 0 of 40 at both. That surviving bound is not vacuous: on the same draws, tightening it by one fails 8 of 40 and 32 of 40 respectively. Every binary was Build-ID asserted against both the running server and its ELF note.
f Fix is general across code paths? Yes. Nothing else constructs a QueryRunnerDispatcher. A repo-wide scan for the same eager-schedule plus blocking-pop shape (with a known instance used as a positive control) finds only CacheDictionaryUpdateQueue and FileCache; the latter is not the same defect (its workers are scheduled per eviction batch and exit when the queue finishes, and it already sets max_free_threads = 0). CacheDictionaryUpdateQueue is a different subsystem and is left for a separate change.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Exercised threads at 1, 2, 4 and 1024; max_queue_size at 1, 4, 8, 100 and UINT64_MAX (the pool bound is a saturating threads + max_queue_size, and max_queue_size has no upper bound, so the overflow is reachable from a CREATE); both mode values; local and cluster locations; zero-row and multi-row inserts. The existing range rejections still fire. The engine accepts no column types beyond String, String and Map(String, String), all covered.
h Backward compatible? Yes. No setting is added, removed or re-defaulted, so no SettingsChangesHistory.cpp entry is needed; no serialization or format change. threads keeps its documented meaning as the concurrency cap, and the total capacity bound stays threads + max_queue_size. No documentation change.
i Invariants and contracts preserved? Yes. Completion accounting fires exactly once on all four ways the pool disposes of a task (executed, refused by trySchedule, dequeued unrun at shutdown, and the temporary lambda copy the pool makes), via a shared_ptr state that is deliberately non-copyable; the pre-existing exception guard survives, scoped to the window before that state exists, so a throw there cannot leave SYSTEM WAIT QUERY RUNNER blocked. Admission is closed under a mutex before pool.wait(), so no task can outlive the dispatcher when shutdown races an insert. shutdown() stays idempotent, and each task still builds its own QueryScope, satisfying the debug-build thread-state assertion. Verified with 25 rounds of parallel inserts racing a drop: no assertion, no sanitizer report, threads back to zero.

Session id: cron:clickhouse-impl-slot-4:20260812-041900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @mstetsyuk @azat, could you review this? A QueryRunner table started its threads workers at CREATE and parked each one on an empty queue, and since a ThreadPool worker is itself a job on the global pool, an idle table held threads global slots for its whole lifetime until the pool was exhausted. The private queue and the parked-worker layer are replaced by scheduling each query on the pool directly, keeping the same threads + max_queue_size capacity bound.

@mstetsyuk

Copy link
Copy Markdown
Member

Much simpler: #114522.

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

Labels

can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AST fuzzer: fuzzed QueryRunner tables with threads = 1024 exhaust the global thread pool (CANNOT_SCHEDULE_TASK storm, job killed as Received signal 15)

3 participants