Repository navigation
fix(core): default retryOn to RETRYABLE_ERRORS when unset in ModelUtils - #2862
Letter2025 wants to merge 3 commits into
Conversation
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
| .verify(Duration.ofSeconds(10)); | ||
|
|
||
| assertEquals(3, attempts.get(), "429 must be retried up to maxAttempts"); | ||
| } | ||
|
|
There was a problem hiding this comment.
[P1] Preserve timeout classification
The timeout operator above emits a cause-less ModelException, so RETRYABLE_ERRORS rejects the timeout produced by this method itself. With maxAttempts=3 the source is subscribed only once. Preserve a TimeoutException cause/type and test an actually timing-out source.
[P1] Real Anthropic 429 is not recognized
Anthropic RateLimitException reports status 429 but does not implement ModelHttpException, so the new default predicate returns false. ReActAgent's default maxAttempts-only configuration therefore stops after one 429. Adapt provider exceptions to the provider-neutral HTTP contract and add a real SDK-exception test.
There was a problem hiding this comment.
Thanks for the careful review — both issues are real, and both are fixed in 5f973767.
P1 (timeout classification) — Confirmed. The timeout(...) operator produced a cause-less ModelException, so RETRYABLE_ERRORS rejected the timeout generated by this method itself (maxAttempts ended up subscribing once). Fixed in ModelUtils.applyTimeoutAndRetry: the produced error now carries a TimeoutException cause, so classification matches the documented default. ModelUtilsRetryDefaultTest now uses an actually timing-out source (Flux.never() + short timeout) and asserts 3 subscriptions at maxAttempts=3; a second test asserts the TimeoutException is preserved on the cause chain.
P1 (real Anthropic 429) — Confirmed and fixed provider-side. Anthropic's RateLimitException carries status 429 but does not implement ModelHttpException, so the new default predicate returned false and a genuine 429 stopped after one attempt. AnthropicChatModel now runs adaptSdkException(...) over the whole response flux (covers synchronous call, non-streaming CompletableFuture, and stream parsing): any AnthropicServiceException found on the cause chain is remapped to HttpTransportException(status, body, cause) before retry/fallback classification sees it. Tests build a real SDK RateLimitException (429) plus a wrapped-through-cause-chain case, and assert RETRYABLE_ERRORS classifies the adapted error as retryable.
While auditing I found the same gap in DashScopeHttpException and OllamaHttpException (they already carried getStatusCode() but did not implement ModelHttpException); both now implement the contract so 429/5xx classify consistently, with contract tests on each client test class.
Local verification before pushing: core ModelUtilsRetryDefaultTest 7/7, AnthropicChatModelTest 29/29, DashScopeHttpClientTest 62/62, OllamaHttpClientTest 14/14, all green; spotless applied.
…tryable contract Review follow-up for agentscope-ai#2862: - ModelUtils.applyTimeoutAndRetry: the timeout operator produced a cause-less ModelException that RETRYABLE_ERRORS rejected (timeout was never retried despite being a documented retryable error). The produced error now carries a TimeoutException cause so classification matches the docs. - AnthropicChatModel: real SDK rate-limit errors (RateLimitException, 429) do not implement ModelHttpException and were classified non-retryable; adaptSdkException maps AnthropicServiceException (status code + body) to HttpTransportException before retry/fallback sees the error, preserving the SDK exception as cause. - DashScope/Ollama: DashScopeHttpException / OllamaHttpException already carried getStatusCode() but did not implement ModelHttpException; they now do, so 429/5xx classify as retryable consistently. Tests: ModelUtilsRetryDefaultTest now uses an actually-timing-out source and asserts the TimeoutException cause chain; AnthropicChatModelTest builds a real SDK RateLimitException, verifies adaptation and cause-chain lookup; DashScope/Ollama client tests verify the ModelHttpException contract.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Fixes a real defaulting bug: when ExecutionConfig.retryOn was unset, ModelUtils used error -> true, so a 401 or a 400 was retried with backoff even though it can never succeed — while ExecutionConfig.MODEL_DEFAULTS and the docs both describe RETRYABLE_ERRORS as the default. Making the unset case match the documented default is the right direction, the timeout path is handled thoughtfully (a real TimeoutException cause so produced timeouts stay retryable, rather than letting the stricter predicate silently swallow them), and the provider-side contract work (DashScopeHttpException / OllamaHttpException implementing ModelHttpException, the Anthropic SDK adapter) is the correct shape for it. ModelUtilsRetryDefaultTest covers the semantics that actually changed: 401 no, 429 yes, 400 no, real timeout yes, explicit predicate respected.
Verdict: comment — two things I would like resolved before this merges, both about the scope of the behaviour change rather than the direction of the fix.
Findings
- [Warning]
ModelUtils.java:119— the new default is applied per provider only where an exception carries a status the predicate can read. OpenAI already did, Anthropic/DashScope/Ollama are adapted here, but Gemini is not, so a Gemini 429/5xx moves from "retried" to "not retried" as a side effect. - [Warning]
AnthropicChatModel.java:266—onErrorResumechanges the exception type that leavesdoStreamfor all subscribers, not just for the retry decision, so non-retryable failures stop arriving asModelException(with itsmodelName/providerfields) even when retry is off. Narrowing the substitution to the statuses being classified keeps that surface stable. - [Info]
AnthropicChatModel.java:298— the raw provider error body ends up in the message that the retry logger prints; fine if intended, worth a conscious call.
Suggestions
For the Anthropic surface, the one-line narrowing keeps both behaviours intact:
if (current instanceof AnthropicServiceException ase
&& (ase.statusCode() == 429 || (ase.statusCode() >= 500 && ase.statusCode() < 600))) {
return new HttpTransportException(...);
}Everything else keeps flowing through untouched as ModelException, and RETRYABLE_ERRORS still sees a status-coded error exactly where the adaptation was needed.
Cross-repo Note
ModelUtils.applyTimeoutAndRetry is shared by every model extension and by the agentscope-extensions-rag-simple embedding clients, so the retry-default change is wider than the five providers named in the commits. A short line in the changelog/release notes about the new default would save downstream surprises.
Automated review by github-manager-bot
| // Match the documented default: only retry transient/retryable errors | ||
| // (429, 5xx, timeouts, network errors). Retrying auth (401/403) or | ||
| // request-side (400/422) errors is guaranteed to fail again. | ||
| retryOn = ExecutionConfig.RETRYABLE_ERRORS; |
There was a problem hiding this comment.
Aligning the unset default with the documented RETRYABLE_ERRORS is right, and the commit chain shows the hard part was done properly — the timeout signal now carries a real TimeoutException cause precisely so it still classifies as retryable, which is easy to miss.
The part that looks unfinished is the other side of the flip. OpenAIException already implements the contract, and this PR adapts Anthropic (adaptSdkException) plus DashScope and Ollama (their *HttpException now implements ModelHttpException) — but Gemini goes through the same helper and is not adapted:
// GeminiChatModel.doStream0, line 318-323
} catch (Exception e) {
return Flux.error(new ModelException("Gemini API call failed: " + e.getMessage(), e));
}com.google.genai.errors.ApiException (and its ClientException / ServerException subclasses) extends RuntimeException and exposes the status only through code(), so isRetryableError matches no branch, walks a cause chain that is also RuntimeException-shaped, and returns false. Under the previous error -> true those 429/5xx responses were retried; after this change a Gemini caller with a hand-built ExecutionConfig (no explicit retryOn) silently loses retry. Worth deciding explicitly: either add the equivalent adapter for Gemini — the RETRYABLE_ERRORS javadoc already claims timeouts and 5xx are retried, so today that guarantee is provider-dependent — or note the gap in the PR description so it lands as a follow-up rather than riding in with a "fix". The agentscope-extensions-rag-simple embedding clients also call applyTimeoutAndRetry and are worth a look in the same pass.
| // contract) to HttpTransportException so the default RETRYABLE_ERRORS predicate | ||
| // classifies real 429/5xx as retryable. Applies uniformly to errors raised by the | ||
| // synchronous call, the non-streaming CompletableFuture, and stream parsing. | ||
| responseFlux.onErrorResume(e -> Flux.error(adaptSdkException(e))), |
There was a problem hiding this comment.
onErrorResume rewrites the error for every subscriber of the stream, not only the retry operator, so the exception type that leaves doStream changes for all Anthropic users regardless of whether retry is configured: a 401/400 that previously surfaced as ModelException (with modelName/provider populated) now surfaces as HttpTransportException, and Retry.backoff(...) re-throws the last failure once attempts are exhausted. That is a wider contract change than the title implies, and ModelException carries the model/provider fields that callers and the fallback chain use for diagnostics.
Two ways to keep the classification without changing what callers see:
- Adapt only for the decision — build the predicate here and pass it through
GenerateOptions/ExecutionConfig.retryOninstead of rewriting the stream:
Predicate<Throwable> retryOn = e ->
ExecutionConfig.RETRYABLE_ERRORS.test(e) || isRetryableSdkStatus(e);- Or keep the rewrite but re-wrap the non-retryable cases so the public type is stable, i.e. only convert when
ase.statusCode() == 429 || ase.statusCode() >= 500and returnerrorunchanged otherwise. That also stops auth/400 errors from changing type on their way out.
Option 2 is the smaller diff and keeps the cause-chain walk in adaptSdkException useful; it just narrows the substitution to the errors the adapter exists to classify.
| + ase.statusCode() | ||
| + (error.getMessage() != null ? ": " + error.getMessage() : ""), | ||
| ase.statusCode(), | ||
| ase.body() != null ? ase.body().toString() : null, |
There was a problem hiding this comment.
ase.body().toString() goes into responseBody, and HttpTransportException.getMessage() appends it (truncated to 1000 chars) — which ModelUtils then logs on every retry attempt via signal.failure().getMessage(). Provider error bodies can echo fragments of the request payload, so for a framework whose agents routinely put user content into prompts it is worth confirming that this log path is acceptable, or leaving the body out and keeping only the status code. HttpTransportException.toString() is more explicit than getMessage() here if the intent is operator-facing output only.
Otherwise this reads well: the while (current != null) cause-chain walk handles the ModelException wrapper from the synchronous catch, error is preserved as the cause so the original stack survives, and ModelUtilsRetryDefaultTest + the three adapter tests pin down exactly the cases that matter (401 not retried, 429 retried, 400 not retried, explicit retryOn still respected).
|
Thanks for the careful review — all four points addressed in
Tests: |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Follow-up commit addresses my earlier retryOn review feedback well: Anthropic's adaptation is narrowed to genuinely retryable statuses (429/5xx) so non-retryable 4xx keep the stable ModelException type, the provider error body is dropped from the retry/log path, and Gemini gains the equivalent adaptSdkException so a real Gemini 429/5xx is no longer misclassified as terminal. New tests pin all three behaviours (400 passthrough, body-free 429, retryable classification) — nice. CLA signed, MERGEABLE/BLOCKED (blocked only on review state). Verdict: COMMENT — three non-blocking points below, no changes requested.
Findings
- [Warning]
GeminiChatModel.java:373— earlyreturn erroraborts the cause-chain walk (mirrors Anthropic). - [Info]
GeminiChatModel.java:375— branch ordering pins an untested assumption about the genai SDK exception hierarchy. - [Info]
AnthropicChatModel.java:295— 429 log detail, and the per-provider duplication ofadaptSdkException(OpenAI/DashScope still unadapted).
Automated review by github-manager-bot
| return new HttpTransportException( | ||
| "Gemini API request failed with status " + status, status, null, error); | ||
| } | ||
| return error; |
There was a problem hiding this comment.
[Warning] The return error inside the ApiException branch aborts the whole cause-chain walk, so a retryable fault nested deeper than a non-retryable ApiException (or a GenAiIOException wrapped underneath it) is never classified. If that ordering is intentional, a one-line comment saying "first hit wins by design" would help; otherwise current = current.getCause(); continue; keeps searching. Same shape in AnthropicChatModel.adaptSdkException.
| } | ||
| return error; | ||
| } | ||
| if (current instanceof GenAiIOException) { |
There was a problem hiding this comment.
[Info] GenAiIOException is matched after ApiException. If the genai SDK ever throws an ApiException subtype whose code() is a non-HTTP sentinel (0/-1) for a transport failure, this branch is unreachable and the failure lands as non-retryable. Worth a test that pins the hierarchy assumption (e.g. assert a GenAiIOException cause nested under a status-less ApiException still retries), or check GenAiIOException first.
| * @return an {@link HttpTransportException} when the cause chain carries a retryable | ||
| * {@link AnthropicServiceException}, otherwise the original error unchanged | ||
| */ | ||
| static Throwable adaptSdkException(Throwable error) { |
There was a problem hiding this comment.
[Info] Good narrowing on the privacy side (no provider body into the retry/log path). Two follow-ups: (1) the 429 message no longer carries any provider detail, so a support ticket built from logs alone loses the retry-after/error type — consider keeping the SDK toString() (no body) or the retry-after header; (2) adaptSdkException now exists per-provider with subtly different shapes (Anthropic: status-only; Gemini: status + IO branch). OpenAI/DashScope have no equivalent adapter, so if their SDK exceptions also lack ModelHttpException, the same 429-misclassification the Anthropic branch fixed is still live there. Extracting one core helper (HttpTransportException forSdk(Throwable, int) + a shared predicate) and applying it to all providers would keep retry semantics aligned as providers are added.
…se-chain short-circuit, release notes Round-5 review follow-ups: - Move the orphaned retryPrompt javadoc back onto retryPrompt (it had drifted onto the new no-arg unknownFailurePrompt, attaching an @PARAM errors tag to a no-arg method). - Guard against a null rawException on the all-unknown-domain path: walk the attempts for the last non-null rawException and fall back to a synthetic cause, so StructuredOutputUnknownFailureException and its log line always carry the original fault. - Match the fallback short-circuit through the whole cause chain (configuration + unknown-domain failures): an intermediate operator wrap can no longer silently reopen the degrade path. - Add the compatibility note to docs/v2/{en,zh} release notes under Unreleased, mirroring the format of agentscope-ai#2862.
…se-chain short-circuit, release notes Round-5 review follow-ups: - Move the orphaned retryPrompt javadoc back onto retryPrompt (it had drifted onto the new no-arg unknownFailurePrompt, attaching an @PARAM errors tag to a no-arg method). - Guard against a null rawException on the all-unknown-domain path: walk the attempts for the last non-null rawException and fall back to a synthetic cause, so StructuredOutputUnknownFailureException and its log line always carry the original fault. - Match the fallback short-circuit through the whole cause chain (configuration + unknown-domain failures): an intermediate operator wrap can no longer silently reopen the degrade path. - Add the compatibility note to docs/v2/{en,zh} release notes under Unreleased, mirroring the format of agentscope-ai#2862.
|
This PR now conflicts with git fetch origin
git checkout fix/retryon-default-semantics
git rebase origin/main
# resolve conflicts, then:
git push --force-with-leaseOnce the branch is clean, @mention me and I will re-review the new head. This is a one-time reminder for this conflict state. Automated notification by github-manager-bot |
ModelUtils.applyTimeoutAndRetry fell back to retry-all (error -> true) when ExecutionConfig.retryOn was null, contradicting the documented RETRYABLE_ERRORS default and pointlessly retrying auth (401/403) and request-side (400/422) errors. Closes agentscope-ai#2861
…tryable contract Review follow-up for agentscope-ai#2862: - ModelUtils.applyTimeoutAndRetry: the timeout operator produced a cause-less ModelException that RETRYABLE_ERRORS rejected (timeout was never retried despite being a documented retryable error). The produced error now carries a TimeoutException cause so classification matches the docs. - AnthropicChatModel: real SDK rate-limit errors (RateLimitException, 429) do not implement ModelHttpException and were classified non-retryable; adaptSdkException maps AnthropicServiceException (status code + body) to HttpTransportException before retry/fallback sees the error, preserving the SDK exception as cause. - DashScope/Ollama: DashScopeHttpException / OllamaHttpException already carried getStatusCode() but did not implement ModelHttpException; they now do, so 429/5xx classify as retryable consistently. Tests: ModelUtilsRetryDefaultTest now uses an actually-timing-out source and asserts the TimeoutException cause chain; AnthropicChatModelTest builds a real SDK RateLimitException, verifies adaptation and cause-chain lookup; DashScope/Ollama client tests verify the ModelHttpException contract.
… Anthropic narrowing, body hygiene Addresses the oss-maintainer review on the retryOn default change: - Gemini: adapt genai SDK exceptions to the provider-neutral HTTP contract. real 429/5xx now classify as retryable via the default predicate (previously they silently became non-retryable after the retryOn default flip); GenAiIOException (transport failure without an HTTP status) adapts to a status-less HttpTransportException which stays retryable. Non-retryable statuses keep their original exception type. - Anthropic: narrow adaptSdkException to retryable statuses (429/5xx) only, so the ModelException surface (modelName/provider) stays stable for callers and the fallback chain on non-retryable failures. - Both adapters stop carrying the provider error body, so per-retry log lines never echo payload fragments; status is preserved for classification. - release-notes (en/zh) document the new default under Unreleased/Compatibility. Tests: GeminiChatModelTest 43/43, AnthropicChatModelTest 31/31, ModelUtilsRetryDefaultTest 7/7; spotless applied.
c06bcb2 to
90158f8
Compare
|
Conflict resolved — rebased onto current
@oss-maintainer could you re-review the new head? |
Summary
ModelUtils.applyTimeoutAndRetry(...)falls back toerror -> true(retry all errors) whenExecutionConfig.getRetryOn()isnull, contradicting the documentedRETRYABLE_ERRORSdefault and pointlessly retrying auth (401/403) and request-side (400/422) errors — each attempt is guaranteed to fail again, burning latency, quota, and log noise.Change
if (retryOn == null) { - retryOn = error -> true; // retry all errors by default + // Match the documented default: only retry transient/retryable errors + // (429, 5xx, timeouts, network errors). Retrying auth (401/403) or + // request-side (400/422) errors is guaranteed to fail again. + retryOn = ExecutionConfig.RETRYABLE_ERRORS; }Runtime behavior now matches the javadoc of
ExecutionConfig.RETRYABLE_ERRORS(which also backsMODEL_DEFAULTS), affecting every official model extension (OpenAI, Anthropic, DashScope, Gemini, Ollama) that routes throughapplyTimeoutAndRetry.Behavior change notice (intentional)
This is a deliberate bug fix that changes default behavior for callers relying on retry-all semantics: 401/403/400/422 will no longer be retried unless an explicit
retryOnpredicate is configured. Explicitly configured predicates are untouched.Tests
New
ModelUtilsRetryDefaultTest(5 cases):retryOnpredicate is still respectedAll pass locally (
mvn test -pl agentscope-core -Dtest=ModelUtilsRetryDefaultTest), plus related regression suites (ExecutionConfigTest, GenerateOptionsTest, ModelConfigTest, ModelTimeoutRetryTest) remain green.Related
Closes #2861
ToolExecutor.applyRetryshares the sameerror -> truefallback, but tool retry is currently dead code becauseexecute()converts failures into normalToolResultBlock.errorsignals beforeretryWhencan observe them). This PR intentionally fixes only the live model path; the tool path deserves separate tracking and a follow-up.