Skip to content

feat(agent): support recovery mechanism for streaming tool call errors - #3131

Open
thinkw wants to merge 18 commits into
agentscope-ai:mainfrom
thinkw:fix/react-stream-tool-error-recovery
Open

thinkw wants to merge 18 commits into
agentscope-ai:mainfrom
thinkw:fix/react-stream-tool-error-recovery

Conversation

@thinkw

@thinkw thinkw commented Sep 13, 2026 •

Copy link
Copy Markdown

AgentScope-Java Version

2.0.3-SNAPSHOT, based on main 39cd304a.

Description

Fixes #3102.

Problem

When the model hallucinates a tool name during streaming, the provider rejects
the call mid-stream and OpenAIClient surfaces it as an OpenAIException
(OpenAI API error in streaming response: LLM is trying to invoke a non-exist tool: ...). ReActAgent.reasoning() only resumes on InterruptedException, so
the exception terminates the whole streamEvents flow — the turn dies with an
error and the model never gets a chance to self-correct. The local
ToolResultBlock.error("Tool not found: ...") handling in ToolExecutor is
unreachable 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 that
has 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"]
Loading

Key properties:

  1. Original assistant/tool-call intent is preserved. Chunks accumulated
    before the error stay in the ReasoningContext; buildFinalMessage() emits
    the assistant message with the tool call, and the acting phase executes it.
    The fed-back error is a structured ToolResultBlock tied to the attempted
    tool-call id/name (via ToolResultMessageBuilder), not a free-form assistant
    text — mirroring ToolExecutor's existing "Tool not found" handling instead
    of duplicating it.
  2. Narrow error classification (isRecoverableStreamError). All three must
    hold:
    • the exception implements ModelHttpException (so every provider benefits:
      OpenAI, DashScope, Anthropic, Gemini, Ollama, ...);
    • the HTTP status is non-retryable — 429 rate limits and 5xx server errors
      still fail fast and remain the transport-level retry mechanism's job;
    • the message contains tool / function / invalid_tool keywords
      suggesting the provider rejected an unknown tool name.
  3. Configurable consecutive-recovery budget. New
    ReactConfig.max_tool_error_recoveries (default 3, JSON key
    max_tool_error_recoveries, builder maxToolErrorRecoveries(int)). Each
    recovered 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.
  4. "Consecutive" semantics. A model stream that completes without
    recovery resets the budget (doOnComplete on the model-call stream). The
    normal maxIters iteration budget still applies throughout — no
    ignoreMaxIters bypass.

Why not inside OpenAIClient (the issue's option B)?

The issue author suggested converting the error chunk into an error
ChatResponse inside the OpenAI client. This PR deliberately keeps provider
error semantics intact and recovers at the agent layer instead:

  • the client layer has no visibility into the ReasoningContext, so it cannot
    know whether tool calls were already accumulated (the precondition for a
    meaningful recovery);
  • unconditional error-chunk-to-response conversion there would silently lose
    fail-fast semantics for auth/rate-limit/schema errors, which the issue
    discussion explicitly wants kept;
  • classifying on the ModelHttpException interface keeps the fix
    provider-agnostic — no new typed capability on ChatResponse is needed, and
    no 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

File Change
agentscope-core/.../ReActAgent.java Recovery (onErrorResume) in modelCallStream(); isRecoverableStreamError() classification; per-call streamToolErrorRecoveries budget with reset-on-clean-completion; maxToolErrorRecoveries agent field + builder method
agentscope-core/.../agent/config/ReactConfig.java New max_tool_error_recoveries component (default 3, validated > 0, JSON-creator back-compat with persisted states, 2-arg convenience constructor kept for source compatibility)
agentscope-core/.../agent/config/ReactConfigTest.java Coverage for the new config field
agentscope-core/.../agent/ReActAgentStreamErrorRecoveryTest.java New test class (see below)

Testing

All scenarios called out in the issue discussion are covered:

  • Recoverable: one unknown-tool error followed by a valid response (model
    called again, turn completes); function-keyword variant.
  • Budget: 3 consecutive unknown-tool errors recover, the 4th propagates
    (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).
  • Non-recoverable still propagates: plain RuntimeException, 500, 429,
    no-accumulated-tool-calls, and non-tool-related messages.

Full agentscope-core suite passes: 2350 tests, 0 failures (8 pre-existing
skips).

Also fixed (unrelated to #3102, found by this PR's CI)

Known follow-ups (out of scope here)

  • Surface registered tool names in the fed-back error hint (discussed as
    optional / "only if safe to expose" in the issue).
  • HarnessAgent.Builder.fromAgent() currently inherits stopOnReject only;
    migrated agents fall back to the default recovery cap of 3.

Checklist

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.)
  • Code is ready for review

- 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
@CLAassistant

CLAassistant commented Sep 13, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@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

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 when getStatusCode() 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 at warn; add truncation/redaction.
  • [Warning] ReActAgent.java:4856 — ReactConfig.maxToolErrorRecoveries is not read back by the builder, so config/persisted-state routes ignore it.
  • [Info] ReActAgent.java:2687 — doOnComplete misses cancellation, so "consecutive" reset is best-effort.
  • [Info] ReActAgent.java:2864 — invalid_tool branch is subsumed by the tool branch.
  • [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

codecov Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.03704% with 14 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...e/src/main/java/io/agentscope/core/ReActAgent.java 86.66% 1 Missing and 7 partials ⚠️
...s/controlplane/transport/HttpSelfRegistration.java 81.25% 4 Missing and 2 partials ⚠️

📢 Thoughts on this report? Let us know!

@thinkw

thinkw commented Sep 13, 2026

Copy link
Copy Markdown
Author

Thanks for the thorough review — traced findings like the happy-path
persistence check are exactly what we wanted validated. Status of each
finding (all fixes in the follow-up commit):

[Warning] classification when getStatusCode() is null — accepted.
Recovery now requires an explicit, non-retryable 4xx status: 401/403
(auth/permission) and 422 (schema validation) are excluded, 429/5xx stay
with transport retry, and a missing status code never recovers (if
fail-fast safety cannot be proven, we fail fast). The bare keyword match
is replaced by a compiled pattern requiring an explicit unknown-tool
phrase — a negation ("non-existent", "not found", "does not exist",
"unknown", "unavailable", "invalid") adjacent to tool|function — so an
auth error whose text happens to contain "function" no longer matches.

[Warning] truncated tool calls — accepted, and the issue goes one
level deeper than described.
The suggested completeness gate on the
aggregated blocks can never fire: ToolCallsAccumulator.ToolCallBuilder#build()
already normalizes a truncated raw argument payload to an empty object
(content = "{}"), so the corruption is invisible at
getAllAccumulatedToolCalls() — recovery would proceed with a
seemingly-valid empty argument object, which is arguably worse than a
corrupt one. The fix therefore reads the raw stream state:
ToolCallsAccumulator#hasIncompleteArguments() (per-builder
hasCompleteArguments(): empty payload = argument-less call, otherwise
the accumulated raw JSON must parse), surfaced through
ReasoningContext#hasIncompleteToolCallArguments(), and the recovery
condition now requires !context.hasIncompleteToolCallArguments().
Tests cover the truncated-mid-arguments shape propagating, and an
argument-less hallucinated call still recovering.

One part of the suggestion we did not take: gating on "name resolves to a
registered tool". A provider rejects a hallucinated name precisely because
it is not in the tool schema list — which the framework derives from the
agent's own toolkit — so requiring a registered name would disable the
core scenario of #3102 by construction. The JSON-completeness gate is the
safe boundary: truncated calls fail fast, argument-less hallucinated calls
recover into Tool not found.

[Warning] unsanitized error text in logs — accepted. Both call sites
now go through a sanitizeForLog helper (200-char truncation +
redaction of sk-…-style tokens); the happy-recovery line is debug,
the exhausted-budget line stays warn.

[Warning] ReactConfig value not read back — accepted. Added
Builder.reactConfig(ReactConfig) which initializes
maxIters/stopOnReject/maxToolErrorRecoveries from an existing config
(explicit setters afterwards take precedence), with a round-trip test.
This also gives HarnessAgent.Builder.fromAgent() a clean path to
inherit the cap later.

[Info] doOnComplete misses cancellation — explained, javadoc
clarified, no logic change.
Cancellation of a model-call stream ends
this per-call execution anyway: the counter lives on CallExecution
(one per call), so there is no cross-turn leak; and within one call,
keeping the credit across a middleware re-subscription matches the
per-call budget semantics. Resetting at reasoning-loop entry (the
suggested alternative) would make the budget meaningless — it would no
longer count across iterations. The field doc now states this
explicitly.

[Info] dead invalid_tool branch — accepted. Subsumed by the
compiled pattern.

[Info] default-on behavior change — accepted. Validation is now
>= 0, and maxToolErrorRecoveries(0) / max_tool_error_recoveries: 0
disable recovery entirely for users who rely on fail-fast. We'll call
the default-on change out in the release notes.

Codecov: the follow-up commit adds tests for 401/422/null-status
propagation, truncated-argument propagation, cap=0, and the
reactConfig round-trip, which should close the reported gaps —
please re-check after CI.

The issue author's reported message ("LLM is trying to invoke a
non-exist tool: ...", non-numeric error code → status 400) still
recovers under the tightened rules, verified locally.

@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

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 bare tool/function keyword hit.
  • Truncation gate reads raw accumulator state (ToolCallsAccumulator#hasIncompleteArguments) instead of the aggregated blocks, which is indeed the only signal that survives build() normalizing a broken payload to {}.
  • Log hygiene (sanitizeForLog: 200-char cap + sk-… redaction), maxToolErrorRecoveries(0) = disabled, and Builder.reactConfig(...) round-trip all look correct, with targeted tests for the 401/422/missing-status/truncated-call paths and CI green (build ubuntu + 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, ambiguous non-?exist order); needs positive regression tests from real payloads.
  • [Warning] ToolCallsAccumulator.java:160 — whitespace / JSON-null raw 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 above debug.

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

@thinkw

thinkw commented Sep 13, 2026

Copy link
Copy Markdown
Author

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 bare tool/function keyword hit.
  • Truncation gate reads raw accumulator state (ToolCallsAccumulator#hasIncompleteArguments) instead of the aggregated blocks, which is indeed the only signal that survives build() normalizing a broken payload to {}.
  • Log hygiene (sanitizeForLog: 200-char cap + sk-… redaction), maxToolErrorRecoveries(0) = disabled, and Builder.reactConfig(...) round-trip all look correct, with targeted tests for the 401/422/missing-status/truncated-call paths and CI green (build ubuntu + 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, ambiguous non-?exist order); needs positive regression tests from real payloads.
  • [Warning] ToolCallsAccumulator.java:160 — whitespace / JSON-null raw 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 above debug.

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

All five follow-ups addressed in the new commit — see inline replies. Worth flagging: the
suggested separator class didn't cover the backticks in your own example, so we extended it
and pinned both rounds' asks (positive "must fire" + negative "must not fire") with tests.
Local CI: 2364 tests, 0 failures.

@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

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 literal null, 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/@throws updated, behaviour pinned by a test.
  • Observability — the recovery line is info with n/max counters and sanitized text; the exhausted-budget line stays warn. Reasonable middle ground between the two rounds' asks.

Findings

  • [Info] ReactConfig.java:40 — DEFAULT_MAX_TOOL_ERROR_RECOVERIES = 3 means 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) and build (windows-latest) are both failing on 49a55e57 (run 34763894558). Please rebase on latest main and 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 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

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 inside tryRegister() can republish registeredInstanceId / registered=true after close() has cleared them; claim the identity with getAndSet(null) and gate tryRegister() on a closed flag.
  • [Info] HttpSelfRegistration.java:153 — identity and identityListener survive close(), so identity() keeps advertising a deregistered instance and a start()-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 == false with 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 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

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 — the closed check (line 270) and the publication (line 285) are still two separate steps, so close() can claim null in between and a heartbeat that finishes the round trip afterwards republishes registeredInstanceId / 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 "read closed → 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 @throws in the javadoc, and its closed / 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; making start()/close() synchronized fixes this together with the finding above.
  • [Info] HttpSelfRegistrationTest.java:136 — the branch this commit actually adds (closed observed after the registration round trip) has no test; blocking the registration handler until close() has returned pins it, and would also have surfaced the race above. Worth adding assertEquals(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 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

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() in tryRegister() 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

@CryoThrust

Copy link
Copy Markdown
Contributor

@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?

@oss-maintainer

Copy link
Copy Markdown
Collaborator

@CryoThrust thanks for the merge-readiness check. Confirming from the bot side: still approved at head b58b3685 (no new pushes since), currently mergeable_state=unstable — required checks pass (Check License, Check Module Sync, Ubuntu/Windows builds, license/cla) with codecov/patch still pending.

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 unstable persists because of a flaky required check, a maintainer re-run or a rebase onto current main would be the next step.


Automated response by github-manager-bot

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]:ReActAgent 调用不存在的工具时直接退出 ReAct 循环,未给模型重试机会

5 participants