Skip to content

Cherry pick #107927 to 26.5: AI functions: retry transient network errors like the url table function - #112522

Merged
robot-clickhouse-ci-2 merged 10 commits into
backport/26.5/107927from
cherrypick/26.5/107927
Jul 30, 2026
Merged

robot-clickhouse-ci-2 merged 10 commits into
backport/26.5/107927from
cherrypick/26.5/107927

Conversation

@robot-ch-test-poll

Copy link
Copy Markdown
Contributor

Original pull-request #107927

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

alexey-milovidov and others added 9 commits June 19, 2026 03:05
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]>
…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]>
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]>
…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]>
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]>
…-errors

AI functions: retry transient network errors like the url table function
@robot-ch-test-poll robot-ch-test-poll added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request labels Jul 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants