Skip to content

AI functions: retry transient network errors like the url table function - #107927

Merged
george-larionov merged 8 commits into
masterfrom
ai-functions-retry-network-errors
Jun 26, 2026
Merged

george-larionov merged 8 commits into
masterfrom
ai-functions-retry-network-errors

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Make the AI functions (aiGenerate, aiClassify, aiExtract, aiTranslate, aiEmbed) retry transient network failures, the same way the url table function does via ReadWriteBufferFromHTTP::doWithRetries.

Previously the AI execution loops 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 actually cover the most common transient failure mode.

This adds 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) are retriable, and provider HTTP error responses are classified by status. To make the latter work the providers preserve the response status: OpenAIProvider and AnthropicProvider throw the new AIProviderHTTPException (carrying the status, while keeping the same RECEIVED_ERROR_FROM_REMOTE_IO_SERVER code and the formatted provider message), and the classifier routes it through isRetriableHTTPError — the predicate lifted out of ReadWriteBufferFromHTTP.cpp into HTTPCommon and now shared with the url path. 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 the url behavior. Both AI execution paths — the shared chat loop in FunctionBaseAI::executeImpl and the embedding loop in aiEmbed — are routed through the classifier, collapsing the previously duplicated catch blocks.

The ai_function_max_retries default is left at 0: unlike the idempotent GET requests issued by the url function (whose http_max_tries defaults 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-AAAA case). 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):

  • Improvement

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) when ai_function_max_retries is set, matching the retry behavior of the url table function. Previously only provider-side HTTP error responses were retried.

Version info

  • Merged into: 26.7.1.92 (included in 26.7 and later)
  • Backported to: 26.6.2.135, 26.5.6.94

alexey-milovidov and others added 2 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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fd3cb89]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, s3 storage, parallel, 2/2) FAIL
Server died FAIL cidb, issue ISSUE EXISTS
ThreadSanitizer: data race (STID: 4071-3348) FAIL cidb IGNORED
Integration tests (amd_msan, 1/6) FAIL
test_dns_cache/test.py::test_user_access_ip_change[node5] FAIL cidb IGNORED
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue ISSUE EXISTS
Stress test (arm_debug) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue ISSUE EXISTS
Stress test (arm_asan_ubsan) FAIL
Logical error: Bad cast from type A to B (STID: 3336-3d90) FAIL cidb IGNORED
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb IGNORED

AI Review

Summary

The PR makes AI functions retry transient network failures and retriable provider HTTP statuses under ai_function_max_retries, while preserving deterministic HTTP errors and enforcing ai_function_max_api_calls_per_query before each retry attempt. The current code addresses the prior review threads for HTTP status preservation, per-attempt quota checks, write-side I/O retry coverage, and the named-collection calling convention in the new tests. I did not find remaining review-blocking issues in the current diff.

Missing context / blind spots
  • ⚠️ I did not run tests/integration/test_ai_functions locally. The latest direct Praktika PR report for commit fd3cb89f6afe8c19648b2cab9a32bb74ed8dc9c3 had no completed test results at review time; passing the required CI, especially test_ai_functions, would close this gap.
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.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 19, 2026
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
alexey-milovidov and others added 2 commits June 19, 2026 23:43
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI Review ⚠️ Request changes verdict and the matching clickhouse-gh thread (FunctionBaseAI.cpp:142) in e4b490d, and merged current master (clean).

Root cause of the major finding: the classifier promised the url table function's retry policy, but OpenAIProvider/AnthropicProvider collapsed every non-2xx response into a plain Exception with RECEIVED_ERROR_FROM_REMOTE_IO_SERVER, discarding the status. So with ai_function_max_retries > 0, deterministic client errors (400/401/403/404/405/501) were retried — the opposite of the url path and of what the description claimed.

Fix:

  • New AIProviderHTTPException (in IAIProvider) carries the HTTP status while keeping the 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 throw it.
  • The retriable-status predicate is lifted out of ReadWriteBufferFromHTTP.cpp into HTTPCommon as isRetriableHTTPError and now genuinely shared between the url path and isRetriableProviderError — no duplicated policy.
  • Added the Ok comment on the catch (...) classifier branch to fix the catch_all style check.

Tests (test_ai_functions): new /v1/bad_request (HTTP 400) endpoint + test_generate_deterministic_http_error_not_retried (asserts AIAPICalls == 1 with ai_function_max_retries = 5), test_generate_deterministic_http_error_throws (surfaces RECEIVED_ERROR_FROM_REMOTE_IO_SERVER under throw_on_error = 1), and test_generate_server_error_is_retried (HTTP 500 → 3 calls), proving the url-style classification.

Verified all 7 changed translation units with -fsyntax-only against the real compile flags; the catch_all style check passes locally. Full build + integration run delegated to CI.

Comment thread src/Functions/aiEmbed.cpp Resolved
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI Review ⚠️ Major finding and the two matching clickhouse-gh threads (FunctionBaseAI.cpp:305, aiEmbed.cpp:238) in 37c4d15.

Issue: the retry loops added for transient-network-failure handling call AIQuotaTracker::recordAttempt on every attempt, but ai_function_max_api_calls_per_query was only checked once per row (FunctionBaseAI) / per batch (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 1 + ai_function_max_retries requests before the next row/batch-level checkQuotas could run — exceeding the documented per-query HTTP-request cap.

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 try so a throw_on_quota_exceeded throw propagates instead of being swallowed by the retry handler — this is exactly the contract already stated in the recordAttempt comment.

Tests (test_ai_functions): test_generate_retry_respects_api_call_quota and test_embed_retry_respects_api_call_quota assert AIAPICalls == 1 with ai_function_max_api_calls_per_query = 1 and ai_function_max_retries = 5 against a retriable HTTP 500 endpoint (would be 6 without the fix).

Verified both changed translation units with -fsyntax-only against the real compile flags. The only remaining CI red is the unrelated arm_msan stress flake Logical error: Distributed task iterator is not initialized (#107898, open, master-wide), which is unrelated to AI functions.

Comment thread src/Functions/FunctionBaseAI.cpp Resolved

@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.

The code comments are a bit too verbose for my taste but the PR itself is good.

Comment thread src/IO/HTTPCommon.h Resolved
Comment thread src/Functions/FunctionBaseAI.h Resolved
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI Review ⚠️ Request changes verdict (the FunctionBaseAI.cpp retry-policy thread) and Robert Schulze's four comment-cleanup threads in c4a489d.

Retry policy (clickhouse-gh thread): the classifier treated every exception other than DB::NetException, Poco::Net::NetException and Poco::TimeoutException as non-retriable via catch (...), so a write-side transient I/O failure — e.g. a broken pipe (EPIPE) from Poco::Net::SocketImpl::sendBytes when the peer resets the connection mid-request — surfaced as a plain Poco::IOException and was not retried, unlike the url path. Added a Poco::IOException branch that retries it, excluding POCO_EMFILE, matching ReadWriteBufferFromHTTP::doWithRetries. It is intentionally narrower than the url path's broad Poco::Exception handling: the AI retry scope also covers parsing the provider's JSON response, so a malformed response (a Poco::Exception that is not a Poco::IOException) must stay in catch (...) and remain non-retriable, so a billed, non-idempotent request is not repeated for an error retrying cannot fix.

Comments: trimmed the verbose doc comments on isRetriableHTTPError and isRetriableProviderError and the per-branch comments, dropping the url-table-function references as requested.

Verified all changed translation units with -fsyntax-only against the real compile flags. The remaining CI reds are unrelated: the Hung check failed stress flakes (tracked in #107941) and an AST-fuzzer Cannot find input column … in inputs of expression actions DAG logical error in buildPhysicalJoinImpl (a query-plan join-planner issue with no AI code in the stack; it has surfaced stochastically on several unrelated PRs — 107351, 106135, 104119, 103112).

@george-larionov
george-larionov added this pull request to the merge queue Jun 25, 2026
@george-larionov
george-larionov removed this pull request from the merge queue due to a manual request Jun 25, 2026
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.30% -0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

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

Full report · Diff report

@george-larionov

Copy link
Copy Markdown
Member

All failures are unrelated and are tracked with issues or have fixes.

@george-larionov
george-larionov added this pull request to the merge queue Jun 26, 2026
Merged via the queue into master with commit 2571895 Jun 26, 2026
160 of 167 checks passed
@george-larionov
george-larionov deleted the ai-functions-retry-network-errors branch June 26, 2026 07:57
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 26, 2026
rschu1ze added a commit that referenced this pull request Jul 1, 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 Jul 30, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Jul 30, 2026
Cherry pick #107927 to 26.5: AI functions: retry transient network errors like the url table function
robot-clickhouse added a commit that referenced this pull request Jul 30, 2026
alexey-milovidov added a commit that referenced this pull request Jul 31, 2026
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]>
robot-ch-test-poll4 added a commit that referenced this pull request Jul 31, 2026
Cherry pick #107927 to 26.6: AI functions: retry transient network errors like the url table function
robot-clickhouse added a commit that referenced this pull request Jul 31, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 31, 2026
george-larionov added a commit that referenced this pull request Jul 31, 2026
Backport #107927 to 26.5: AI functions: retry transient network errors like the url table function
george-larionov added a commit that referenced this pull request Jul 31, 2026
Backport #107927 to 26.6: AI functions: retry transient network errors like the url table function
george-larionov added a commit that referenced this pull request Jul 31, 2026
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]>
george-larionov added a commit that referenced this pull request Jul 31, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ry-network-errors

AI functions: retry transient network errors like the url table function
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-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.4-must-backport v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants