Skip to content
Open
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,10 @@ private Flux<String> processStreamResponse(InputStream inputStream, HttpRequest
boolean isNdjson =
TransportConstants.STREAM_FORMAT_NDJSON.equals(
request.getHeaders().get(TransportConstants.STREAM_FORMAT_HEADER));
String terminator =
isNdjson
? null
: request.getHeaders().get(TransportConstants.STREAM_TERMINATOR_HEADER);

// The body is closed by the terminal signal's doFinally, never the reader: BufferedReader
// close() contends for the monitor held by a parked readLine(), which is the hang
Expand All @@ -344,22 +348,49 @@ private Flux<String> processStreamResponse(InputStream inputStream, HttpRequest
new BufferedReader(
new InputStreamReader(
inputStream, StandardCharsets.UTF_8));
return isNdjson ? readNdJsonLines(reader) : readSseLines(reader);
return isNdjson
? readNdJsonLines(reader)
: readSseLines(reader, terminator);
})
// reader.lines() uses blocking I/O internally
.subscribeOn(streamScheduler);
}

/**
* Extract non-empty SSE data payloads and stop before the terminal marker.
*
* <p>When {@code terminator} is non-null (caller's {@code STREAM_TERMINATOR_HEADER}), a body
* that ends without the marker fails with {@link StreamTerminationException}: a clean
* connection close is not proof of complete content.
*/
private Flux<String> readSseLines(BufferedReader reader) {
return Flux.fromStream(reader.lines())
.filter(line -> line.startsWith(SSE_DATA_PREFIX))
.map(line -> line.substring(SSE_DATA_PREFIX.length()).trim())
.takeWhile(data -> !SSE_DONE_MARKER.equals(data))
.doOnNext(data -> log.debug("Received SSE data chunk"))
.filter(data -> !data.isEmpty());
private Flux<String> readSseLines(BufferedReader reader, String terminator) {
String marker = terminator != null ? terminator : SSE_DONE_MARKER;
AtomicBoolean sawMarker = new AtomicBoolean(false);
Flux<String> lines =
Flux.fromStream(reader.lines())
.filter(line -> line.startsWith(SSE_DATA_PREFIX))
.map(line -> line.substring(SSE_DATA_PREFIX.length()).trim())
.doOnNext(
data -> {
if (marker.equals(data)) {
sawMarker.set(true);
}
})
.takeWhile(data -> !marker.equals(data))
.doOnNext(data -> log.debug("Received SSE data chunk"))
.filter(data -> !data.isEmpty());
if (terminator == null) {
return lines;
}
// Runs only on natural completion, never on cancellation or error: the marker check must
// not fire when the caller cancelled mid-stream.
return lines.concatWith(
Flux.defer(
() ->
sawMarker.get()
? Flux.<String>empty()
: Flux.<String>error(
new StreamTerminationException(terminator))));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
Expand Down Expand Up @@ -237,6 +238,10 @@ public Flux<String> stream(HttpRequest request) {
boolean isNdjson =
TransportConstants.STREAM_FORMAT_NDJSON.equals(
request.getHeaders().get(TransportConstants.STREAM_FORMAT_HEADER));
String terminator =
isNdjson
? null
: request.getHeaders().get(TransportConstants.STREAM_TERMINATOR_HEADER);
return Flux.defer(
() -> {
Call call = client.newCall(okHttpRequest);
Expand Down Expand Up @@ -265,21 +270,47 @@ public Flux<String> stream(HttpRequest request) {
Flux.fromStream(reader.lines());
if (isNdjson)
return lines.filter(line -> !line.isEmpty());
return lines.filter(
line ->
line.startsWith(
SSE_DATA_PREFIX))
.map(
line ->
line.substring(
SSE_DATA_PREFIX
.length())
.trim())
.takeWhile(
data ->
!SSE_DONE_MARKER.equals(
data))
.filter(data -> !data.isEmpty());
String marker =
terminator != null
? terminator
: SSE_DONE_MARKER;
AtomicBoolean sawMarker = new AtomicBoolean(false);
lines =
lines.filter(
line ->
line.startsWith(
SSE_DATA_PREFIX))
.map(
line ->
line.substring(
SSE_DATA_PREFIX
.length())
.trim())
.doOnNext(
data -> {
if (marker.equals(
data)) {
sawMarker.set(true);
}
})
.takeWhile(
data ->
!marker.equals(
data))
.filter(data -> !data.isEmpty());
if (terminator == null) return lines;
return lines.concatWith(
Flux.defer(
() ->
sawMarker.get()
? Flux
.<String>
empty()
: Flux
.<String>
error(
new StreamTerminationException(
terminator))));
},
this::closeQuietly)
.doOnCancel(call::cancel);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 2024-2026 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.agentscope.core.model.transport;

/**
* The stream body ended before the terminator declared via {@link
* TransportConstants#STREAM_TERMINATOR_HEADER} was seen.
*
* <p>A clean connection close is not proof of complete content: providers and gateways can cut a
* stream mid-generation without emitting the terminal marker. Delivering the partial payload as a
* normal completion would silently truncate model responses, so transports raise this error
* instead when the caller opted into terminator enforcement.
*/
public class StreamTerminationException extends HttpTransportException {

private final String terminator;

public StreamTerminationException(String terminator) {
super("SSE stream ended before the expected terminal marker: " + terminator);
this.terminator = terminator;
}

public String getTerminator() {
return terminator;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ public class TransportConstants {
*/
public static final String STREAM_FORMAT_NDJSON = "ndjson";

/**
* Header name declaring the expected SSE stream terminator (e.g. {@code [DONE]}).
*
* <p>When set, transports must fail the stream with {@link StreamTerminationException} if the
* body ends before the terminator is seen, instead of silently completing with a possibly
* truncated payload. When absent, transports keep their lenient default behavior.
*/
public static final String STREAM_TERMINATOR_HEADER = "X-AgentScope-Stream-Terminator";

private TransportConstants() {
// Prevent instantiation
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,83 @@ void testStreamHandlesEmptyLines() {
.verifyComplete();
}

@Test
void testStreamWithoutTerminatorHeaderStaysLenient() {
// No STREAM_TERMINATOR_HEADER: a body that ends without [DONE] still completes normally
// (backwards-compatible behavior for providers without a terminal marker).
String sseResponse = "data: {\"id\":\"1\"}\n\n";

mockServer.enqueue(
new MockResponse()
.setResponseCode(200)
.setBody(sseResponse)
.setHeader("Content-Type", "text/event-stream"));

HttpRequest request =
HttpRequest.builder()
.url(mockServer.url("/stream").toString())
.method("POST")
.body("{}")
.build();

StepVerifier.create(transport.stream(request))
.expectNextMatches(data -> data.contains("\"id\":\"1\""))
.verifyComplete();
}

@Test
void testStreamWithTerminatorHeaderErrorsWhenMarkerMissing() {
String sseResponse = "data: {\"id\":\"1\"}\n\n";

mockServer.enqueue(
new MockResponse()
.setResponseCode(200)
.setBody(sseResponse)
.setHeader("Content-Type", "text/event-stream"));

HttpRequest request =
HttpRequest.builder()
.url(mockServer.url("/stream").toString())
.method("POST")
.header(TransportConstants.STREAM_TERMINATOR_HEADER, "[DONE]")
.body("{}")
.build();

StepVerifier.create(transport.stream(request))
.expectNextMatches(data -> data.contains("\"id\":\"1\""))
.expectErrorMatches(
e ->
e instanceof StreamTerminationException
&& "[DONE]"
.equals(
((StreamTerminationException) e)
.getTerminator()))
.verify();
}

@Test
void testStreamWithTerminatorHeaderCompletesWhenMarkerSeen() {
String sseResponse = "data: {\"id\":\"1\"}\n\ndata: [DONE]\n\n";

mockServer.enqueue(
new MockResponse()
.setResponseCode(200)
.setBody(sseResponse)
.setHeader("Content-Type", "text/event-stream"));

HttpRequest request =
HttpRequest.builder()
.url(mockServer.url("/stream").toString())
.method("POST")
.header(TransportConstants.STREAM_TERMINATOR_HEADER, "[DONE]")
.body("{}")
.build();

StepVerifier.create(transport.stream(request))
.expectNextMatches(data -> data.contains("\"id\":\"1\""))
.verifyComplete();
}

@Test
void testStreamErrorResponse() {
mockServer.enqueue(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,83 @@ void testStreamSseEvents() {
assertTrue(events.get(1).contains("\"id\":\"2\""));
}

@Test
void testStreamWithoutTerminatorHeaderStaysLenient() {
// No STREAM_TERMINATOR_HEADER: a body that ends without [DONE] still completes normally
// (backwards-compatible behavior for providers without a terminal marker).
String sseResponse = "data: {\"id\":\"1\"}\n\n";

mockServer.enqueue(
new MockResponse()
.setResponseCode(200)
.setBody(sseResponse)
.setHeader("Content-Type", "text/event-stream"));

HttpRequest request =
HttpRequest.builder()
.url(mockServer.url("/stream").toString())
.method("POST")
.body("{}")
.build();

StepVerifier.create(transport.stream(request))
.expectNextMatches(data -> data.contains("\"id\":\"1\""))
.verifyComplete();
}

@Test
void testStreamWithTerminatorHeaderErrorsWhenMarkerMissing() {
String sseResponse = "data: {\"id\":\"1\"}\n\n";

mockServer.enqueue(
new MockResponse()
.setResponseCode(200)
.setBody(sseResponse)
.setHeader("Content-Type", "text/event-stream"));

HttpRequest request =
HttpRequest.builder()
.url(mockServer.url("/stream").toString())
.method("POST")
.header(TransportConstants.STREAM_TERMINATOR_HEADER, "[DONE]")
.body("{}")
.build();

StepVerifier.create(transport.stream(request))
.expectNextMatches(data -> data.contains("\"id\":\"1\""))
.expectErrorMatches(
e ->
e instanceof StreamTerminationException
&& "[DONE]"
.equals(
((StreamTerminationException) e)
.getTerminator()))
.verify();
}

@Test
void testStreamWithTerminatorHeaderCompletesWhenMarkerSeen() {
String sseResponse = "data: {\"id\":\"1\"}\n\ndata: [DONE]\n\n";

mockServer.enqueue(
new MockResponse()
.setResponseCode(200)
.setBody(sseResponse)
.setHeader("Content-Type", "text/event-stream"));

HttpRequest request =
HttpRequest.builder()
.url(mockServer.url("/stream").toString())
.method("POST")
.header(TransportConstants.STREAM_TERMINATOR_HEADER, "[DONE]")
.body("{}")
.build();

StepVerifier.create(transport.stream(request))
.expectNextMatches(data -> data.contains("\"id\":\"1\""))
.verifyComplete();
}

@Test
void testStreamEmitsBufferedEventsWhenDownstreamRequestsIncrementally() throws Exception {
Pipe responsePipe = new Pipe(1024);
Expand Down
Loading
Loading