Repository navigation
Conversation
- Add a configuration option `maxToolErrorRecoveries` for the maximum number of consecutive streaming tool call error recoveries - Capture recoverable streaming errors related to tool calls during model stream processing, and limit the number of consecutive recoveries - Allow the model to self-correct via a "tool not found" result when a tool call errors, avoiding infinite error loops - Reset the consecutive recovery counter when the stream completes and no recovery occurred - Add recoverability determination logic for streaming errors related to tool calls, ignoring network and server retry errors - Add a `maxToolErrorRecoveries` setter method in `ReActAgent.Builder` to support a custom recovery budget - Add the `maxToolErrorRecoveries` property to `ReactConfig`, including its default value and validation - Implement unit tests covering streaming tool error recovery scenarios and limits, ensuring the recovery mechanism is stable and reliable
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Well-scoped fix for #3102 with an unusually thorough test suite (551 new lines covering the recoverable, budget-exhausted, budget-reset and non-recoverable paths), and the choice to recover in ReActAgent.modelCallStream() rather than inside OpenAIClient is the right one — it is the only layer that can see both the provider error and the accumulated ReasoningContext. I traced the happy path through buildFinalMessage() → runPostReasoningPipeline() (state.contextMutable().add(eventMsg)) → acting() and the assistant message with the hallucinated call does reach persisted state, so the model genuinely gets Tool not found feedback.
The reservations are all about the classification being looser than the design assumes: the isRetryableHttpStatus() guard is a no-op whenever a provider exception carries no status code, and getAllAccumulatedToolCalls() cannot distinguish a complete tool call from one truncated mid-arguments. Recommend tightening both before merge; the rest are nits.
Not approving as review feedback only (and the CLA is still unsigned) — merge decision stays with the maintainers.
Findings
- [Warning]
ReActAgent.java:2649— keyword heuristic is the only real guard whengetStatusCode()is null; tighten with provider error codes. - [Warning]
ReActAgent.java:2650— recovery can fire on a tool call truncated mid-arguments and invoke a real tool with corrupt input. - [Warning]
ReActAgent.java:2661— unsanitized provider error text logged atwarn; add truncation/redaction. - [Warning]
ReActAgent.java:4856—ReactConfig.maxToolErrorRecoveriesis not read back by the builder, so config/persisted-state routes ignore it. - [Info]
ReActAgent.java:2687—doOnCompletemisses cancellation, so "consecutive" reset is best-effort. - [Info]
ReActAgent.java:2864—invalid_toolbranch is subsumed by thetoolbranch. - [Info]
ReactConfig.java:36— wire compatibility OK; flag the default-on behaviour change in release notes and consider a disabled (0) escape hatch.
Suggestions
// illustrative only — tune the alternatives against the real provider error
// catalogue ("non-exist tool", "no such function", "tool_not_found", ...)
// instead of relying on an open-ended substring match.
private static final Pattern UNKNOWN_TOOL = Pattern.compile(
"(non-?exist|not found|does not exist|unknown|invalid|unavailable)"
+ "[a-z_ ]{0,20}(tool|function)"
+ "|(tool|function)[a-z_ ]{0,20}"
+ "(non-?exist|not found|does not exist|unknown|unavailable)",
Pattern.CASE_INSENSITIVE);
private boolean isRecoverableStreamError(Throwable error) {
if (!(error instanceof ModelHttpException he)) {
return false;
}
Integer status = he.getStatusCode();
// no status => cannot prove fail-fast is safe; require an exact error code instead
if (he.isRetryableHttpStatus()) {
return false; // 429 / 5xx stay with transport retry
}
String message = error.getMessage();
return message != null
&& (UNKNOWN_TOOL.matcher(message).find()
|| RECOVERABLE_ERROR_CODES.contains(providerErrorCode(error)));
}and for the completeness gate:
List<ToolUseBlock> pending = context.getAllAccumulatedToolCalls();
boolean streamComplete = pending.stream().allMatch(t ->
toolkit.getToolSchema(t.getName()) != null
&& (t.getContent() == null || t.getContent().isBlank()
|| JsonUtils.isValidJsonObject(t.getContent())));
if (isRecoverableStreamError(error) && !pending.isEmpty() && streamComplete) { ... }Automated review by github-manager-bot
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
|
Thanks for the thorough review — traced findings like the happy-path [Warning] classification when [Warning] truncated tool calls — accepted, and the issue goes one One part of the suggestion we did not take: gating on "name resolves to a [Warning] unsanitized error text in logs — accepted. Both call sites [Warning] [Info] [Info] dead [Info] default-on behavior change — accepted. Validation is now Codecov: the follow-up commit adds tests for 401/422/null-status The issue author's reported message ("LLM is trying to invoke a |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review after 91873d89 (new commits since the previous review). All six points from the first round are addressed, and addressed in the right places:
- Classification now requires
ModelHttpException+ an explicit non-retryable 4xx (401/403/422 excluded, missing status never recovers) + a compiled unknown-tool phrase — auth and schema errors can no longer be swallowed by a baretool/functionkeyword hit. - Truncation gate reads raw accumulator state (
ToolCallsAccumulator#hasIncompleteArguments) instead of the aggregated blocks, which is indeed the only signal that survivesbuild()normalizing a broken payload to{}. - Log hygiene (
sanitizeForLog: 200-char cap +sk-…redaction),maxToolErrorRecoveries(0)= disabled, andBuilder.reactConfig(...)round-trip all look correct, with targeted tests for the 401/422/missing-status/truncated-call paths and CI green (buildubuntu + windows, license, codecov) on an already-signed CLA.
The remaining items are non-blocking: two precision gaps that can make recovery silently under-fire (pattern coverage, argument-less payloads) and three maintainability notes. Nice fix on the original bug — routing the recovery through the existing ToolExecutor "Tool not found" path instead of duplicating it keeps the assistant/tool-call intent intact.
Findings
- [Warning]
ReActAgent.java:2847— unknown-tool pattern is narrower than real provider messages (backtick/quoted names, ambiguousnon-?existorder); needs positive regression tests from real payloads. - [Warning]
ToolCallsAccumulator.java:160— whitespace / JSON-nullraw payloads count as "truncated", blocking recovery for argument-less calls. - [Info]
ReActAgent.java:2652— accumulated tool calls are rebuilt twice per error-path check. - [Info]
ReActAgent.java:4914— stale "must be positive" javadoc and no validation in the setter. - [Info]
ReActAgent.java:2665— a swallowed provider error is invisible abovedebug.
Test coverage note
@730 new lines in ReActAgentStreamErrorRecoveryTest is a strong suite for a first contribution; only the "must not fire" side is encoded today — please add the "must fire" cases with real provider error text so the heuristic cannot rot.
Automated review by github-manager-bot
…mplete, surface recovery at info level
All five follow-ups addressed in the new commit — see inline replies. Worth flagging: the |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review after 49a55e57. All five items from the previous round are fixed, and the fixes are better than what was suggested:
- Pattern (
UNKNOWN_TOOL_NAME_ERROR) — separator class widened to[\w\s.,:;"'()\[\]-]{0,24}(backtick included) andno suchadded to the negation set on both alternatives, so ``The toolmy_tooldoes not exist``,No such function: ...` and the exact #3102 payload now all match. Positive "must fire" regression tests pin each shape, which is what protects the heuristic from rotting later. - Argument-less payloads —
hasCompleteArguments()trims and accepts a literalnull, so zero-arg calls (the exact #3102 shape) are no longer misread as truncated. - Gate ordering — the cheap raw-state scan now runs first and short-circuits before
getAllAccumulatedToolCalls()allocates/aggregates; the double rebuild on the error path is gone. - Setter contract —
maxToolErrorRecoveries(-1)fails fast at the call site, javadoc/@throwsupdated, behaviour pinned by a test. - Observability — the recovery line is
infowithn/maxcounters and sanitized text; the exhausted-budget line stayswarn. Reasonable middle ground between the two rounds' asks.
Findings
- [Info]
ReactConfig.java:40—DEFAULT_MAX_TOOL_ERROR_RECOVERIES = 3means every existing agent silently gains "swallow a provider 4xx and re-run the reasoning loop" behaviour on upgrade. The default-on choice is defensible (bounded, fail-safe at the cap, now logged at info), but since it changes turn behaviour for users who relied on fail-fast, please make sure the release note / migration section calls it out explicitly, as proposed in the thread. - [Info] CI —
build (ubuntu-latest)andbuild (windows-latest)are both failing on49a55e57(run 34763894558). Please rebase on latestmainand push the failing log excerpt; if the breakage is unrelated to this PR, a maintainer re-run would make that visible in the review queue.
Verdict
Code quality, test coverage (+162 lines of targeted regression tests on top of the existing suite) and responsiveness to review feedback are all well above the bar for a first contribution. Approving on the code; merging should wait until the build checks are green.
Automated review by github-manager-bot
…istration Fixes agentscope-ai#3132. A heartbeat failure clears `registered` before re-registering; a concurrent close() reading that window skipped the control-plane DELETE (leaked instance, flaky HttpSelfRegistrationTest on CI). close() now best-effort unregisters whenever an identity exists; test latches widened 2s -> 10s.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of the commit pushed after my approve on 49a55e57: HttpSelfRegistration.close() now unregisters whenever a durable identity exists rather than only while the registered flag is still set, plus wider latch timeouts in the aistio test. The direction is correct — skipping the DELETE while an identity is live leaks the instance on the control plane, and clearing registered mid re-register is exactly how that happens on a loaded runner. The two new findings are about closing the rest of the window (the heartbeat thread is not joined) and about the lifecycle state left behind after close().
Findings
- [Warning]
HttpSelfRegistration.java:149—shutdownNow()interrupts but does not join, so a heartbeat already insidetryRegister()can republishregisteredInstanceId/registered=trueafterclose()has cleared them; claim the identity withgetAndSet(null)and gatetryRegister()on aclosedflag. - [Info]
HttpSelfRegistration.java:153—identityandidentityListenersurviveclose(), soidentity()keeps advertising a deregistered instance and astart()-after-close()replays a credential that has already been DELETEd. - [Info]
HttpSelfRegistrationTest.java:98— the 10s headroom is harmless, but the branch this commit adds (registered == falsewith an identity still set) is not pinned by any assertion.
Verdict
Not a regression — this commit is strictly better than the guard it replaces, and everything here is non-blocking polish on a path that is already best-effort. I have left my earlier approval in place rather than re-approving the new head, since the interleaving above is worth one look before this is considered finished. CI is green on 22bd6ac on both ubuntu and windows, license/cla is signed, and there are no unresolved review threads from the earlier rounds.
Automated review by github-manager-bot
Follows up agentscope-ai#3132: an in-flight tryRegister() could re-publish an identity after close(), leaking it. close() now claims the identity atomically behind a closed flag (respected by the re-register path, with a post-round-trip double-check), DELETEs exactly once, clears the cached identity, refuses start() after close(), and logs lost deregistrations at WARNING.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of the single commit pushed after my round-2 comment (22bd6ac6..ebe75db6). It takes the close() atomicity work seriously and closes most of the gap: a closed flag set before anything else, registeredInstanceId.getAndSet(null) so exactly one caller claims the DELETE, tryRegister() refusing to resurrect a closed instance both on entry and after the control-plane round trip, identity cleared in the finally, deregistration failures promoted from FINE to WARNING, start() after close() refused, and two deterministic tests that drive the re-register window through reflection instead of relying on runner timing. All three items from the previous round are genuinely addressed.
Findings
- [Warning]
HttpSelfRegistration.java:285— theclosedcheck (line 270) and the publication (line 285) are still two separate steps, soclose()can claimnullin between and a heartbeat that finishes the round trip afterwards republishesregisteredInstanceId/identity/registered=true. That is the same "live on the control plane, heartbeated by nobody, deleted by nobody" state the commit exists to prevent, just through a much narrower window. Suggested shape: one lifecycle monitor around "readclosed→ publish" and "closed.set(true)→ claim", or a lock-free retract immediately after line 298. - [Info]
HttpSelfRegistration.java:117—start()now has a hard lifecycle contract but no@throwsin the javadoc, and itsclosed/scheduler != null/scheduler = ...sequence is check-then-act on a non-volatile field. Safe for the only in-repo caller (SessionBridge,synchronized), undeclared for external ones; makingstart()/close()synchronizedfixes this together with the finding above. - [Info]
HttpSelfRegistrationTest.java:136— the branch this commit actually adds (closedobserved after the registration round trip) has no test; blocking the registration handler untilclose()has returned pins it, and would also have surfaced the race above. Worth addingassertEquals(1, deleteCount.get())in the existing case to pin exactly-once deregistration, since try-with-resources closes a second time.
Verdict
COMMENT, nothing blocking. None of the above is a regression — ebe75db6 is strictly better than the guard it replaces and every earlier item is fixed. CI is now fully green on ebe75db6 (build ubuntu + windows, license, module sync, codecov patch), license/cla is signed, and mergeable_state is clean (it was unstable on the previous head only because the windows job was still running). The remaining window is a one-line-of-defence gap in code that is already best-effort with a WARNING log, so the merge call is maintainers'.
Automated review by github-manager-bot
Follows up agentscope-ai#3132: a lifecycleLock now serializes publish against the identity claim, so a registration completing after close() self-deletes exactly once; identity is cleared in all exit paths, start() after close() throws, and the round-trip branch plus exactly-once DELETE are pinned by tests.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of ebe75db6..ff5b86a6. Both items from the previous round are resolved, and the race is closed in the way it needed to be closed rather than papered over: close() sets closed=true before it claims registeredInstanceId via getAndSet(null), and tryRegister() re-checks closed inside the same lifecycle lock before publishing — so whichever side loses the race deterministically deletes the surviving registration instead of leaving an instance that is live on the control plane, heartbeated by nobody and deleted by nobody. identity is now cleared on every close() exit path and start() after close() is refused and documented.
The two new tests are the part I most wanted to see: closeStillDeletesWhenHeartbeatCycleClearedRegisteredFlag and registrationCompletedAfterCloseIsDeletedInsteadOfPublished drive the exact window states through the latch/reflection instead of hoping a runner timing works out, which is the only way a fix like this stays fixed.
Findings
No blocking or non-blocking findings on this increment.
Notes (non-blocking, take or leave)
- The early
closed.get()intryRegister()is intentionally outside the lock to avoid a wasted HTTP round trip; correctness comes from the in-lock re-check, which is fine — worth a one-line comment saying exactly that so a later refactor doesn't "simplify" the second check away. - The DELETE is issued while holding the lifecycle lock, so a concurrent
close()can be delayed by one client timeout. Bounded and acceptable for a registration component; only reconsider if aistio ever lowers that timeout aggressively.
Verdict: re-approved on the current head. Merge decision stays with the maintainers.
Automated review by github-manager-bot
|
@oss-maintainer, a merge-readiness check for current head 443f0fd:\n\n- Review decision is APPROVED.\n- License, module-sync, Ubuntu/Windows builds, codecov/patch, and CLA checks are green.\n- The PR is CLEAN and is the active fix path for #3102.\n\nCould you merge when convenient? |
|
@CryoThrust thanks for the merge-readiness check. Confirming from the bot side: still approved at head Merging is a maintainer decision, so I won't merge it myself — flagging for a human maintainer to land when the pending check settles. If Automated response by github-manager-bot |
AgentScope-Java Version
2.0.3-SNAPSHOT, based on main39cd304a.Description
Fixes #3102.
Problem
When the model hallucinates a tool name during streaming, the provider rejects
the call mid-stream and
OpenAIClientsurfaces it as anOpenAIException(
OpenAI API error in streaming response: LLM is trying to invoke a non-exist tool: ...).ReActAgent.reasoning()only resumes onInterruptedException, sothe exception terminates the whole
streamEventsflow — the turn dies with anerror and the model never gets a chance to self-correct. The local
ToolResultBlock.error("Tool not found: ...")handling inToolExecutorisunreachable for this path because the LLM service rejects the name before the
agent-side executor is ever invoked.
Solution
Recovery now happens in
ReActAgent.modelCallStream(), at the one layer thathas both the error and the accumulated conversation state:
flowchart TD A["Model streams tool_call chunk"] --> B["ReasoningContext accumulates ToolUseBlock"] B --> C["Provider error: unknown tool"] C --> D{"isRecoverableStreamError?<br/>(ModelHttpException + non-retryable<br/>+ tool/function keyword)"} D -- "yes, budget left" --> E["Stream completes normally<br/>(recovery budget +1)"] E --> F["acting executes the hallucinated call"] F --> G["ToolExecutor returns ToolResultBlock.error<br/>'Tool not found: X' tied to call id/name"] G --> H["Next reasoning round:<br/>model sees the error and self-corrects"] D -- "yes, budget exhausted" --> I["Original error propagates, turn fails"] D -- no --> I H -. "a later stream completes without recovery" .-> J["Recovery budget resets to 0"]Key properties:
before the error stay in the
ReasoningContext;buildFinalMessage()emitsthe assistant message with the tool call, and the acting phase executes it.
The fed-back error is a structured
ToolResultBlocktied to the attemptedtool-call id/name (via
ToolResultMessageBuilder), not a free-form assistanttext — mirroring
ToolExecutor's existing "Tool not found" handling insteadof duplicating it.
isRecoverableStreamError). All three musthold:
ModelHttpException(so every provider benefits:OpenAI, DashScope, Anthropic, Gemini, Ollama, ...);
still fail fast and remain the transport-level retry mechanism's job;
tool/function/invalid_toolkeywordssuggesting the provider rejected an unknown tool name.
ReactConfig.max_tool_error_recoveries(default 3, JSON keymax_tool_error_recoveries, buildermaxToolErrorRecoveries(int)). Eachrecovered streaming error increments a per-call counter; once exhausted, the
original provider error propagates and fails the turn with a clear warning —
a confused model cannot loop forever on hallucinated names.
recovery resets the budget (
doOnCompleteon the model-call stream). Thenormal
maxItersiteration budget still applies throughout — noignoreMaxItersbypass.Why not inside
OpenAIClient(the issue's option B)?The issue author suggested converting the error chunk into an error
ChatResponseinside the OpenAI client. This PR deliberately keeps providererror semantics intact and recovers at the agent layer instead:
ReasoningContext, so it cannotknow whether tool calls were already accumulated (the precondition for a
meaningful recovery);
fail-fast semantics for auth/rate-limit/schema errors, which the issue
discussion explicitly wants kept;
ModelHttpExceptioninterface keeps the fixprovider-agnostic — no new typed capability on
ChatResponseis needed, andno OpenAI-extension-only behavior is introduced.
The end state in the conversation is exactly what option B aimed for (assistant
tool-call intent + structured tool error + continued reasoning), achieved
through the existing acting/executor path.
Changes
agentscope-core/.../ReActAgent.javaonErrorResume) inmodelCallStream();isRecoverableStreamError()classification; per-callstreamToolErrorRecoveriesbudget with reset-on-clean-completion;maxToolErrorRecoveriesagent field + builder methodagentscope-core/.../agent/config/ReactConfig.javamax_tool_error_recoveriescomponent (default 3, validated > 0, JSON-creator back-compat with persisted states, 2-arg convenience constructor kept for source compatibility)agentscope-core/.../agent/config/ReactConfigTest.javaagentscope-core/.../agent/ReActAgentStreamErrorRecoveryTest.javaTesting
All scenarios called out in the issue discussion are covered:
called again, turn completes);
function-keyword variant.(exactly 4 model calls); budget resets after an intervening successful
stream (scripted err/err/err → valid-tool → err → text completes all 6
calls and returns the final text); custom cap via the builder (cap=1 → 2nd
error propagates).
RuntimeException, 500, 429,no-accumulated-tool-calls, and non-tool-related messages.
Full
agentscope-coresuite passes: 2350 tests, 0 failures (8 pre-existingskips).
Also fixed (unrelated to #3102, found by this PR's CI)
HttpSelfRegistration.close()could skip the control-planeDELETE when a heartbeat re-register cycle was in flight (flaky test on a
loaded Windows runner; real instance leak).
Known follow-ups (out of scope here)
optional / "only if safe to expose" in the issue).
HarnessAgent.Builder.fromAgent()currently inheritsstopOnRejectonly;migrated agents fall back to the default recovery cap of 3.
Checklist
mvn spotless:applymvn test)