Repository navigation
Do not reject a query when index analysis has more parts than threads - #116822
Conversation
A valid SELECT over a MergeTree table could fail with Code: 439. DB::Exception: Cannot schedule a task: no free thread (timeout=60000000) (threads=3, jobs=3). (CANNOT_SCHEDULE_TASK) raised from filterPartsByPrimaryKeyAndSkipIndexes, after waiting out lock_acquire_timeout on an otherwise healthy server. The private pool for parallel index analysis is built with the four-argument ThreadPool constructor, which sets queue_size equal to max_threads, i.e. to num_threads = min(num_streams, parts_with_ranges.size()). The loop below it submits one job per part. So whenever a table has more parts to analyse than the query has streams, the loop submits more jobs than its own queue can hold. The predicate that then blocks is about the queue rather than about threads (ThreadPool.cpp: !queue_size || scheduled_jobs < queue_size || finished), so the submitter waits for lock_acquire_timeout and reports "no free thread", a message that misdescribes its own condition. The in-flight jobs are slow because index analysis blocks in MergeTreeMarksLoader on the server-wide marks pool. CI randomises max_threads down to 1..3 in most runs, which is why every observed occurrence reports threads=2, jobs=2 or threads=3, jobs=3. Schedule those jobs with scheduleOrThrowOnError, so a full queue means waiting for a slot instead of rejecting the query. The bound being removed was never the guard against global thread pool saturation that the comment above the loop described. Local pool worker creation goes through a different branch of scheduleImpl, reached before the queue-full wait, bounded by max_threads alone: it uses a zero-wait global schedule and fails immediately with "failed to start the thread". That was already true when the timeout was introduced in dc677f0, and it is unchanged here, so a query that cannot get a worker at all still fails fast. The comment is deleted because after this change it describes neither the code nor a real protection, and the now-unused lock_acquire_timeout extern goes with it: the executor no longer consults a lock-acquisition setting to decide whether a SELECT may proceed. The regression test needs an injected delay, because no existing failpoint sits anywhere on the index-analysis path and lock_acquire_timeout is measured in whole seconds, so nothing else outlasts it deterministically. The new slowdown_index_analysis_per_part failpoint is placed inside process_part so that the inline num_threads <= 1 path carries the same instrumentation, is inert unless explicitly enabled, and compiles away when USE_LIBFIU is off. The test asserts the fixture is armed without relying on wall-clock timing: it checks the active part count and the failpoint's enabled flag, and ends with a failpoint-off control query. Without this change the test fails 20 out of 20 runs with the error above; with it, 20 out of 20 pass, and 50 randomised runs pass.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 findings), plus 2 findings from my
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260828-014400 |
Pre-PR validation gate (click to expand)
Broader regression check: 192 index-related tests swept on both binaries under matched conditions. The failure sets are identical, so this change introduces no new failures. Session id: cron:clickhouse-impl-slot-5:20260827-220002 |
|
Workflow [PR], commit [eef4d88] Summary: ✅
AI ReviewSummaryThis PR fixes the Final Verdict
LLVM Coverage ReportMeasured on commit eef4d88.
Changed lines: Changed C/C++ lines covered: 28/28 (100.00%) · Uncovered code |
|
cc @tiandiwonder @KochetovNicolai, could you review this? The private pool for parallel index analysis is built with the four-argument |
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Stress test (amd_tsan) / Logical error: Not-ready Set is passed as the second argument for function 'A (STID 0250-41a5) |
trunk logical error in subquery set building, aborting the server in sanitizer builds. 429 rows over 316 distinct pull requests plus 26 rows on master across 25 distinct commits in 30 days, first seen 2026-07-29. Passed at this same commit in the sibling run. |
#102308 (external, open) |
Stress test (arm_msan) / Logical error: Not-ready Set is passed as the second argument for function 'A (STID 0250-3e49) |
same family and same owner, a second bucket of the one signature. Passed at this same commit in the sibling run. | #102308 (external, open) |
This diff is MergeTreeDataSelectExecutor.cpp (+11/-12), FailPoint.cpp and one stateless test.
Reports:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116822&sha=e510569678130b6b781ba1eb921d3cbc8a92e32a&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116822&sha=e510569678130b6b781ba1eb921d3cbc8a92e32a&name_0=PR&name_1=Stress%20test%20%28arm_msan%29
Session id: cron:our-pr-ci-monitor:20260828-080000
CI finish ledger: b88a03bEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
This diff touches Session id: cron:our-pr-ci-monitor:20260831-093000 |
`filterPartsByPrimaryKeyAndSkipIndexes` scheduled one `ThreadPool` job per part into a private pool whose queue holds only `num_threads` jobs. With more parts than threads the submitting thread handed the parts over one at a time, and every job attached its worker to the query thread group and detached it again. When the per-part analysis is cheap (skip indexes served from caches or evaluated at read time), these fixed per-part costs dominate the phase. Now `min(num_threads, parts)` jobs are scheduled. Each attaches once and takes parts from a shared counter until none are left, so the parallelism and the per-part load balancing stay the same. - The counter is declared before the pool, because the pool destructor joins the jobs that still read it when scheduling throws. - A job stops once the pool is finished: after a job has thrown (`shutdown_on_exception`) or when the destructor starts. The remaining parts are then abandoned, as the queued per-part jobs were discarded before. The patch proposed in the issue declared its counters after the pool, so a scheduling failure would leave running jobs reading destroyed stack objects, and it kept the bounded `scheduleOrThrow` wait, which cannot fire with at most `num_threads` jobs. Measured on x86 (Xeon 6975P-C, both servers pinned to the same 16 cores, release build, warm caches, `use_query_condition_cache = 0`, the tables and queries from the issue, three server pairs, 600 interleaved queries each): - pool jobs per query at `max_threads = 4`: 204 -> 8 (200 parts), 1004 -> 8 (1000 parts) - `hasToken` over 1000 parts: median latency -37% to -43% - text-index `count()` over 200 parts: median latency -12% to -33% - 4 concurrent clients over 200 parts: 727 -> 1086 QPS (`hasToken`), 633 -> 881 QPS (`hasAllTokens`) - queries that do not reach the parallel path (one part, primary key range only) differed by -10% to +18% between server pairs, so that is the noise floor of this setup for 2 ms queries. Closes: ClickHouse#122556
…sis-schedule-queue-bound Co-Authored-By: Claude Opus 5.5 <[email protected]>
`05045_index_analysis_more_parts_than_threads` now checks in `system.query_log` that the query run with the failpoint took at least 3 s, so the test fails if the injected delay stops firing instead of passing without testing anything. It is a lower bound, so a slow runner cannot break it. `05060_thread_pool_schedule_timeout_chrono_overflow` checked that `lock_acquire_timeout` reaches the index analysis pool. Index analysis no longer reads that setting, so the test cannot reach the path it describes. The setting still bounds the table lock of a `SELECT`, which `04327_wait_timeout_chrono_overflow` covers with the same values, and the pool's timed wait is covered by `gtest_thread_pool_schedule_timeout`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review of the folded tree by an independent model (engine: codex; 2 rounds, 3 findings), plus my own cold review of each round, which changed only the wording of the description.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260928-004503 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260927-214300 |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
| CurrentMetrics::MergeTreeDataSelectExecutorThreads, | ||
| CurrentMetrics::MergeTreeDataSelectExecutorThreadsActive, | ||
| CurrentMetrics::MergeTreeDataSelectExecutorThreadsScheduled, | ||
| num_threads); |
There was a problem hiding this comment.
Another alternative is to pass queue_size=0, but I like this approach more, allows to get rid of extra overhead (even though it can be minor)
The `failpoint_tests_are_isolated` style check requires a test that enables a fail point to be tagged `no-fasttest` as well as `no-parallel`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
eef4d88 tags |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a spurious
Cannot schedule a task: no free thread ... (CANNOT_SCHEDULE_TASK)error that rejected a validSELECTover aMergeTreetable when it had more parts to analyse than the query had threads and their analysis took longer thanlock_acquire_timeout. Index analysis now runs one pool job per thread instead of one per part, which also makes it faster for queries over many parts.Description
Closes: #122556
Related: #116376
On 26.8, a valid
SELECTover aMergeTreetable with more parts to analyse than threads is rejected withCode: 439 ... no free thread (CANNOT_SCHEDULE_TASK)when every in-flight analysis stalls pastlock_acquire_timeout. Six CI occurrences in 60 days, most recently here.Root cause:
filterPartsByPrimaryKeyAndSkipIndexesscheduled one job per part into a private pool whose queue holdsnum_threadsjobs, so with more parts than threads the submitter blocked on its own full queue untillock_acquire_timeout, and every part paid a thread-group attach and detach.Now
min(num_threads, parts)jobs are scheduled. Each attaches once and takes parts from a shared counter until none are left or a failure finishes the pool, so parallelism and per-part balancing are unchanged. The submitter no longer waits for its own queue, so the timedscheduleOrThrowbecomesscheduleOrThrowOnError; global pool saturation still fails fast (failed to start the thread): local workers are created with a zero-wait schedule.05060_thread_pool_schedule_timeout_chrono_overflowis removed: index analysis no longer readslock_acquire_timeout(still covered by04327_wait_timeout_chrono_overflow).The patch proposed in #122556 declared its counters after the pool: with injected thread allocation failures an ASan build of that shape reported
stack-use-after-scopewithin 11 queries, while this one ran 2000 such queries with no report.On x86 (release build, warm caches, tables and queries from #122556,
max_threads = 4):max_threads_for_indexes = 1before and 1.05x-1.07x after (4 servers each);hasTokenover 1000 parts: median -34% to -40% in 7 server pairs; queries that do not reach this code differ by up to 18% between servers.The new test fails 20/20 without the scheduling change, passes 50/50 randomised, and asserts that its injected stall ran.
Workflow [PR]
Sync PR [sync-upstream/pr/116822]
Version info
26.10.1.1653-master(included in26.10and later)