Repository navigation
AI functions: Make quotas per query not per block - #114885
Conversation
`AIQuotaTracker` was a stack local in `executeImpl`, so every block and every pipeline stream got a fresh allowance and the `ai_function_max_*_per_query` limits scaled with the data instead of bounding the query. Own one tracker on the query `Context` (shared by every AI function call in the query) and make its counters atomic for concurrent pipeline threads. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Move the AI call-count tests into the mock suite and add multi-part (multi-block) tests that a per-block tracker cannot pass: `test_api_call_quota_is_per_query`, `test_api_call_quota_throws_per_query`, `test_input_token_quota_is_per_query`. Merges are stopped so the parts survive to the scan. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [6f74085] Summary: ✅
AI ReviewSummaryThis PR moves AI-function quota tracking from per-call stack locals into a Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 100/102 (98.04%) · Uncovered code |
Reserve each request slot with an atomic bounded increment (`tryReserveApiCall`) so concurrent pipeline threads cannot overshoot `ai_function_max_api_calls_per_query`. Token limits stay best-effort: usage is known only after the response. Adds a multi-threaded test and updates the setting docs. Co-Authored-By: Claude Opus 4.8 <[email protected]>
- Fix the garbled `ai_function_max_api_calls_per_query` doc string. - Print the observed call count (not the max twice) in the limit-reached exception. - Make `test_api_call_quota_holds_under_concurrency` prove concurrency: assert `peak_threads_usage` exceeds 1 (from `system.query_log`) over a table with enough marks to split the scan across threads. The mock becomes a threaded server with a larger backlog so it serves the concurrent AI calls. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units1252 translation units recompiled, 7463 s compile time in total, 1252 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
rschu1ze
left a comment
There was a problem hiding this comment.
I skimmed this PR only and excluded the tests. The idea + implementation are overall sound, thanks!
…uery The tracker lives on the per-query-execution `Context`, and distributed execution creates one context per shard/fragment (`makeQueryContext`), so each enforces the limit independently. Narrow the setting docs and the `AIQuotaTracker` comment to say so, instead of claiming a global cap. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Drop the `AIQuotaTracker & quota = *quota_tracker` reference bindings and call through the `shared_ptr` instead. No behavior change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Per review: "reserve an API call" reads oddly; the method counts a call against the request quota. Behavior unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Per review: the counters aren't performance-critical (each is touched once per provider request), so a plain mutex with TSA annotations is simpler than atomics and drops the memory-order noise. Behavior unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The quota settings are read from the query context, so a sub-query SETTINGS override of them is ignored. Note this in the four settings' docs and add a regression test asserting a sub-query cap does not change the query budget (the top-level value governs). Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes AI-function quota tracking (the shared per-query tracker used by aiClassify/aiEmbed/aiSimilarity), a doc-string refresh, and tests; the sole non-AI edit adds a new getAIQuotaTracker accessor without altering the standard query hot path. Neither ClickBench nor the TPC-H suite executes any of that code, so every flagged "improvement" is off-path and I downgraded all of them to not-sure as run-to-run variance. The two TPC-H queries (Q7 x8.4 faster, Q8 x2.1 faster) were also co-located on the same node, consistent with those large deltas being measurement artifacts rather than a real effect. Q31's no-change suppression is consistent: its median sits inside master's variance band and this diff cannot touch that query. clickbenchFlagged queries (8 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_officialFlagged queries (2 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
recordApiCall now re-checks the token/sticky quotas under the same lock as the API-call reservation (shared helper quotasExceededLocked), so a call is never started after another thread's response pushed the token budget over - closing the check-then-reserve gap for the token limits. The now-redundant per-attempt checkQuotas before recordApiCall is removed; the top-of-row and top-of-batch checks stay. Co-Authored-By: Claude Opus 4.8 <[email protected]>
| mutable ReverseLookupCachePtr reverse_lookup_cache; | ||
|
|
||
| /// AI-function quota usage for the current query, shared by every AI function call in it. | ||
| mutable AIQuotaTrackerPtr ai_quota_tracker; |
There was a problem hiding this comment.
Making AIQuotaTracker a field on Context still does not give every fresh query context its own budget. Context::createCopy copies this shared_ptr by value (src/Interpreters/Context.cpp:1382-1457), and makeQueryContext() reinitializes other per-query state such as query_privileges_info, async_read_counters, and runtime_filter_lookup, but never clears ai_quota_tracker (src/Interpreters/Context.cpp:3789-3817). As a result, any path that does createCopy(context); makeQueryContext(); after the parent query has already dispatched an AI call can inherit a spent tracker instead of starting fresh. DistributedPlanExecutor::executeTask() is one such path, so a supposedly independent fragment can start skipping/throwing based on another fragment's usage even though the new docs say quotas are enforced independently per server / fragment. Please reset ai_quota_tracker when a context becomes a new query context, and add a focused regression around createCopy + makeQueryContext().
There was a problem hiding this comment.
I don't think this is correct. The copy constructor at line 1320 does not have a line for the AIQuotaTracker object, and so it gets default initialized to nullptr which will then be created when getAIQuotaTracker() is called. Note that this is separate from the subquery path which uses a weak-ptr and so does not perform a real copy and will re-use the existing quota tracker.
…rs-on-throw Reconciles this branch with the per-query quota rework in #114885: `recordAttempt` became `recordApiCall`, called outside the `try`, and the text path now uses the query-scoped tracker. The counters stay in caller-owned storage published from scope guards, so `aiSimilarity` no longer increments `AIAPICalls`/`AIInputTokens` itself. Co-Authored-By: Claude Opus 5 <[email protected]>
Cherry pick #114885 to 26.5: AI functions: Make quotas per query not per block
Cherry pick #114885 to 26.6: AI functions: Make quotas per query not per block
Cherry pick #114885 to 26.7: AI functions: Make quotas per query not per block
Backport #114885 to 26.6: AI functions: Make quotas per query not per block
Backport #114885 to 26.5: AI functions: Make quotas per query not per block
Backport #114885 to 26.7: AI functions: Make quotas per query not per block
AIQuotaTrackerwas a stack local insideexecuteImpl, so every block and every pipeline stream started with a fresh allowance. Theai_function_max_api_calls_per_query,ai_function_max_input_tokens_per_queryandai_function_max_output_tokens_per_querylimits therefore scaled with the data (one allowance per block per function) instead of bounding the query — any limit above the largest block's row count could never fire.The tracker is now a single instance owned by the query
Contextand shared by every AI function call in that context, with atomic counters for the concurrent pipeline threads. The API-call limit is claimed with an atomic bounded reservation, so it is an exact cap within a query-execution context even undermax_threads > 1; the token limits are best-effort, since a call's token usage is known only after its response arrives. The limits are enforced per server / query fragment: a distributed query (across shards or parallel-replica fragments) enforces them independently on each, not summed globally.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The AI-function quota settings (
ai_function_max_api_calls_per_query,ai_function_max_input_tokens_per_query,ai_function_max_output_tokens_per_query) were enforced per block rather than per query, letting a query exceed the configured limit in proportion to the number of blocks and threads processed. They now bound the whole query per server: the API-call limit is an exact cap (atomic reservation), and the token limits are best-effort. A distributed query enforces the limits independently on each participating server / fragment.Workflow [PR]
Sync PR [sync-upstream/pr/114885]
Version info
26.8.1.1732(included in26.8and later)26.7.6.13,26.6.4.19,26.5.8.17