Repository navigation
AI functions: retry transient network errors like the url table function - #107927
Conversation
The AI functions (`aiGenerate`, `aiClassify`, `aiExtract`, `aiTranslate`, `aiEmbed`) retried only provider HTTP-error responses (the `RECEIVED_ERROR_FROM_REMOTE_IO_SERVER` exception). A transient network failure — connection refused/reset, a TLS connect failure, a connect/receive timeout, or a host that advertises an unreachable address (e.g. an `AAAA` record on a network without IPv6 routing) — was caught by a `catch (...)` that never retried, so `ai_function_max_retries` did not cover the most common transient failure mode. The `url` table function retries these via `ReadWriteBufferFromHTTP::doWithRetries`. Add `FunctionBaseAI::isRetriableProviderError`, which classifies the active exception with the same policy as the url table function: transient network failures (`DB::NetException`, `Poco::Net::NetException`, `Poco::TimeoutException`) and provider-side HTTP errors are retriable, while deterministic argument/usage errors are not. Route both AI execution paths (the shared chat loop in `FunctionBaseAI::executeImpl` and the embedding loop in `aiEmbed`) through it, collapsing the duplicated `catch` blocks. The `ai_function_max_retries` default is left at `0`: unlike the idempotent GET requests of the url function, AI requests are billed and not idempotent, so retries stay opt-in. The change makes the existing setting actually cover network failures once enabled. Add integration coverage: a flaky mock endpoint that drops the connection for the first N requests, exercising recovery for both the chat and embedding paths, plus a check that disabling retries surfaces the network error. Related: #103786 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…network-errors Resolve conflict in `FunctionBaseAI.cpp`: keep `isRetriableProviderError` and adopt master's argument-less `resolveConfig` (AI credentials now come from the `ai_function_credentials` setting rather than the first function argument). Adapt the new network-error retry tests to the same setting-based calling convention. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [fd3cb89] Summary: ❌
AI ReviewSummaryThe PR makes AI functions retry transient network failures and retriable provider HTTP statuses under Missing context / blind spots
Final Verdict✅ Approve from code review. No new inline findings to post; merge should still wait for the pending required CI on the latest commit. |
…ble function The previous version routed all provider failures through `FunctionBaseAI::isRetriableProviderError`, but `OpenAIProvider` and `AnthropicProvider` collapsed every non-2xx response into a plain `Exception` with `RECEIVED_ERROR_FROM_REMOTE_IO_SERVER`, discarding the HTTP status. As a result the classifier retried *all* provider HTTP errors when `ai_function_max_retries` was set — including deterministic client errors (400, 401, 403, 404, 405, 501) that the `url` table function never retries. This contradicted the helper comment and PR description. Preserve the HTTP status by introducing `AIProviderHTTPException`, a provider exception that carries the status while keeping the existing `RECEIVED_ERROR_FROM_REMOTE_IO_SERVER` code and the formatted provider message (so error text and `ai_function_throw_on_error` behavior are unchanged). Both providers now throw it. Share the `url` retry policy itself: the predicate that was local to `ReadWriteBufferFromHTTP.cpp` is exposed as `isRetriableHTTPError` in `HTTPCommon`, and `isRetriableProviderError` classifies `AIProviderHTTPException` through it. Deterministic statuses are surfaced immediately; transient/server errors (5xx, rate limiting) and network failures are retried. Also add the `Ok` comment to the `catch (...)` classifier branch to satisfy the `catch_all` style check. Tests: add `/v1/bad_request` (HTTP 400) to the mock server and assert a deterministic status is not retried (`AIAPICalls` stays at 1) with `ai_function_max_retries > 0`, that it surfaces under `ai_function_throw_on_error = 1`, and a counterpart asserting HTTP 500 is retried. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the AI Review Root cause of the major finding: the classifier promised the Fix:
Tests ( Verified all 7 changed translation units with |
The retry loops added for transient-network-failure handling call `AIQuotaTracker::recordAttempt` on every attempt but only checked `ai_function_max_api_calls_per_query` once per row (in `FunctionBaseAI`) or per batch (in `aiEmbed`), before the loop. So with, e.g., `ai_function_max_api_calls_per_query = 1` and `ai_function_max_retries = 5`, a single retriable failure still dispatched the initial request plus up to five retries — `1 + ai_function_max_retries` requests — before the next row/batch-level `checkQuotas` could run, exceeding the documented per-query HTTP-request cap. Move the quota check to the top of each retry loop, before every provider request, so the documented cap actually bounds the number of dispatched requests including retries. The check is kept outside the `try` so that a `throw_on_quota_exceeded` throw propagates instead of being swallowed by the retry handler. This matches the contract already stated in the `AIQuotaTracker::recordAttempt` comment. Adds `test_generate_retry_respects_api_call_quota` and `test_embed_retry_respects_api_call_quota`, asserting a single dispatched request (`AIAPICalls == 1`) under `ai_function_max_api_calls_per_query = 1` and `ai_function_max_retries = 5` against a retriable HTTP 500 endpoint. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the AI Review Issue: the retry loops added for transient-network-failure handling call Fix: moved the quota check to the top of each retry loop, before every provider request (including retries), so the cap actually bounds the number of dispatched requests. It is kept outside the Tests ( Verified both changed translation units with |
rschu1ze
left a comment
There was a problem hiding this comment.
The code comments are a bit too verbose for my taste but the PR itself is good.
…assifier comments The AI Review flagged a remaining gap between `FunctionBaseAI::isRetriableProviderError` and the `url` table function's retry policy: every exception other than `DB::NetException`, `Poco::Net::NetException` and `Poco::TimeoutException` fell into `catch (...)` and became non-retriable. A write-side transient I/O failure — e.g. a broken pipe (`EPIPE`) raised from `Poco::Net::SocketImpl::sendBytes` when the peer resets the connection while the request body is being written — surfaces as a plain `Poco::IOException`, so it was not retried even though the `url` path retries it. Add a `Poco::IOException` branch that retries such failures, excluding `POCO_EMFILE` (out of file descriptors, where retrying cannot help), matching `ReadWriteBufferFromHTTP::doWithRetries`. The branch is intentionally narrower than the `url` path's broad `Poco::Exception` handling. Unlike the `url` retried callable, the AI retry scope also includes parsing the provider's JSON response, and a malformed response surfaces as a `Poco::Exception` (e.g. a JSON parse error) that is not a `Poco::IOException`. Such deterministic errors must stay in `catch (...)` and remain non-retriable, so a billed, non-idempotent request is not repeated for an error that retrying cannot fix. Also trim the verbose comments on `isRetriableHTTPError`, `isRetriableProviderError` and the classifier branches, as requested in review. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the AI Review Retry policy ( Comments: trimmed the verbose doc comments on Verified all changed translation units with |
Resolve FunctionBaseAI.cpp conflict: keep the PR's new isRetriableProviderError method and master's reworked resolveConfig(const ColumnsWithTypeAndName &).
The master merge (4d098d8) brought in master's rework of the AI functions' calling convention: the named collection is now passed as the first positional argument (`aiGenerate('collection', 'prompt')`) instead of via the removed `ai_function_credentials` setting. The merge converted the pre-existing `test_ai_functions` tests to the new convention but left the PR's new retry tests on the old setting-based convention, so they failed in the flaky-check integration job (e.g. `test_generate_retries_on_network_error`, `test_embed_retries_on_network_error`): the queries either treated the prompt as the (missing) collection or rejected the unknown `ai_function_credentials` setting, never reaching the mock provider. Convert the eight new retry tests to pass the named collection as the first positional argument and drop the obsolete `ai_function_credentials` setting, matching how the rest of the file was updated during the merge. #107927 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 72/83 (86.75%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 3 line(s) · Uncovered code |
|
All failures are unrelated and are tracked with issues or have fixes. |
Cherry pick #107927 to 26.5: AI functions: retry transient network errors like the url table function
…s like the url table function
In 26.6, `aiGenerate` and `aiEmbed` take only the prompt/text (the named collection comes from the `ai_function_credentials` setting), unlike master where the collection name is the first positional argument. Move the collection names of the new retry tests into the query settings. Cherry pick of #107927 Co-Authored-By: Claude Fable 5 <[email protected]>
Cherry pick #107927 to 26.6: AI functions: retry transient network errors like the url table function
…s like the url table function
Backport #107927 to 26.5: AI functions: retry transient network errors like the url table function
Backport #107927 to 26.6: AI functions: retry transient network errors like the url table function
26.5 gained #105701 (`api_key` optional) and #107927 (retry transient network errors) after this backport branch was cut, so the conflict resolution keeps both and drops the earlier `api_key`-required adaptation. `aiEmbed` stays at the master signature `aiEmbed(text, model[, params])`; `introduced_in` stays 26.5. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
26.6 gained #107927 (retriable provider error classification) after this branch was cut, so keep its retry code and layer the parameter map on top instead of reverting it. Drop `resolveConfig`/`resolveTemperature`, superseded by `resolveAIParams`, and take the integration tests from master so the new retry tests use the parameter map and `aiEmbed`'s positional model. Related: #112710 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The master merge (4d098d8) brought in master's rework of the AI functions' calling convention: the named collection is now passed as the first positional argument (`aiGenerate('collection', 'prompt')`) instead of via the removed `ai_function_credentials` setting. The merge converted the pre-existing `test_ai_functions` tests to the new convention but left the PR's new retry tests on the old setting-based convention, so they failed in the flaky-check integration job (e.g. `test_generate_retries_on_network_error`, `test_embed_retries_on_network_error`): the queries either treated the prompt as the (missing) collection or rejected the unknown `ai_function_credentials` setting, never reaching the mock provider. Convert the eight new retry tests to pass the named collection as the first positional argument and drop the obsolete `ai_function_credentials` setting, matching how the rest of the file was updated during the merge. ClickHouse#107927 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ry-network-errors AI functions: retry transient network errors like the url table function
Make the AI functions (
aiGenerate,aiClassify,aiExtract,aiTranslate,aiEmbed) retry transient network failures, the same way theurltable function does viaReadWriteBufferFromHTTP::doWithRetries.Previously the AI execution loops retried only provider HTTP-error responses (the
RECEIVED_ERROR_FROM_REMOTE_IO_SERVERexception). A transient network failure — connection refused/reset, a TLS connect failure, a connect/receive timeout, or a host that advertises an unreachable address (e.g. anAAAArecord on a network without IPv6 routing) — was caught by acatch (...)that never retried, soai_function_max_retriesdid not actually cover the most common transient failure mode.This adds
FunctionBaseAI::isRetriableProviderError, which classifies the active exception with the same policy as theurltable function: transient network failures (DB::NetException,Poco::Net::NetException,Poco::TimeoutException) are retriable, and provider HTTP error responses are classified by status. To make the latter work the providers preserve the response status:OpenAIProviderandAnthropicProviderthrow the newAIProviderHTTPException(carrying the status, while keeping the sameRECEIVED_ERROR_FROM_REMOTE_IO_SERVERcode and the formatted provider message), and the classifier routes it throughisRetriableHTTPError— the predicate lifted out ofReadWriteBufferFromHTTP.cppintoHTTPCommonand now shared with theurlpath. So deterministic statuses (400,401,403,404,405,501) are surfaced immediately even with retries enabled, while transient/server-side errors (5xx, rate limiting) are retried — exactly matching theurlbehavior. Both AI execution paths — the shared chat loop inFunctionBaseAI::executeImpland the embedding loop inaiEmbed— are routed through the classifier, collapsing the previously duplicatedcatchblocks.The
ai_function_max_retriesdefault is left at0: unlike the idempotent GET requests issued by theurlfunction (whosehttp_max_triesdefaults to 10), AI requests are billed and not idempotent, so retries remain opt-in. This change makes the existing setting actually cover network failures once a user enables it.Note: the related connection-pool fix in #103786 already lets a single connection attempt fall back to the next resolved address (helping the dead-
AAAAcase). This change is complementary: it adds full request-level retries for the broader class of transient failures (resets, timeouts, recovered endpoints), for both chat and embedding requests.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
AI functions (
aiGenerate,aiEmbed,aiClassify,aiExtract,aiTranslate) now retry transient network failures (connection resets, TLS connect failures, timeouts, unreachable addresses) whenai_function_max_retriesis set, matching the retry behavior of theurltable function. Previously only provider-side HTTP error responses were retried.Version info
26.7.1.92(included in26.7and later)26.6.2.135,26.5.6.94