Skip to content

fix(core): fail model empty-completion before retry - #2968

Open
Buktal wants to merge 1 commit into
agentscope-ai:mainfrom
Buktal:fix/2962-empty-completion-silent-success
Open

Buktal wants to merge 1 commit into
agentscope-ai:mainfrom
Buktal:fix/2962-empty-completion-silent-success

Conversation

@Buktal

@Buktal Buktal commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

AgentScope-Java Version

main @ ea511ec2 (defect observed in production on 2.0.1)

Description

Fixes #2962

When a model provider (or an LLM gateway in front of it) returns HTTP 200 with a stream that completes without any content-bearing chunk — e.g. only the [DONE] marker, or only well-formed chunks whose content parses to empty — the entire chain treated it as a normal successful completion: no error, no retry, no fallback, and no assistant message persisted. To the caller it looked like the model simply chose to say nothing.

Changes

ModelUtils.applyTimeoutAndRetry — the shared path all model implementations route through — now detects empty completions and converts them to a ModelException before retryWhen:

  • Detection: ensureNonEmptyCompletion (new private helper) rejects a stream that completes without any chunk carrying a non-null, non-empty getContent(). Any content block counts (multimodal blocks included); only a fully contentless stream is rejected.
  • Withholding: contentless chunks are withheld until the first content-bearing chunk arrives, then released in order. This guarantees the error is the first downstream signal on an empty completion: switchOnFirst-based fallback commits on the first signal, and the common OpenAI-compatible empty shape (a role-only first chunk, then [DONE]) would otherwise emit a contentless chunk first and bypass the fallback model entirely. Healthy streams are unaffected — withheld chunks are released the moment content arrives, with order and metadata preserved.
  • Placement: after timeout (a timed-out request goes straight to error) and before retry (an empty completion triggers retry like any other model error).
  • Unconditional: the check applies regardless of retry configuration, so a bare agent.call(...) without an ExecutionConfig still surfaces the error instead of ending as silent success.
  • Hardening: applyTimeoutAndRetry no longer NPEs when both options and defaultOptions are null — GenerateOptions.mergeOptions documents that it can return null, and both parameters are documented as nullable.

Tests

ModelTimeoutRetryTest — 6 tests:

  1. Zero chunks (Flux.empty(), the [DONE]-only case) → error.
  2. Two contentless chunks → error as the first downstream signal (no chunk is emitted before it, so a switchOnFirst-based fallback still engages).
  3. Empty first attempt, success on retry → retry engages, attemptCount == 2.
  4. Content-then-mid-stream-error followed by an empty retry attempt → still fails (RetryExhaustedException wrapping ModelException).
  5. Image-only (multimodal) chunks → completes normally.
  6. Leading contentless chunks are released in order once content arrives; trailing contentless chunks pass through.

ReActAgentTest: primary model returns an empty completion (contentless chunks, then complete) → fallback model takes over and answers.

Provider extension tests: mocks that stubbed contentless responses (choices: [], or streaming bodies without any content-bearing delta) were updated to return realistic content-bearing responses, since a contentless completion is now an error by design (OpenAIChatModelTest, DashScopeChatModelTest, DashScopeNonStreamingBlockingBehaviorTest).

Checklist

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test -pl agentscope-core, plus the full agentscope-extensions-model reactor)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (n/a — internal behavior change, covered by Javadoc)
  • Code is ready for review

ModelUtils.applyTimeoutAndRetry's shared path (all model implementations)
now detects empty completions—streams with zero chunks or only chunks
whose content blocks are not TextBlock/ThinkingBlock/ToolUseBlock—and
converts them to ModelException before retryWhen, so the existing retry
and fallback chains engage.

Detection is unconditional (applies regardless of ExecutionConfig/retry
configuration), since empty completion is an upstream transport anomaly
that should always surface as an error. Detection sits after timeout
(a timed-out request bypasses the check and goes straight to error).

Three regression tests: zero-chunk stream, all-empty-content chunks,
and retry-then-success (confirming the error triggers retry and a
subsequent non-empty response completes successfully).

Fixes agentscope-ai#2962
@Buktal
Buktal force-pushed the fix/2962-empty-completion-silent-success branch from aa64284 to 3839e8b Compare September 3, 2026 13:31
@codecov

codecov Bot commented Sep 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@jujn jujn self-assigned this Sep 6, 2026
@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with main and cannot be merged as-is. Please rebase (or merge main) and resolve the conflicts:

git fetch origin
git checkout fix/2962-empty-completion-silent-success
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

Code review is not blocked by this — I will re-review the new head once it is pushed. This is a one-time reminder; @mention me if you want a re-review sooner.


Automated notification by github-manager-bot

@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

Guards model completions that carry zero content-bearing chunks by withholding contentless chunks and surfacing a ModelException before retry, so switchOnFirst-based fallback engages and empty completions retry like any other model error. The per-subscription state via Flux.defer is the right call (retry resubscribes cleanly, no leakage between attempts), the type-agnostic content check avoids misclassifying multimodal completions, and the test matrix (zero chunks / all-empty / retry-then-succeed / mid-stream failure then empty / multimodal / leading-contentless ordering) covers the interesting cases well. Not approving yet mostly for the scope question below: the guard is unconditional across every adapter, which makes an empty completion a billed-retry-and-error for callers that may treat emptiness as a legitimate result.

Two smaller points: usage/finish-reason data is dropped on the rejected path (hurts triage of issue #2962), and the existing non-streaming fixtures were rewritten to carry content rather than asserting the new failure shape.

Also flagging: this PR currently has merge conflicts with main and cannot be merged as-is — see the earlier conflict reminder.


Automated review by github-manager-bot

}

// Apply retry if configured (maxAttempts > 1 means retry is enabled)
responseFlux = ensureNonEmptyCompletion(responseFlux, modelName, provider);

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] This guard is applied unconditionally to every caller of applyTimeoutAndRetry, i.e. all five chat adapters (dashscope / openai / anthropic / gemini / ollama) plus anything that reuses the helper. A completion that used to terminate the stream normally now surfaces as a ModelException, and when maxAttempts > 1 it also consumes retry budget (extra billed calls) for what may be a deterministic provider response — e.g. a content-filter refusal that legitimately returns no content blocks.

Consider making it opt-out-able via GenerateOptions/ExecutionConfig (defaulting to the new behaviour is fine) so callers that treat an empty completion as a valid outcome can keep it, and so the behaviour change is discoverable per call site rather than global-only.

modelName,
provider);
return Mono.error(
new ModelException(

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] When the stream is rejected here, every withheld chunk is dropped, so any usage / finishReason / metadata the provider did send (OpenAI-compatible endpoints commonly send a final usage-only chunk) is lost: the caller cannot account tokens for the attempt and cannot see the provider's finish reason, which is exactly the diagnostic you want when debugging an empty completion.

Suggest keeping the last non-null usage / finishReason observed while withholding and either logging it alongside the warn or exposing it on the exception (e.g. a dedicated EmptyCompletionException carrying the finish reason), so triage does not require a provider-side replay.

* @param chunk the response chunk to inspect
* @return true if the chunk carries at least one content block
*/
private static boolean isContentBearing(ChatResponse chunk) {

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] The type-agnostic rule (any content block counts) is the right default, but it makes an implicit assumption per adapter: that a chunk carrying only a partial tool-call argument fragment still exposes a non-empty getContent(). A provider chunk that surfaces tool-call fragments through metadata rather than a ToolUseBlock would be classified as empty and the error would fire mid-stream.

Worth a one-line note (or a parameterized test) per adapter covering "tool-call-only streaming response" so the assumption is pinned down — DashScopeResponseParser / OpenAIResponseParser build ToolUseBlocks, but the empty-completion path here is shared by all of them.

MockWebServer mockServer = new MockWebServer();
mockServer.start();

// The response must carry content: contentless completions are rejected as upstream

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] This converts the existing mock from a non-streaming JSON body to an SSE body to make the chunk content-bearing, so the previous non-streaming-with-application/json code path is no longer exercised by this case, and the choices: [] shape is no longer asserted at all.

Suggest keeping both: (a) a non-streaming JSON case that returns real content, and (b) an explicit choices: [] case asserting the new ModelException, so the intentional behaviour change is pinned by a test instead of being sidestepped by the fixture rewrite. Same for the OpenAIChatModelTest / DashScopeNonStreamingBlockingBehaviorTest updates.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR has conflicts with the main branch and cannot be merged. Please rebase or merge main into your branch and resolve the conflicts:

git fetch origin
git checkout fix/2962-empty-completion-silent-success
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 conflicts are resolved.


Automated notification 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

P1 紧急不重要

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Zero-chunk model completion ends the ReAct run as silent success - no error, no retry, no fallback

3 participants