Skip to content

[Bug]: Streaming response terminated without [DONE]/finish_reason is silently accepted as a complete answer #3808

Open

Description

@pengzuyu

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 error

A 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)

Suggested direction (we run this in production)

We fixed this in production and are happy to upstream it. Sketch:

  1. Detect. OpenAIClient tracks whether either completion signal was seen
    ([DONE] sentinel or any chunk carrying finish_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))))
  1. Keep generic retry away from it. ModelUtils's default retryOn excludes
    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).

  2. Retry safely at the reasoning layer. ReActAgent retries such a model call
    once after ReasoningContext.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
    fresh replyId; ModelCallStartEvent carries an attempt number and
    ModelCallEndEvent exposes the provider finishReason, so downstream consumers can
    drop the aborted attempt's partial content instead of duplicating it.

  3. Observability. Surfacing finishReason on ModelCallEndEvent also 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

  1. pcbeingused333 commented on Oct 28, 2026

    @pcbeingused333
    Contributor

    The cause matches what the report found: in OpenAIClient.stream the takeWhile on the [DONE] sentinel only ends the Flux early, and nothing after it records whether [DONE] or a chunk with a non-null finish_reason was ever seen, so a connection closed mid-stream completes the Flux like a normal answer.

    A possible shape: keep two AtomicBooleans next to seenChunk (one set when [DONE] is matched, one when a choice carries a finish_reason), and concatWith(Flux.defer(...)) a final step that errors when neither was set after at least one chunk arrived. The error would be a retryable one, so ModelUtils.applyTimeoutAndRetry can 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 send finish_reason working 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_reason but no [DONE], and a cut stream.

    (This comment was prepared with Claude Code.)

  2. wahllllll commented on Nov 10, 2026

    @wahllllll
    Contributor

    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 reaches OpenAIClient. Both JdkHttpTransport and OkHttpTransport already terminate their flux on [DONE] themselves (readSseLines does its own takeWhile), so the client sees a stream that simply ends. That means the marker we can rely on in production is finish_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 any finish_reason now fails with

    Streaming response ended before completion: the stream closed without the [DONE]
    sentinel and no chunk reported a finish_reason, so the partial response is truncated
    

    carrying an EOFException cause, so ExecutionConfig.RETRYABLE_ERRORS sees 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 real JdkHttpTransport against a MockWebServer whose body just stops: on main it 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:

    git fetch wahl fix/issue-3808-truncated-stream-failure
    git checkout wahl/fix/issue-3808-truncated-stream-failure

    and reproduce your original cut-off, I would like to know three things:

    1. you now get the error, and with retry configured a retried request rather than a silent truncation;
    2. the truncated text no longer lands in the conversation as a complete assistant turn;
    3. whether anything legitimate starts failing. This is the risk I worry about most: the check fails closed, so an OpenAI-compatible backend in your fleet that streams fine but never sends finish_reason will 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions