Skip to content

Issue AI function requests concurrently from a server-wide thread pool - #122484

Merged
george-larionov merged 31 commits into
masterfrom
ai-functions/ai-service-static-pool
Oct 23, 2026
Merged

george-larionov merged 31 commits into
masterfrom
ai-functions/ai-service-static-pool

Conversation

@george-larionov

@george-larionov george-larionov commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

Resolves #112248.

Explicit multithreading for AI functions.

Reasoning: AI funcs don't use any local compute and so the traditional concurrency in ClickHouse is not enough. In my tests I was not able to get above ~6 concurrent streams with default settings, ~12 with more parts per table. I tested up to 1m rows.

This PR implements a server-wide static thread pool (AIRequestThreadPool), and each query thread keeps up to ai_function_max_concurrent_requests_per_thread (default 8) of them in flight. Retries with backoff, API-call reservation and token accounting run on the pool workers.

  • New server settings ai_function_max_thread_pool_size (default 1000), ai_function_max_thread_pool_free_size, ai_function_thread_pool_queue_size, changeable without restart.
  • ai_function_max_retries defaults to 3 (was 1), so 429 responses from rate-limited providers under concurrent requests are retried.
  • New ProfileEvents AIAPICallsRetried, AIAPICallsFailed and AIAPICallsThrottled (HTTP 429), per query in system.query_log and per server in system.events and system.metric_log.

Tested against a mock endpoint up to 1M rows, and against the ClickHouse inference gateway with nova-micro, claude-haiku-4-5, gpt-oss-20b and text-embedding-3-small. With the defaults, a typical query stays within provider rate limits; nova-micro is throttled above roughly 4,300 requests per minute by the retries.

Important decisions

  • The settings above were set empirically, to maximize multithreading while minimizing any issues with existing popular models/providers. The combination of 8 default threads per query thread and max_retries = 3 make even endpoints that throttle this many requests per second work well.
  • I decided to make the ai_function_max_concurrent_requests_per_thread be per query thread instead of overall for implementation simplicity. If this is too confusing (thinking about requests per thread x number of threads) it is not too difficult to make it a per-query setting that uses a semaphore to enforce the total concurrent requests per query.

Changelog category (leave one):

  • Improvement

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

AI functions issue provider requests concurrently from a server-wide thread pool (ai_function_max_thread_pool_size), with up to ai_function_max_concurrent_requests_per_thread requests in flight per query thread (default 8). ai_function_max_retries defaults to 3, and new ProfileEvents count retried, failed and throttled provider requests.


Workflow [PR]
Sync PR [sync-upstream/pr/122484]

Version info

  • Merged into: 26.11.1.671-master (included in 26.11 and later)

george-larionov and others added 10 commits September 24, 2026 19:58
Requests run on `getAIRequestThreadPool` (a `StaticThreadPool`), configured by
`max_ai_request_thread_pool_size`, `max_ai_request_thread_pool_free_size` and
`ai_request_thread_pool_queue_size`. `ai_function_max_concurrent_requests` bounds
one function call's share. Retries, API-call reservation and token accounting
move into `submitAIRequest` / `submitAIEmbeddingRequest`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`AIQuotaTracker::checkQuotas` and `recordApiCall` throw on `KILL QUERY` or
`max_execution_time`, so a killed query no longer finishes its current block,
and queued requests and retries are not dispatched. Also doc and comment tweaks.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`submitAIRequest` is overloaded for both request types over one `submit`
template; `runAttempt` overloads pick `call` or `embed`. `AIEmbeddingResponse`
gains an always-zero `output_tokens`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A `/v1/chat/jitter` mock endpoint answers after a random delay, so concurrent
responses complete out of order.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`ai_function_max_concurrent_requests` becomes
`ai_function_max_concurrent_requests_per_stream`, defaulting to 16.
`max_ai_request_thread_pool_size` defaults to 1000. Token-quota tests pin
the setting to 1.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Measured against the inference gateway, 8 per stream keeps a typical query
within provider rate limits, and 3 retries absorb the remaining 429s. Tests
that call unreachable endpoints pin one retry.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@mintlify

mintlify Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 22, 2026, 11:43 PM

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 27, 2026
Settings history moved into the declarations on master: the new
`ai_function_max_concurrent_requests_per_stream` and the
`ai_function_max_retries` default change now carry their 26.10 records there.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8edef79]

Summary: ✅


AI Review

Summary

Reviewed #122484 at 8edef7939964cc313d9b88203f3d03d406c6ae16, including the diff, current implementations, and every prior discussion thread. The PR adds concurrent AI requests through a shared thread pool, cancellation-aware waits, retry accounting, and shutdown draining. No new inline findings; one previously reported compatibility violation remains and was explicitly dismissed by the author.

Findings

❌ Blockers

  • src/Functions/FunctionBaseAI.cpp:358–363 Previously valid retry configurations now fail even under older compatibility. [dismissed by author -- https://github.com/Issue AI function requests concurrently from a server-wide thread pool #122484#discussion_r4274410474] The author declines compatibility handling because AI functions are beta. The code nevertheless unconditionally rejects existing values such as ai_function_max_retries = 6 or ai_function_retry_initial_delay_ms = 30000, across text, embedding, and similarity functions. The latter is rejected even with retries disabled. Setting history restores defaults only; it cannot preserve execution of these existing queries. Gate the enforcement under compatibility, retain overflow-safe bounded backoff for legacy values, and document the restrictions and migration path.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available. A passing current-head ASan result for test_shutdown_after_cancelling_query_with_request_in_flight could not be verified from the available CI reports. That result would validate the new shutdown lifetime boundary at runtime; the earlier inline lifetime finding was resolved based on the corrected destruction order.
Tests
  • ⚠️ Add a focused regression using previously accepted retry values with older compatibility, against a successful mock response. The new setting-limit test covers rejection only.
Final Verdict

Status: ❌ Block. Preserve previously valid retry configurations under older compatibility and cover that behavior with a regression. The dismissed concern remains summary-only; no duplicate inline comment or thread reply was posted.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 28, 2026
@george-larionov
george-larionov marked this pull request as ready for review September 28, 2026 22:37
Comment thread src/Functions/AI/AIRequestExecutor.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8edef7939 with master 7566d4f6d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

89 object files changed (+329.36 KiB total), 1 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/AI/AIRequestExecutor.cpp.o new 237.87 KiB +237.87 KiB
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionBaseAI.cpp.o 461.89 KiB 528.24 KiB +66.34 KiB (+14.36%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

551 translation units recompiled, 4926 s compile time in total, 549 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.9 s

Job report

@Blargian Blargian added the pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard label Oct 1, 2026
Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
`ai_function_max_concurrent_requests_per_stream` becomes `..._per_thread`, and the
pool settings become `ai_function_max_thread_pool_size`,
`ai_function_max_thread_pool_free_size` and `ai_function_thread_pool_queue_size`.
Regenerated reference docs for these settings.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
george-larionov and others added 2 commits October 1, 2026 20:50
New `ProfileEvents`: `AIAPICallsRetried`, `AIAPICallsFailed` (including errors
replaced by a default value) and `AIAPICallsThrottled` (HTTP 429). Server-wide
totals and history come from `system.events` and `system.metric_log`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…me limits

`ai_function_max_concurrent_requests_per_thread` records 1 -> 8 in 26.10, so
`compatibility` below 26.10 keeps the previous serial behavior. Integration
tests cover `max_execution_time` with both overflow modes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 23, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 30, 2026
george-larionov added a commit that referenced this pull request Oct 30, 2026
Adapt the request executor to 26.8's value-returning `IAIProvider::call`/`embed`, without porting #114905 or its tests.
Keep 26.8's generated docs pages and `aiEmbed` row counters; add the settings changes to the `26.8` block of `SettingsChangesHistory`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll added a commit that referenced this pull request Oct 30, 2026
Cherry pick #122484 to 26.8: Issue AI function requests concurrently from a server-wide thread pool
robot-clickhouse added a commit that referenced this pull request Oct 30, 2026
george-larionov added a commit that referenced this pull request Oct 31, 2026
Keep 26.9's generated docs pages and `Settings.cpp` form; add the settings changes to the `26.9` block of `SettingsChangesHistory`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse-ci-2 added a commit that referenced this pull request Oct 31, 2026
Cherry pick #122484 to 26.9: Issue AI function requests concurrently from a server-wide thread pool
robot-clickhouse added a commit that referenced this pull request Oct 31, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 31, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 31, 2026
Backport #122484 to 26.10: Issue AI function requests concurrently from a server-wide thread pool
clickhouse-gh Bot added a commit that referenced this pull request Oct 31, 2026
Backport #122484 to 26.9: Issue AI function requests concurrently from a server-wide thread pool
clickhouse-gh Bot added a commit that referenced this pull request Oct 31, 2026
Backport #122484 to 26.8: Issue AI function requests concurrently from a server-wide thread pool
george-larionov added a commit that referenced this pull request Oct 31, 2026
…4-26.10

[26.10] Record the #122484 settings changes under 26.10
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
The clean backport kept master's `26.11` records, so `compatibility = '26.10'` reverted `ai_function_max_retries` and `ai_function_max_concurrent_requests_per_thread`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-ai-functions AI functions: SQL functions that call a large language model or an embedding model (aiGenerate, a... and removed comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-ai-functions AI functions: SQL functions that call a large language model or an embedding model (aiGenerate, a... hold Skip for auto-updating. pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AI functions: parallelize remote calls

6 participants