Repository navigation
Description
Environment
- AgentScope-Java:
main @ 2f0da9708(2.1.0-SNAPSHOT) - Model path:
agentscope-extensions-model-openai(OpenAIChatModel) against an
OpenAI-compatible endpoint behind an LLM gateway (multi-tenant production deployment) - JDK 17, streaming (
stream=true) throughout
Describe the bug
When a streaming chat completion is cut mid-generation — the gateway or provider
closes the connection early, so the SSE stream simply ends without the [DONE]
sentinel and without any chunk carrying finish_reason — the entire stack treats the
partial content as a normal, successful completion:
- no error is raised anywhere,
- no WARN/ERROR is logged,
- the retry machinery never engages,
- the truncated text is persisted as a complete assistant turn and delivered to the user
as if the model had finished normally.
In production (multi-tenant gateway) this surfaces as users receiving silently
truncated answers. Because nothing fails, it cannot be distinguished from a model that
"just said less" — neither by ops dashboards nor by the conversation history.
Root-cause chain (current main)
1. Transport: a clean server-side FIN is a normal completion.
JdkHttpTransport.processStreamResponse parses the body via blocking line reads:
// agentscope-core/src/main/java/io/agentscope/core/model/transport/JdkHttpTransport.java
return Flux.fromStream(reader.lines()) // server closes mid-stream → reader ends
// → Flux completes NORMALLY, no errorA server that closes the connection mid-SSE produces onComplete, not onError.
Read-timeout configuration does not help: it only fires on silence, not on a clean
FIN.
2. OpenAIClient: [DONE] is consumed but never checked.
// agentscope-extensions-model-openai/.../OpenAIClient.java
return transport.stream(httpRequest)
.takeWhile(data -> !SSE_DONE_MARKER.equals(data)) // completes ON [DONE],
// but a stream that ENDS
// without it also just completes
.<OpenAIResponse>handle((data, sink) -> {
OpenAIResponse response = parseStreamData(data);
...
sink.next(response);
// no finish_reason tracking, no completeness check
})takeWhile guarantees the Flux completes when [DONE] arrives, but nothing verifies
that it (or a finish_reason chunk) ever did. Per the OpenAI streaming spec, the
[DONE] sentinel is mandatory, and the final chunk always carries finish_reason —
their joint absence means the response did not finish.
3. ModelUtils.applyTimeoutAndRetry: the emission guard only governs errors that
are raised. The #3058 guard correctly skips retrying after visible content was
emitted (preventing duplicated content) — but in this scenario no error is ever raised,
so the guard is never consulted.
4. ReasoningContext / ReActAgent: partial accumulation is final. The reasoning
accumulator builds the final assistant message from whatever chunks arrived; a message
with real (partial) content is a perfectly "successful" result, so the run finishes
normally and the turn is persisted.
Minimal reproduction (mock SSE)
data: {"object":"chat.completion.chunk","choices":[{"delta":{"role":"assistant","content":"Here is the first part of the an"},"finish_reason":null}]}
data: {"object":"chat.completion.chunk","choices":[{"delta":{"content":"swer, and the second part incl"},"finish_reason":null}]}
<server closes the connection — no finish_reason chunk, no data: [DONE]>
Result on current main: the assistant turn ends with "…the second part incl" as a
complete answer — finish_reason == null, no log, no retry, no error event.
How we hit it
Multi-tenant production deployment, every tenant's agent behind a shared OpenAI-compatible
gateway. During a gateway rolling-redeploy / connection-recycling window, mid-generation
SSE connections were closed cleanly. The framework accepted each truncated stream as a
complete answer; end users received cut-off replies, and because the turn persisted
normally, the failure was invisible to monitoring. We only traced it by diffing response
lengths against direct-to-provider calls.
We are aware the frequency of this depends on gateway behavior (idle timeouts, deploys,
load balancing) — but we could find no configuration path in the framework that makes
a completion-signal-less stream surface as anything other than success. That is the gap
this issue reports.
Related but distinct (please see before closing as duplicate)
- [Bug]: Zero-chunk model completion ends the ReAct run as silent success - no error, no retry, no fallback #2962 / fix(core): fail model empty-completion before retry #2968 — the empty variant: a
[DONE]-only / zero-content stream ends as
silent success. Same family ("no completeness check"), opposite symptom: ours has
partial content, sobuildFinalMessage()returns a real message and none of the
empty-response paths trigger. fix(core): fail model empty-completion before retry #2968's fail-empty check would not fire here. - [Bug]: Streaming retry re-subscribes the model and duplicates already-delivered chunks #2478 / fix(model): streaming retry re-delivers already-sent chunks downstream #2479 / [Bug]: Model retry misclassifies streaming transport errors (Connection reset) as non-retryable when wrapped by OpenAIException with null status code #3057 / fix(core): retry streaming transport errors wrapped by ModelHttpException without status code #3058 — retry duplication safety: those govern retries
after an error is raised. In this scenario no error is raised at all; fix(core): retry streaming transport errors wrapped by ModelHttpException without status code #3058's
emission guard is never consulted. - [Bug]:模型输出长度截断后遗留不完整工具调用,导致任务未完成或重复失败 #2648 / feat(core): 阻止长度截断的不完整工具调用执行并引导模型分块恢复 #2649 —
finish_reason=lengthtruncation: the provider confirms
completion with an explicit reason. Here the provider never confirms anything. - [Bug]: ReActAgent treats thinking-only final response as finished - user receives no text message, silent failure #2750 / fix(core): retry empty final responses instead of finishing silently #2755 — empty final response retry (thinking-only turns).
Suggested direction (we run this in production)
We fixed this in production and are happy to upstream it. Sketch:
- Detect.
OpenAIClienttracks whether either completion signal was seen
([DONE]sentinel or any chunk carryingfinish_reason); if the stream completes
with neither, error with a typed exception (e.g.IncompleteStreamException)
implementing a small capability interface (PartialStreamContent) that says
"content may already be downstream".
.concatWith(Flux.defer(() -> sawCompletionSignal.get()
? Flux.empty()
: Flux.error(new IncompleteStreamException(
"streaming response ended without [DONE] or finish_reason chunk; "
+ "response is likely truncated", emittedChunks > 0, emittedChunks))))-
Keep generic retry away from it.
ModelUtils's defaultretryOnexcludes
PartialStreamContent— a blind flux-level resubscription would duplicate the
already-delivered chunks (composes with fix(core): retry streaming transport errors wrapped by ModelHttpException without status code #3058's emission guard rather than
replacing it). -
Retry safely at the reasoning layer.
ReActAgentretries such a model call
once afterReasoningContext.resetStreamState()(text/thinking/tool-call
accumulators, chunk history, metadata), so the retried attempt's content replaces
the aborted attempt's partial content instead of concatenating. Each attempt gets a
freshreplyId;ModelCallStartEventcarries anattemptnumber and
ModelCallEndEventexposes the providerfinishReason, so downstream consumers can
drop the aborted attempt's partial content instead of duplicating it. -
Observability. Surfacing
finishReasononModelCallEndEventalso gives
consumers a general "provider did not confirm completion" signal (null=
unconfirmed) even on deployments where throwing is undesired.
Scope note: the DashScope client appears to have the same structural gap
(finishReason exists in the DTOs but is never used as a completion signal) — worth
aligning whatever approach is chosen.
One compatibility consideration: an OpenAI-compatible server that (non-compliantly)
never sends [DONE] nor finish_reason even on success would start failing under a
strict check. If that is a concern, the strictness could be configurable — we'd defer
to maintainers on the default.
Checklist
- Could not find an existing open issue for this exact behavior (searched
finish_reason,[DONE],truncated,stream closed; nearest ones listed above)
Activity
pcbeingused333 commentedon Oct 28, 2026
The cause matches what the report found: in
OpenAIClient.streamthetakeWhileon the[DONE]sentinel only ends the Flux early, and nothing after it records whether[DONE]or a chunk with a non-nullfinish_reasonwas ever seen, so a connection closed mid-stream completes the Flux like a normal answer.A possible shape: keep two
AtomicBooleans next toseenChunk(one set when[DONE]is matched, one when a choice carries afinish_reason), andconcatWith(Flux.defer(...))a final step that errors when neither was set after at least one chunk arrived. The error would be a retryable one, soModelUtils.applyTimeoutAndRetrycan decide with its existing emitted-content guard (#3058) whether a retry is safe. Requiring both signals to be absent, rather than only[DONE], keeps OpenAI-compatible providers that omit[DONE]but do sendfinish_reasonworking as today.This turns a silent success into an error for the truncated case, which is a visible behaviour change, so I wanted to check the direction before sending code: error versus a logged warning, and whether it should be retryable. If you want it, I can open a PR with the check and tests for a clean stream, a stream with
finish_reasonbut no[DONE], and a cut stream.(This comment was prepared with Claude Code.)
wahllllll commentedon Nov 10, 2026
Hi @PatrickUncle — I picked this one up. The fix is up as #4100, branch
fix/issue-3808-truncated-stream-failure.Your root-cause chain was accurate except in one place worth telling you: on the standard paths,
[DONE]never actually reachesOpenAIClient. BothJdkHttpTransportandOkHttpTransportalready terminate their flux on[DONE]themselves (readSseLinesdoes its owntakeWhile), so the client sees a stream that simply ends. That means the marker we can rely on in production isfinish_reason— and the fix keys on both, so it also covers custom transports that do pass the sentinel through.What it does: a stream that delivered chunks and then completed without
[DONE]and without anyfinish_reasonnow fails withcarrying an
EOFExceptioncause, soExecutionConfig.RETRYABLE_ERRORSsees it as an I/O truncation and the existing streaming retry re-issues the request instead of surfacing a permanent failure. Nothing else moves: same chunks, same order, and a stream that ends with zero chunks is left alone because that is a different failure mode.Verified red then green in
OpenAIStreamTerminationTest, including one case over the realJdkHttpTransportagainst a MockWebServer whose body just stops: onmainit completes silently (expected: onError(); actual: onComplete()), with the branch it errors.What would help most is your gateway. I have only reproduced this with MockWebServer closing a body — not with a real multi-tenant gateway cutting an upstream LLM. If you can run the branch:
and reproduce your original cut-off, I would like to know three things:
finish_reasonwill now error where it used to work. If you have one, say so and I will loosen the check rather than defend it.A flat "does not reproduce, here is what I see instead" is as useful to me as a confirmation — this is the part of the change I could not test on my own machine.