Repository navigation
Conversation
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
|
期望尽快合并 |
oss-maintainer
left a comment
There was a problem hiding this comment.
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-retryOndefaults toerror -> true, somaxAttempts>1now retries non-idempotent tools; previously this was a no-op for tool exceptions. - [Warning]
ToolExecutor.java:303- oneDefaultToolEmitteris 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- eagerObjects.requireNonNullescapes theonErrorResumecompat contract; wrap inMono.defer. - [Info]
ExceptionUtils.java:117- whole-cause-chain suspension lookup can permanently suspend a genuine failure; consider bounding the walk. Also notecore.utilnow depends oncore.tool.
Suggestions
- Default the tool retry predicate to
ExecutionConfig.RETRYABLE_ERRORS(already available), or gate implicit retries onAgentTool.isReadOnly(), keeping an opt-in for callers that need the current behavior. - Build
executionParam/toolEmitterinside theMono.deferso 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) | |||
There was a problem hiding this comment.
[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:
- Default the tool-path predicate to a whitelist (
ExecutionConfig.RETRYABLE_ERRORSalready exists and is the safer default), or - Gate retries on
AgentTool.isReadOnly(), which is already on the interface, so only read-only tools are retried implicitly, or - Keep
error -> truebut state the new behavior prominently in the changelog /TOOL_DEFAULTSjavadoc, 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)) |
There was a problem hiding this comment.
[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))); |
There was a problem hiding this comment.
[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"); |
There was a problem hiding this comment.
[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) { |
There was a problem hiding this comment.
[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.
|
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-leaseThis 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 |
b028351 to
1cbff72
Compare
|
@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. |
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
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. |
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 completedToolResultBlockerror results before the timeout/retry layers ran, soapplyRetryonly ever saw completed results. Verified onmainwith the reproduction from #2829: a tool throwingIOExceptiononce was invoked only once (maxAttempts=3withRETRYABLE_ERRORSconfigured), and in the timeout comparison the retry layer ran 3 attempts (Retries exhausted: 2/2) without ever re-invoking the tool.Changes:
AgentTool.callAsyncForExecution(...)(newdefaultmethod, backward compatible) plusToolMethodInvoker.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 existingcallAsync(...)contract — failures surface as error results on direct calls — is unchanged and covered by tests for custom, annotation-based, and MCP tools.TimeoutException, whichExecutionConfig.RETRYABLE_ERRORSrecognizes.onRetryExhaustedThrow((spec, signal) -> signal.failure()), instead of the genericRetries exhausted: N/Nmessage.ToolSuspendExceptionanywhere 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 noretryOnpredicate is configured.isError=true) as completed error results so they are never retried.AgentTooland the tool retry semantics onExecutionConfig.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 andToolSuspendException(raw and wrapped), retry-exhaustion error results with id/name, timeout retries, retry isolation in parallel batches, and the direct-call compatibility contract.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.
mvn spotless:applymvn test) —mvn -pl agentscope-core clean verifypasses locally: 2312 tests, 0 failures, 0 errors (9 pre-existing skips); the full-reactorclean verifyruns in CImvn -pl agentscope-core javadoc:javadocpasses withdoclint=all,-missingdefaultmethod, and theExecutionConfigjavadoc is updated in code