Skip to content

fix(tool): honor execution config retries for tool exceptions - #2830

Open
kevinvv03 wants to merge 2 commits into
agentscope-ai:mainfrom
kevinvv03:fix/tool-retry-on-exceptions
Open

kevinvv03 wants to merge 2 commits into
agentscope-ai:mainfrom
kevinvv03:fix/tool-retry-on-exceptions

Conversation

@kevinvv03

@kevinvv03 kevinvv03 commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.0.3-SNAPSHOT

Description

Fixes #2829.

Background: Tool calls never honored the retry settings in ExecutionConfig. ToolExecutor.executeCore(...) converted tool failures into completed ToolResultBlock error results before the timeout/retry layers ran, so applyRetry only ever saw completed results. Verified on main with the reproduction from #2829: a tool throwing IOException once was invoked only once (maxAttempts=3 with RETRYABLE_ERRORS configured), and in the timeout comparison the retry layer ran 3 attempts (Retries exhausted: 2/2) without ever re-invoking the tool.

Changes:

  • Add an execution channel: AgentTool.callAsyncForExecution(...) (new default method, backward compatible) plus ToolMethodInvoker.invokeRawAsync(...), which keep failures as reactive error signals. ToolExecutor.executeWithInfrastructure(...) now runs this channel through scheduling → timeout → retry → shutdown and converts the final error into an error result only after retries are exhausted. The existing callAsync(...) contract — failures surface as error results on direct calls — is unchanged and covered by tests for custom, annotation-based, and MCP tools.
  • Make tool timeouts retryable: the timeout fallback now emits TimeoutException, which ExecutionConfig.RETRYABLE_ERRORS recognizes.
  • Preserve the root cause when retries are exhausted via onRetryExhaustedThrow((spec, signal) -> signal.failure()), instead of the generic Retries exhausted: N/N message.
  • Detect ToolSuspendException anywhere in the cause chain (ExceptionUtils.findToolSuspendException(...), identity-guarded against circular causes) so suspensions — even wrapped in reflection/future/arbitrary exceptions — become suspended results and are never retried, including under the retry-everything fallback when no retryOn predicate is configured.
  • Keep MCP protocol-level business errors (isError=true) as completed error results so they are never retried.
  • Document the execution-channel contract on AgentTool and the tool retry semantics on ExecutionConfig.TOOL_DEFAULTS.

How to test:

  • mvn -pl agentscope-core test -Dtest=ToolExecutorTest — 18 new end-to-end tests (class total: 30), covering retry of annotation tools (sync/Mono/CompletableFuture) and MCP transport failures, no-retry for protocol-level business errors and ToolSuspendException (raw and wrapped), retry-exhaustion error results with id/name, timeout retries, retry isolation in parallel batches, and the direct-call compatibility contract.
  • The reproduction from [Bug]: ExecutionConfig retry settings are ignored for tool failures #2829 now returns the recovered result after 2 attempts (state=RUNNING, output ["recovered"]), and the timeout comparison re-invokes the tool on every attempt with the root cause preserved (Tool execution timeout after PT0.1S).

Checklist

Please check the following items before code is ready to be reviewed.

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test) — mvn -pl agentscope-core clean verify passes locally: 2312 tests, 0 failures, 0 errors (9 pre-existing skips); the full-reactor clean verify runs in CI
  • Javadoc comments are complete and follow project conventions — mvn -pl agentscope-core javadoc:javadoc passes with doclint=all,-missing
  • Related documentation has been updated (e.g. links, examples, etc.) — no doc changes needed; the new API is a backward-compatible default method, and the ExecutionConfig javadoc is updated in code
  • Code is ready for review

@CLAassistant

CLAassistant commented Aug 24, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@kevinvv03 kevinvv03 closed this Aug 24, 2026
@kevinvv03 kevinvv03 reopened this Aug 24, 2026
@codecov

codecov Bot commented Aug 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.85507% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...n/java/io/agentscope/core/util/ExceptionUtils.java 73.33% 1 Missing and 3 partials ⚠️
...ain/java/io/agentscope/core/tool/ToolExecutor.java 90.62% 1 Missing and 2 partials ⚠️

📢 Thoughts on this report? Let us know!

@guslegend0510 guslegend0510 left a comment

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.

LGTM

@Leslie-ZH1023

Copy link
Copy Markdown

期望尽快合并

@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

Wiring the raw execution channel so ExecutionConfig retries actually apply to tool exceptions is the right fix, and the new test matrix (sync / Mono / CompletableFuture / MCP transport vs protocol / suspend / retryOn / parallel isolation / direct-path contract) is thorough. The useExecutionPath split correctly keeps Toolkit.callTool semantics intact, which was the risky part.

My main concern is upstream of the code: this turns a previously inert setting into a live one. Anyone who already set maxAttempts > 1 on a tool path (with the default permissive retryOn) will start re-executing side-effecting tools after a transient failure once they upgrade, and the worst-case latency of a single tool call becomes maxAttempts x timeout. That deserves an explicit decision on the default retry predicate plus a changelog note before merge.

Findings

  • [Critical] ToolExecutor.java:506 - retryOn defaults to error -> true, so maxAttempts>1 now retries non-idempotent tools; previously this was a no-op for tool exceptions.
  • [Warning] ToolExecutor.java:303 - one DefaultToolEmitter is reused across retry attempts, so chunks emitted by the discarded attempt are already delivered before the retry re-emits.
  • [Warning] ToolExecutor.java:483 - timeout is applied per attempt, not cumulatively; document it or bound total elapsed time.
  • [Info] McpTool.java:206 - eager Objects.requireNonNull escapes the onErrorResume compat contract; wrap in Mono.defer.
  • [Info] ExceptionUtils.java:117 - whole-cause-chain suspension lookup can permanently suspend a genuine failure; consider bounding the walk. Also note core.util now depends on core.tool.

Suggestions

  • Default the tool retry predicate to ExecutionConfig.RETRYABLE_ERRORS (already available), or gate implicit retries on AgentTool.isReadOnly(), keeping an opt-in for callers that need the current behavior.
  • Build executionParam / toolEmitter inside the Mono.defer so each attempt is isolated.
  • Add a test asserting chunk callbacks are not duplicated across a retry - that gap is exactly what makes the emitter finding invisible to CI.

Overall: solid fix and excellent test coverage; I would only settle the default-retry-policy question so the upgrade path is safe for existing configurations.


Automated review by github-manager-bot

@@ -450,6 +504,8 @@ private Mono<ToolResultBlock> applyRetry(
.maxBackoff(maxBackoff)
.jitter(0.5)
.filter(retryOn)

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.

[Critical] Silent behavior change: maxAttempts > 1 now retries non-idempotent tools.

Before this PR, a tool exception was converted into a completed ToolResultBlock error result before applyRetry ran, so retryOn never matched and maxAttempts was effectively inert for tool failures. Wiring the raw channel through makes the setting live — but retryOn defaults to error -> true when the caller configures only maxAttempts (as retryConfig(int) in the new tests does):

Predicate<Throwable> retryOn =
        config.getRetryOn() != null ? config.getRetryOn() : error -> true;

So any existing user who set maxAttempts=3 (e.g. copied from a model-call config) will now silently re-execute side-effecting tools — file writes, ShellExecuteTool, MCP POST-style calls — after a transient failure. That is a correctness regression risk for upgrade, not just a fix.

Suggested, either:

  1. Default the tool-path predicate to a whitelist (ExecutionConfig.RETRYABLE_ERRORS already exists and is the safer default), or
  2. Gate retries on AgentTool.isReadOnly(), which is already on the interface, so only read-only tools are retried implicitly, or
  3. Keep error -> true but state the new behavior prominently in the changelog / TOOL_DEFAULTS javadoc, since the added note documents the mechanics but not the "previously inert, now active" migration hazard.

Mono<ToolResultBlock> invocation;
if (useExecutionPath) {
invocation =
Mono.defer(() -> tool.callAsyncForExecution(executionParam))

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 ToolEmitter is created once per executeCore call but reused by every retry attempt.

toolEmitter (line ~273) and executionParam are built outside the Mono.defer, so re-subscription re-invokes callAsyncForExecution with the same emitter, whose chunkCallback is the caller's sink. With maxAttempts > 1, the partial chunks emitted by the discarded attempt have already been delivered before the retry re-emits from scratch, so the UI / streaming consumer can see duplicated or interleaved tool output.

The doBeforeRetry log already admits the previous "attempt is cancelled and may still be consuming resources" — cancellation stops further emissions but cannot retract what was already pushed.

Consider moving the emitter + executionParam construction inside the Mono.defer so each attempt gets a fresh emitter, or suppress chunk callbacks for attempts after the first (e.g. an attempt counter captured by the emitter) and note the chosen semantic in the callAsyncForExecution javadoc.

return execution.timeout(
timeout,
Mono.error(new RuntimeException("Tool execution timeout after " + timeout)));
Mono.error(new TimeoutException("Tool execution timeout after " + timeout)));

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] Timeout is applied per attempt, so worst-case latency becomes maxAttempts × timeout plus backoff.

applyTimeout runs before applyRetry, which is the right ordering for making timeouts retryable, but it means the configured TOOL_DEFAULTS 5-minute timeout is now a per-attempt budget. With maxAttempts=3 a single tool call can occupy the ReAct loop for 15+ minutes, which callers of callTools(...) and any upstream agent/turn deadline probably do not expect.

Would be good to either bound the total elapsed time (apply the timeout outside the retry layer as an overall deadline in addition to the per-attempt one), or document explicitly in the ExecutionConfig javadoc that timeout is per attempt, not cumulative.

*/
@Override
public Mono<ToolResultBlock> callAsyncForExecution(ToolCallParam param) {
Objects.requireNonNull(param, "param must not be 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.

[Info] Objects.requireNonNull at assembly time escapes the compat onErrorResume.

callAsync is now callAsyncForExecution(param).onErrorResume(...), but callAsyncForExecution validates param eagerly, so a null argument throws synchronously at method-invocation time instead of surfacing through the Mono. The .onErrorResume in callAsync cannot catch it, which breaks the "direct path always returns an error result" contract this PR documents (and asserts in shouldKeepCallAsyncContractOnDirectCalls).

Wrapping the body in Mono.defer(() -> { ... }) keeps the validation on the subscribe path so both channels behave uniformly. Same pattern as the Mono.defer you already added in ToolExecutor.executeCore.

* @param error the throwable to inspect (may be {@code null})
* @return the first {@link ToolSuspendException} found, or {@code null} if none is present
*/
public static ToolSuspendException findToolSuspendException(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] Whole-cause-chain matching can turn a genuine failure into a permanent suspension.

findToolSuspendException walks the entire chain, so any error that merely wraps a ToolSuspendException (rather than signalling a suspension) is reported as ToolResultBlock.suspended(...), and the agent will then wait for an external result that can never arrive. shouldNotRetryWrappedToolSuspension shows this is deliberate, but the blast radius is larger than it looks once tools start composing sub-calls.

Two small hardening options: bound the walk to the first N causes (or only direct cause + one level), or log at warn when a wrapped suspension is detected so a mis-classified suspension is diagnosable instead of silent. Also worth noting io.agentscope.core.util now depends on io.agentscope.core.tool, a small layering inversion for a util package — the tool-facing helper could live next to ToolSuspendException instead.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with the target branch and cannot be merged. Please rebase or merge the latest target branch into your branch and resolve the conflicts:

git fetch origin
git checkout fix/tool-retry-on-exceptions
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

This is a one-time reminder. Feel free to @mention me for a re-review after the conflicts are resolved.


Automated notification by github-manager-bot

@kevinvv03
kevinvv03 force-pushed the fix/tool-retry-on-exceptions branch from b028351 to 1cbff72 Compare October 20, 2026 15:42
@kevinvv03

Copy link
Copy Markdown
Contributor Author

@oss-maintainer Thanks for the review! I've pushed the follow-up fixes in 1cbff72, resolved the merge conflicts, and all CI checks are now green.
The update addresses the retry policy, streaming isolation, MCP error handling, and upgrade documentation discussed in the review. A developer has also requested that this fix be merged soon.
Could you please re-review the latest commit and let me know if any merge blockers remain? If it's ready, could a maintainer help get this merged? I'm happy to address any remaining concerns promptly. Thanks!

@jujn jujn added the P2 重要不紧急 label Nov 4, 2026
@mintlify

mintlify Bot commented Nov 9, 2026

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit a7bf6ab.

Approve preview

@kevinvv03

Copy link
Copy Markdown
Contributor Author

期望尽快合并

Hi @jujn, I hope you don’t mind me following up on Leslie-ZH1023’s earlier comment. I’ve synced this PR with upstream main and resolved the merge conflicts.

May I ask when you might have time to review it? If the changes look good to you, I’d also appreciate a rough idea of when the PR might be able to merge. If you have any concerns about the implementation or tests, I’d be happy to take another look at the code, add coverage where needed, and make revisions based on your feedback.

Thank you for your time.

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]: ExecutionConfig retry settings are ignored for tool failures

6 participants