Skip to content

fix(core): default retryOn to RETRYABLE_ERRORS when unset in ModelUtils - #2862

Open
Letter2025 wants to merge 3 commits into
agentscope-ai:mainfrom
Letter2025:fix/retryon-default-semantics
Open

Letter2025 wants to merge 3 commits into
agentscope-ai:mainfrom
Letter2025:fix/retryon-default-semantics

Conversation

@Letter2025

Copy link
Copy Markdown
Contributor

Summary

ModelUtils.applyTimeoutAndRetry(...) falls back to error -> true (retry all errors) when ExecutionConfig.getRetryOn() is null, contradicting the documented RETRYABLE_ERRORS default 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 backs MODEL_DEFAULTS), affecting every official model extension (OpenAI, Anthropic, DashScope, Gemini, Ollama) that routes through applyTimeoutAndRetry.

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 retryOn predicate is configured. Explicitly configured predicates are untouched.

Tests

New ModelUtilsRetryDefaultTest (5 cases):

  • 401 is not retried by default
  • 429 is retried up to maxAttempts
  • 400 is not retried by default
  • timeout is retried up to maxAttempts
  • an explicit retryOn predicate is still respected

All pass locally (mvn test -pl agentscope-core -Dtest=ModelUtilsRetryDefaultTest), plus related regression suites (ExecutionConfigTest, GenerateOptionsTest, ModelConfigTest, ModelTimeoutRetryTest) remain green.

Related

Closes #2861

  • [Bug]: ExecutionConfig retry settings are ignored for tool failures #2829 tracks the companion issue on the tool-execution path (ToolExecutor.applyRetry shares the same error -> true fallback, but tool retry is currently dead code because execute() converts failures into normal ToolResultBlock.error signals before retryWhen can observe them). This PR intentionally fixes only the live model path; the tool path deserves separate tracking and a follow-up.

@codecov

codecov Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.88889% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...scope/extensions/model/gemini/GeminiChatModel.java 87.50% 0 Missing and 2 partials ⚠️
...extensions/model/anthropic/AnthropicChatModel.java 90.00% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

Comment on lines +110 to +114
.verify(Duration.ofSeconds(10));

assertEquals(3, attempts.get(), "429 must be retried up to maxAttempts");
}

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Letter2025 added a commit to Letter2025/agentscope-java that referenced this pull request Aug 27, 2026
…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 oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 — onErrorResume changes the exception type that leaves doStream for all subscribers, not just for the retry decision, so non-retryable failures stop arriving as ModelException (with its modelName/provider fields) 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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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))),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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:

  1. Adapt only for the decision — build the predicate here and pass it through GenerateOptions/ExecutionConfig.retryOn instead of rewriting the stream:
Predicate<Throwable> retryOn = e ->
        ExecutionConfig.RETRYABLE_ERRORS.test(e) || isRetryableSdkStatus(e);
  1. 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() >= 500 and return error unchanged 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,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

@Letter2025

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review — all four points addressed in c06bcb2c:

  1. Gemini not adapted (W1) — GeminiChatModel now adapts genai SDK exceptions the same way as Anthropic: a real ApiException (and its ClientException/ServerException subclasses) with 429/5xx is rewritten to HttpTransportException(status, no body, cause) so the default RETRYABLE_ERRORS predicate classifies it correctly; GenAiIOException (transport failure without an HTTP status) adapts to a status-less HttpTransportException which stays retryable. Non-retryable statuses keep their original exception type.

  2. Anthropic onErrorResume rewrites for every subscriber (W2) — narrowed: adaptSdkException now only rewrites retryable statuses (429 / 5xx); anything else flows through unchanged, so ModelException with modelName/provider stays the public surface for auth/400 failures.

  3. Provider error body in retry logs (Info) — both adapters no longer carry the response body into HttpTransportException; only the status is preserved for classification, so per-retry log lines never echo payload fragments.

  4. Changelog (Note) — added an Unreleased → Compatibility entry in release-notes (en/zh) documenting the new retryOn default.

Tests: GeminiChatModelTest 43/43 (incl. real-SDK 429/5xx/4xx/IO adaptation + a doStream retry-count regression), AnthropicChatModelTest 31/31 (incl. 400-keeps-type and no-body assertions), ModelUtilsRetryDefaultTest 7/7; spotless applied; CI re-running.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 — early return error aborts 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 of adaptSdkException (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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

helloworldtang added a commit to helloworldtang/agentscope-java that referenced this pull request Sep 16, 2026
…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.
helloworldtang added a commit to helloworldtang/agentscope-java that referenced this pull request Sep 27, 2026
…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.
@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR now conflicts with main and cannot be merged (mergeable: CONFLICTING, mergeStateStatus: DIRTY). Please rebase (or merge main into your branch) and resolve the conflicts:

git fetch origin
git checkout fix/retryon-default-semantics
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

Once 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.
@Letter2025
Letter2025 force-pushed the fix/retryon-default-semantics branch from c06bcb2 to 90158f8 Compare October 9, 2026 09:48
@Letter2025

Copy link
Copy Markdown
Contributor Author

Conflict resolved — rebased onto current main.

  • fix/retryon-default-semantics was 168 commits behind origin/main; all three commits rebased onto b6a483086. The only conflict was the import block of agentscope-core/src/main/java/io/agentscope/core/model/ModelUtils.java (main now imports java.util.List and java.util.concurrent.atomic.AtomicBoolean alongside TimeoutException); resolved by keeping main's imports.
  • Re-verified the fix is still needed: origin/main still has retryOn = error -> true; // retry all errors by default (ModelUtils.java:119).
  • Local validation on the rebased head: ModelUtilsRetryDefaultTest 7/7, GeminiChatModelTest 44/44, AnthropicChatModelTest 31/31, DashScopeHttpClientTest 77/77, OllamaHttpClientTest 14/14; spotless:apply reports no changes.
  • New head: 90158f868.

@oss-maintainer could you re-review the new head?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: ModelUtils retries auth/request-side errors when retryOn is unset, contradicting RETRYABLE_ERRORS docs

4 participants