From ef85d856d2ace8c867a21d7572ac2d993f0d9036 Mon Sep 17 00:00:00 2001 From: wahl <592211009@qq.com> Date: Tue, 10 Nov 2026 20:34:36 +0800 Subject: [PATCH] fix(openai): fail a streamed response that never proves it finished A gateway or provider that closes the connection mid-generation produces onComplete on the SSE body, not onError: a server-side FIN is a normal completion to the HTTP client. Nothing downstream could tell the prefix apart from a full answer, so truncated text was persisted and shown as final. Track the two markers that prove a response completed -- the `[DONE]` sentinel or a chunk carrying `finish_reason` -- and fail the flux when a stream that did deliver chunks ends with neither. The error carries an EOFException cause so the existing retry classification treats it as an I/O truncation and retries it instead of surfacing a permanent failure. The built-in transports terminate on `[DONE]` themselves, so in practice `finish_reason` is the signal; the `[DONE]` check covers custom transports that pass the marker through. --- .../extensions/model/openai/OpenAIClient.java | 82 +++++++++- .../OpenAIChatModelStreamingRetryTest.java | 14 +- .../openai/OpenAIStreamTerminationTest.java | 141 ++++++++++++++++-- 3 files changed, 223 insertions(+), 14 deletions(-) diff --git a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/main/java/io/agentscope/extensions/model/openai/OpenAIClient.java b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/main/java/io/agentscope/extensions/model/openai/OpenAIClient.java index ddf548f739..b102e09fb8 100644 --- a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/main/java/io/agentscope/extensions/model/openai/OpenAIClient.java +++ b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/main/java/io/agentscope/extensions/model/openai/OpenAIClient.java @@ -28,10 +28,12 @@ import io.agentscope.extensions.model.openai.dto.OpenAIRequest; import io.agentscope.extensions.model.openai.dto.OpenAIResponse; import io.agentscope.extensions.model.openai.exception.OpenAIException; +import java.io.EOFException; import java.net.URI; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; @@ -403,12 +405,24 @@ public Flux stream( .build(); AtomicBoolean seenChunk = new AtomicBoolean(false); + // A stream that ends without either marker below did not finish: the provider, the + // gateway or a proxy closed the connection mid-generation and the transport reports + // that as a normal completion (a server-side FIN is not an error to the HTTP client). + AtomicBoolean sawDoneMarker = new AtomicBoolean(false); + AtomicBoolean sawFinishReason = new AtomicBoolean(false); return transport.stream(httpRequest) // The SSE `[DONE]` sentinel terminates the stream: complete the Flux here // rather than merely filtering it out, otherwise completion is deferred until // the underlying connection closes (keep-alive gateways may stall this for the // full idle timeout even though the model has finished responding). - .takeWhile(data -> !SSE_DONE_MARKER.equals(data)) + .takeWhile( + data -> { + if (SSE_DONE_MARKER.equals(data)) { + sawDoneMarker.set(true); + return false; + } + return true; + }) .handle( (data, sink) -> { OpenAIResponse response = parseStreamData(data); @@ -440,10 +454,18 @@ public Flux stream( summaryChoice.setMessage(null); } } + markFinishReason(response, sawFinishReason); sink.next(response); } // If response is null (malformed chunk), skip it silently }) + // Completion without [DONE] and without any finish_reason means the answer was + // cut short; surface it instead of returning the partial text as a final one. + .concatWith( + Flux.defer( + () -> + failIfTruncated( + seenChunk, sawDoneMarker, sawFinishReason))) .onErrorMap( ex -> { if (ex instanceof HttpTransportException hte) { @@ -465,6 +487,64 @@ public Flux stream( } } + /** + * Remember whether a streamed chunk reported a {@code finish_reason}. + * + *

A well-formed stream carries one on its last chunk before the {@code [DONE]} sentinel, so + * observing either proves the provider finished the response rather than being cut off. + * + * @param response the parsed response, which may carry several choices + * @param sawFinishReason set once any choice reports a {@code finish_reason} + */ + private static void markFinishReason(OpenAIResponse response, AtomicBoolean sawFinishReason) { + if (sawFinishReason.get()) { + return; + } + List choices = response.getChoices(); + if (choices == null) { + return; + } + for (OpenAIChoice choice : choices) { + if (choice != null && choice.getFinishReason() != null) { + sawFinishReason.set(true); + return; + } + } + } + + /** + * Fail the stream when it ended before the response was complete. + * + *

An interrupted generation is indistinguishable from a finished one once the underlying + * connection is gone, so the only evidence left is the terminating marker: either the SSE + * {@code [DONE]} sentinel or a chunk carrying {@code finish_reason}. Without both, the text + * delivered so far is a prefix of the answer and must not be persisted or shown as a full one. + * + *

The built-in transports already terminate their fluxes on {@code [DONE]} and never hand the + * marker to this method, so in practice {@code finish_reason} is the signal that matters; the + * {@code [DONE]} check covers custom {@link HttpTransport} implementations that pass it through. + * + *

The error carries an {@link EOFException} cause so it is classified as retryable: a body + * that stopped mid-stream is an I/O-level truncation, not a request the server rejected. + * + * @param seenChunk whether any streamed chunk was delivered at all + * @param sawDoneMarker whether the {@code [DONE]} sentinel was received + * @param sawFinishReason whether any chunk reported a {@code finish_reason} + * @return an empty flux when the response completed, an error flux when it did not + */ + private static Flux failIfTruncated( + AtomicBoolean seenChunk, AtomicBoolean sawDoneMarker, AtomicBoolean sawFinishReason) { + if (sawDoneMarker.get() || sawFinishReason.get() || !seenChunk.get()) { + return Flux.empty(); + } + return Flux.error( + new OpenAIException( + "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", + new EOFException("SSE stream ended without [DONE]"))); + } + /** * Resolve the actual HTTP error status code when the API returns 200 OK * but contains an error payload. diff --git a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIChatModelStreamingRetryTest.java b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIChatModelStreamingRetryTest.java index 6a9ef7a49c..33e0d51296 100644 --- a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIChatModelStreamingRetryTest.java +++ b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIChatModelStreamingRetryTest.java @@ -279,7 +279,7 @@ private static MockResponse successStreamResponse(String content) { return new MockResponse() .setResponseCode(200) .setHeader("Content-Type", "text/event-stream") - .setBody(sseChunk(content) + sseDone()); + .setBody(sseChunk(content) + sseFinish("stop") + sseDone()); } private static String sseChunk(String content) { @@ -288,6 +288,18 @@ private static String sseChunk(String content) { + "\"},\"finish_reason\":null}]}\n\n"; } + /** + * The terminating chunk of a real OpenAI stream: it carries the {@code finish_reason} that + * proves the response completed. Without it a stream that simply stops is indistinguishable + * from one the gateway cut off, which {@code OpenAIClient} now reports as a failure. + */ + private static String sseFinish(String finishReason) { + return "data: {\"object\":\"chat.completion.chunk\",\"choices\":[{\"delta\":{}," + + "\"finish_reason\":\"" + + finishReason + + "\"}]}\n\n"; + } + private static String sseDone() { return "data: [DONE]\n\n"; } diff --git a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java index bb437f76f0..61c4d41331 100644 --- a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java +++ b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIStreamTerminationTest.java @@ -15,14 +15,24 @@ */ package io.agentscope.extensions.model.openai; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.agentscope.core.model.ExecutionConfig; import io.agentscope.core.model.GenerateOptions; import io.agentscope.core.model.transport.HttpRequest; import io.agentscope.core.model.transport.HttpResponse; import io.agentscope.core.model.transport.HttpTransport; +import io.agentscope.core.model.transport.HttpTransportFactory; import io.agentscope.extensions.model.openai.dto.OpenAIMessage; import io.agentscope.extensions.model.openai.dto.OpenAIRequest; +import io.agentscope.extensions.model.openai.dto.OpenAIResponse; +import io.agentscope.extensions.model.openai.exception.OpenAIException; +import java.io.IOException; import java.time.Duration; import java.util.List; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -30,13 +40,18 @@ import reactor.test.StepVerifier; /** - * Tests that the OpenAI streaming response is terminated deterministically by the SSE - * {@code [DONE]} sentinel, independent of the underlying HTTP connection lifecycle. + * Tests that the OpenAI streaming response is terminated deterministically by the SSE {@code + * [DONE]} sentinel, and that a stream that ends without ever proving it finished fails instead of + * being accepted as a complete answer. + * + *

The first case is the regression test for {@code [DONE]} being merely filtered out instead of + * completing the {@link Flux}: against an OpenAI-compatible gateway that keeps the connection open + * (HTTP keep-alive) after emitting {@code [DONE]}, the stream would only complete when the socket + * was eventually closed by an idle timeout, stalling the ReAct turn for up to a minute. * - *

Regression test for the case where {@code [DONE]} was merely filtered out instead of - * completing the {@link Flux}. Against an OpenAI-compatible gateway that keeps the connection - * open (HTTP keep-alive) after emitting {@code [DONE]}, the stream would only complete when the - * socket was eventually closed by an idle timeout, stalling the ReAct turn for up to a minute. + *

The other cases are the regression test for a connection closed mid-generation: that produces + * {@code onComplete}, not {@code onError}, so the truncated text used to be persisted and shown as + * if the model had finished normally. */ @Tag("unit") @DisplayName("OpenAI Stream Termination Tests") @@ -44,6 +59,8 @@ class OpenAIStreamTerminationTest { private static final String CHUNK_CONTENT = "{\"id\":\"1\",\"choices\":[{\"delta\":{\"content\":\"hello\"},\"index\":0}]}"; + private static final String CHUNK_CONTENT_MORE = + "{\"id\":\"1\",\"choices\":[{\"delta\":{\"content\":\" world\"},\"index\":0}]}"; private static final String CHUNK_FINISH = "{\"id\":\"1\",\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\",\"index\":0}]}"; @@ -69,6 +86,27 @@ public void close() {} }; } + /** + * A transport that emits the given SSE lines and then completes cleanly — simulating a + * connection closed by the provider or by a gateway in front of it. + */ + private static HttpTransport transportEmitting(List sseLines) { + return new HttpTransport() { + @Override + public HttpResponse execute(HttpRequest request) { + throw new UnsupportedOperationException("not used in this test"); + } + + @Override + public Flux stream(HttpRequest request) { + return Flux.fromIterable(sseLines); + } + + @Override + public void close() {} + }; + } + private static OpenAIRequest sampleRequest() { return OpenAIRequest.builder() .model("gpt-4o-mini") @@ -76,19 +114,98 @@ private static OpenAIRequest sampleRequest() { .build(); } + private static Flux streamFrom(OpenAIClient client) { + return client.stream( + "test-key", "http://localhost", sampleRequest(), GenerateOptions.builder().build()); + } + @Test @DisplayName("Stream should complete on [DONE] even if the connection stays open") void streamCompletesOnDoneSentinelWithoutWaitingForConnectionClose() { OpenAIClient client = new OpenAIClient(keepAliveTransportAfterDone()); - StepVerifier.create( - client.stream( - "test-key", - "http://localhost", - sampleRequest(), - GenerateOptions.builder().build())) + StepVerifier.create(streamFrom(client)) .expectNextCount(2) .expectComplete() .verify(Duration.ofSeconds(5)); } + + @Test + @DisplayName("Stream should fail when it ends without [DONE] and without a finish_reason") + void streamFailsWhenConnectionClosesBeforeTheResponseCompletes() { + OpenAIClient client = + new OpenAIClient(transportEmitting(List.of(CHUNK_CONTENT, CHUNK_CONTENT_MORE))); + + StepVerifier.create(streamFrom(client)) + .expectNextCount(2) + .expectErrorSatisfies( + error -> { + OpenAIException typed = assertInstanceOf(OpenAIException.class, error); + assertTrue( + typed.getMessage().contains("ended before completion"), + "unexpected message: " + typed.getMessage()); + assertTrue( + ExecutionConfig.RETRYABLE_ERRORS.test(typed), + "a truncated stream must be retryable, otherwise the retry" + + " machinery never sees it"); + }) + .verify(Duration.ofSeconds(5)); + } + + @Test + @DisplayName("Stream should complete when finish_reason arrives without [DONE]") + void streamCompletesWhenFinishReasonArrivesWithoutDoneSentinel() { + OpenAIClient client = + new OpenAIClient(transportEmitting(List.of(CHUNK_CONTENT, CHUNK_FINISH))); + + StepVerifier.create(streamFrom(client)) + .expectNextCount(2) + .expectComplete() + .verify(Duration.ofSeconds(5)); + } + + @Test + @DisplayName("Stream should still complete on [DONE] when no chunk carries a finish_reason") + void streamCompletesOnDoneSentinelWithoutFinishReason() { + OpenAIClient client = new OpenAIClient(transportEmitting(List.of(CHUNK_CONTENT, "[DONE]"))); + + StepVerifier.create(streamFrom(client)) + .expectNextCount(1) + .expectComplete() + .verify(Duration.ofSeconds(5)); + } + + @Test + @DisplayName("Stream over the JDK transport should fail when the server closes mid-stream") + void streamOverRealTransportFailsWhenTheServerClosesMidStream() throws IOException { + MockWebServer server = new MockWebServer(); + server.start(); + try { + // The body simply stops: no terminating chunk, no [DONE], and the connection is + // closed cleanly, which is what a gateway cutting the response short looks like. + server.enqueue( + new MockResponse() + .setResponseCode(200) + .setHeader("Content-Type", "text/event-stream") + .setBody(sseLine(CHUNK_CONTENT) + sseLine(CHUNK_CONTENT_MORE))); + + OpenAIClient client = new OpenAIClient(HttpTransportFactory.getDefault()); + + StepVerifier.create( + client.stream( + "test-key", + server.url("/v1").toString(), + sampleRequest(), + GenerateOptions.builder().build())) + .expectNextCount(2) + .expectErrorSatisfies(error -> assertInstanceOf(OpenAIException.class, error)) + .verify(Duration.ofSeconds(10)); + } finally { + server.shutdown(); + } + } + + private static String sseLine(String payload) { + return "data: " + payload + "\n\n"; + } }