Skip to content

AI functions: Make quotas per query not per block - #114885

Merged
george-larionov merged 11 commits into
masterfrom
ai-function-per-query-quota
Aug 20, 2026
Merged

george-larionov merged 11 commits into
masterfrom
ai-function-per-query-quota

Conversation

@george-larionov

@george-larionov george-larionov commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

AIQuotaTracker was a stack local inside executeImpl, so every block and every pipeline stream started with a fresh allowance. The ai_function_max_api_calls_per_query, ai_function_max_input_tokens_per_query and ai_function_max_output_tokens_per_query limits 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 Context and 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 under max_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):

  • 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):

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

  • Merged into: 26.8.1.1732 (included in 26.8 and later)
  • Backported to: 26.7.6.13, 26.6.4.19, 26.5.8.17

george-larionov and others added 3 commits August 13, 2026 22:48
`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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6f74085]

Summary: ✅


AI Review

Summary

This PR moves AI-function quota tracking from per-call stack locals into a Context-owned tracker, makes the API-call cap exact within one execution context, and adds regression coverage for per-query, retry, and concurrency behavior. The main remaining problem is that the new tracker is copied into fresh query contexts instead of being reinitialized there, so the advertised per-fragment independence can still be violated.

Findings

❌ Blockers

  • [src/Interpreters/Context.h:646] AIQuotaTracker is stored as copied Context state, but Context::createCopy preserves that shared_ptr and makeQueryContext() never clears it. A new query context created from an already-running query can therefore inherit spent quota and quota_exceeded state instead of starting fresh. DistributedPlanExecutor::executeTask() (createCopy(context); makeQueryContext();) is a concrete path: if the parent context has already issued any AI call, the child fragment can skip rows or throw based on the parent's counters even though the docs now promise independent per-server / per-fragment enforcement.
    Suggested fix: reset ai_quota_tracker in makeQueryContext() (and any other helper that creates a fresh query context) so copied contexts start with no tracker and lazily allocate a new one on first AI call.
Tests
  • ⚠️ Add a focused regression that initializes an AIQuotaTracker in one context, then exercises Context::createCopy + makeQueryContext() and proves the new query context starts with fresh quotas. The current integration tests cover per-block and concurrent sharing, but not this fragment-boundary reset.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.90% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.30% +0.10%

Changed lines: Changed C/C++ lines covered: 100/102 (98.04%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 14, 2026
Comment thread src/Functions/AI/AIQuotaTracker.h Resolved
george-larionov and others added 2 commits August 14, 2026 21:17
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]>
@george-larionov
george-larionov marked this pull request as ready for review August 14, 2026 22:29
Comment thread src/Interpreters/Context.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6f740850c with master 581c15c46 (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
Binary Master PR Δ
programs/clickhouse-stripped 702.08 MiB 699.06 MiB -3.02 MiB (-0.43%)

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 units

1252 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.
The matched translation units cost -408.7 s (-5%) in total before that adjustment.

Job report

@rschu1ze rschu1ze left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I skimmed this PR only and excluded the tests. The idea + implementation are overall sound, thanks!

Comment thread src/Functions/FunctionBaseAI.cpp Resolved
Comment thread src/Functions/AI/AIQuotaTracker.h Resolved
Comment thread src/Functions/AI/AIQuotaTracker.h Resolved
Comment thread src/Functions/AI/AIQuotaTracker.h Resolved
george-larionov and others added 3 commits August 17, 2026 22:05
…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]>
Comment thread src/Interpreters/Context.cpp Resolved
george-larionov and others added 2 commits August 18, 2026 00:23
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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 34 queries analysed

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.

clickbench

⚠️ 8 inconclusive

Flagged queries (8 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 13 not_sure 424 339 -20.0% <0.0001 This PR only changes AI-function quota tracking (aiClassify/aiEmbed/aiSimilarity), which ClickBench Q13 never executes, so the -20.0% delta is run-to-run variance, not a PR effect.
⚠️ 15 not_sure 193 163 -15.5% <0.0001 Q15 does not touch the AI-function code this PR changes; the -15.5% shift is run-to-run variance, not attributable to this change.
⚠️ 16 not_sure 726 597 -17.8% <0.0001 Q16 exercises none of the AI-function paths this PR edits, so the -17.8% delta is off-path noise rather than a real improvement.
⚠️ 18 not_sure 1271 1053 -17.2% <0.0001 Q18 never calls the AI functions changed here; the -17.2% reading is run-to-run variance, not a PR effect.
⚠️ 23 not_sure 165 73 ×2.3 faster <0.0001 Q23 doesn't execute the AI-function quota code this PR touches, and the source measurements here were very noisy, so the x2.3 faster reading is variance, not a real change.
⚠️ 30 not_sure 278 231 -16.9% <0.0001 Q30 is unrelated to the AI-function code changed here; the -16.9% delta is run-to-run variance.
⚠️ 33 not_sure 1242 1172 -5.7% <0.0001 Q33 does not touch the AI-function paths this PR edits; the -5.7% delta is off-path noise.
⚠️ 34 not_sure 1238 1160 -6.3% <0.0001 Q34 exercises none of the changed AI-function code; the -6.3% shift is run-to-run variance, not a PR effect.

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_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 560 67 ×8.4 faster <0.0001 TPC-H Q7 never calls the AI functions changed here, and it ran co-located with Q8 on one node; the x8.4 faster reading is a measurement artifact, not a PR effect.
⚠️ 8 not_sure 167 78 ×2.1 faster <0.0001 TPC-H Q8 is off-path for this AI-function-only change and was co-located with Q7 on one node; the x2.1 faster reading is a measurement artifact, not a real improvement.

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
  • StressHouse run: 87167d35-5701-43ce-9a94-e24272ab9ab0
  • MIRAI run: 5827782d-b8bb-414b-b5c0-cc6d3a5e094a
  • PR check IDs:
    • clickbench_201936_1787177025
    • clickbench_201942_1787177025
    • clickbench_201948_1787177025
    • tpch_adapted_1_official_201965_1787177025
    • tpch_adapted_1_official_201977_1787177025
    • tpch_adapted_1_official_202006_1787177025

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;

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.

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().

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@george-larionov
george-larionov added this pull request to the merge queue Aug 20, 2026
Merged via the queue into master with commit 3ca258f Aug 20, 2026
175 checks passed
@george-larionov
george-larionov deleted the ai-function-per-query-quota branch August 20, 2026 03:29
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 20, 2026
george-larionov added a commit that referenced this pull request Aug 20, 2026
…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]>
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 21, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Aug 22, 2026
Cherry pick #114885 to 26.5: AI functions: Make quotas per query not per block
robot-ch-test-poll3 added a commit that referenced this pull request Aug 24, 2026
Cherry pick #114885 to 26.6: AI functions: Make quotas per query not per block
robot-ch-test-poll4 added a commit that referenced this pull request Aug 24, 2026
Cherry pick #114885 to 26.7: AI functions: Make quotas per query not per block
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 24, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 24, 2026
Backport #114885 to 26.6: AI functions: Make quotas per query not per block
george-larionov added a commit that referenced this pull request Aug 25, 2026
Backport #114885 to 26.5: AI functions: Make quotas per query not per block
george-larionov added a commit that referenced this pull request Aug 25, 2026
Backport #114885 to 26.7: AI functions: Make quotas per query not per block
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default 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.4-must-backport v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants