fix(bedrock-runtime): stop abandoned calls and omit error-body logs (#5526)

* fix(bedrock-runtime): cancel abandoned calls and omit error-body logs

Closes #5522. Tie upstream transport lifetime to the Bedrock caller, clean up interrupted streaming bodies, and retain HTTP-error status diagnostics without backend response content.

* fix(bedrock-runtime): bound stalled upstream error-body reads

Enforce a one-second diagnostic-read deadline with the existing disconnect monitor. Close short stalled error bodies and retain the known ModelErrorException. Regressions cover empty bodies and one or 50 short lines, caller latency, upstream closure, and payload-free warnings.

* fix(bedrock-runtime): share cancellation monitoring and split error-read deadline

Use one monitor accepting a cancellation condition and action for both Converse paths. Move error-read deadline implementation, regressions, and documentation to a separate follow-up at the maintainer request.
This commit is contained in:
david lee authored and GitHub committed 2026-10-12 18:14:46 -04:00
1 parent 8565ad837a
commit ce3d826fc7
5 files changed
+430 -24

No files matched your search

@@ -0,0 +1,181 @@
package io.github.hectorvent.floci.services.bedrockruntime;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(BedrockProxyCancellationIntegrationTest.Profile.class)
class BedrockProxyCancellationIntegrationTest {
private static final int PORT = 18939;
@TestHTTPResource
URI base;
@Test
void disconnectClosesUpstreamWithoutAnotherToken() throws Exception {
CountDownLatch closed = new CountDownLatch(1);
try (ServerSocket server = new ServerSocket(PORT)) {
server.setSoTimeout(10000);
Thread upstream = Thread.ofVirtual().start(() -> {
try (Socket socket = server.accept()) {
socket.setSoTimeout(10000);
InputStream input = socket.getInputStream();
StringBuilder header = new StringBuilder();
while (!header.toString().endsWith("\r\n\r\n")) {
int next = input.read();
if (next < 0 || header.length() > 65536) {
return;
}
header.append((char) next);
}
int bytes = 0;
for (String line : header.toString().split("\r\n")) {
if (line.toLowerCase().startsWith("content-length:")) {
bytes = Integer.parseInt(line.substring(line.indexOf(':') + 1).trim());
}
}
assertEquals(bytes, input.readNBytes(bytes).length);
OutputStream output = socket.getOutputStream();
output.write("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n".getBytes(StandardCharsets.US_ASCII));
byte[] chunk = "data: {\"choices\":[{\"delta\":{\"content\":\"hello\"}}]}\n\n".getBytes(StandardCharsets.UTF_8);
output.write((Integer.toHexString(chunk.length) + "\r\n").getBytes(StandardCharsets.US_ASCII));
output.write(chunk);
output.write("\r\n".getBytes(StandardCharsets.US_ASCII));
output.flush();
// No more output: disconnect must close the transport independently of token delivery.
try {
if (input.read() == -1) {
closed.countDown();
}
} catch (SocketException disconnected) {
closed.countDown();
}
} catch (Exception expected) {
// The latch remains unset so a backend setup failure cannot pass the assertion.
}
});
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder(base.resolve("/model/fixture/converse-stream"))
.timeout(Duration.ofSeconds(10)).header("Content-Type", "application/json")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/bedrock/aws4_request")
.POST(HttpRequest.BodyPublishers.ofString("{\"messages\":[{\"role\":\"user\",\"content\":[{\"text\":\"synthetic\"}]}]}"))
.build();
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
assertEquals(200, response.statusCode());
try (InputStream body = response.body()) {
assertTrue(body.read() >= 0);
}
assertTrue(closed.await(5, TimeUnit.SECONDS), "Client disconnect must close the stalled upstream");
} finally {
upstream.interrupt();
upstream.join(1000);
}
}
}
@Test
void nonStreamingDisconnectBeforeHeadersClosesUpstream() throws Exception {
disconnectWhileUpstreamStalls("converse", false);
}
@Test
void streamingDisconnectBeforeHeadersClosesUpstream() throws Exception {
disconnectWhileUpstreamStalls("converse-stream", false);
}
@Test
void nonStreamingDisconnectDuringBodyClosesUpstream() throws Exception {
disconnectWhileUpstreamStalls("converse", true);
}
private void disconnectWhileUpstreamStalls(String route, boolean partialResponse) throws Exception {
CountDownLatch accepted = new CountDownLatch(1);
CountDownLatch closed = new CountDownLatch(1);
try (ServerSocket server = new ServerSocket(PORT)) {
server.setSoTimeout(10000);
Thread upstream = Thread.ofVirtual().start(() -> {
try (Socket socket = server.accept()) {
socket.setSoTimeout(10000);
InputStream input = socket.getInputStream();
StringBuilder header = new StringBuilder();
while (!header.toString().endsWith("\r\n\r\n")) {
int next = input.read();
if (next < 0 || header.length() > 65536) {
return;
}
header.append((char) next);
}
int bytes = 0;
for (String line : header.toString().split("\r\n")) {
if (line.toLowerCase().startsWith("content-length:")) {
bytes = Integer.parseInt(line.substring(line.indexOf(':') + 1).trim());
}
}
if (input.readNBytes(bytes).length != bytes) {
return;
}
if (partialResponse) {
socket.getOutputStream().write(("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
+ "Content-Length: 1000\r\n\r\n{").getBytes(StandardCharsets.US_ASCII));
socket.getOutputStream().flush();
}
accepted.countDown();
// The upstream stalls before completing its response, so cancellation must close it.
try {
if (input.read() == -1) {
closed.countDown();
}
} catch (SocketException disconnected) {
closed.countDown();
}
} catch (Exception expected) {
// An unset latch exposes setup and transport failures to the test thread.
}
});
try (Socket frontend = new Socket(base.getHost(), base.getPort())) {
String body = "{\"messages\":[{\"role\":\"user\",\"content\":[{\"text\":\"synthetic\"}]}]}";
String request = "POST /model/fixture/" + route + " HTTP/1.1\r\nHost: localhost\r\n"
+ "Content-Type: application/json\r\n"
+ "Authorization: AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/bedrock/aws4_request\r\n"
+ "Content-Length: " + body.getBytes(StandardCharsets.UTF_8).length + "\r\n\r\n" + body;
frontend.getOutputStream().write(request.getBytes(StandardCharsets.UTF_8));
frontend.getOutputStream().flush();
assertTrue(accepted.await(5, TimeUnit.SECONDS), "Upstream must receive the request before disconnect");
frontend.close();
assertTrue(closed.await(5, TimeUnit.SECONDS), "Disconnect must close the stalled upstream request");
} finally {
upstream.interrupt();
upstream.join(1000);
}
}
}
public static final class Profile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.bedrock-runtime.backend", "proxy",
"floci.services.bedrock-runtime.proxy.url", "http://127.0.0.1:" + PORT + "/v1",
"floci.services.bedrock-runtime.proxy.passthrough", "true");
}
}
}
@@ -0,0 +1,116 @@
package io.github.hectorvent.floci.services.bedrockruntime;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.services.bedrockruntime.backend.ProxyBackend;
import io.github.hectorvent.floci.testutil.LogCapture;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(BedrockProxyCancellationIntegrationTest.Profile.class)
class BedrockProxyLoggingIntegrationTest {
@TestHTTPResource
URI base;
@ParameterizedTest
@ValueSource(strings = {"converse", "converse-stream"})
void upstreamErrorIsLoggedWithoutResponseBody(String operation) throws IOException {
String marker = "synthetic-private-upstream-content";
HttpServer backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 18939), 0);
backend.createContext("/v1/chat/completions", exchange -> {
exchange.getRequestBody().readAllBytes();
byte[] body = ("{\"error\":\"" + marker + "\"}").getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(503, body.length);
try (exchange) {
exchange.getResponseBody().write(body);
}
});
backend.start();
try {
List<LogRecord> records = LogCapture.capture(ProxyBackend.class, () ->
given()
.contentType("application/json")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/bedrock/aws4_request")
.body("{\"messages\":[{\"role\":\"user\",\"content\":[{\"text\":\"synthetic\"}]}]}")
.when()
.post("/model/fixture/" + operation)
.then()
.statusCode(424)
.body("__type", equalTo("ModelErrorException"))
.body("message", containsString("HTTP 503"))
.body("message", containsString(marker)));
SimpleFormatter formatter = new SimpleFormatter();
assertTrue(records.stream().anyMatch(record -> record.getLevel().equals(Level.WARNING)
&& formatter.format(record).contains("HTTP 503")), "The upstream status must remain diagnosable");
assertFalse(records.stream().anyMatch(record -> formatter.format(record).contains(marker)),
"Operational logs must not include upstream response bodies");
} finally {
backend.stop(0);
}
}
@Test
void streamingErrorBodyReadIsBoundedWithoutWaitingForEof() throws Exception {
CountDownLatch release = new CountDownLatch(1);
HttpServer backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 18939), 0);
backend.createContext("/v1/chat/completions", exchange -> {
exchange.getRequestBody().readAllBytes();
exchange.sendResponseHeaders(503, 32768);
try (exchange) {
exchange.getResponseBody().write("x".repeat(8192).getBytes(StandardCharsets.UTF_8));
exchange.getResponseBody().flush();
try {
release.await(10, TimeUnit.SECONDS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
}
}
});
backend.start();
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder(base.resolve("/model/fixture/converse-stream"))
.timeout(Duration.ofSeconds(5))
.header("Content-Type", "application/json")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/bedrock/aws4_request")
.POST(HttpRequest.BodyPublishers.ofString(
"{\"messages\":[{\"role\":\"user\",\"content\":[{\"text\":\"synthetic\"}]}]}"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(424, response.statusCode());
assertTrue(response.body().contains("ModelErrorException"));
assertTrue(response.body().contains("HTTP 503"));
assertTrue(response.body().length() < 1024, "Caller error descriptions must remain bounded");
} finally {
release.countDown();
backend.stop(0);
}
}
}
@@ -6,7 +6,8 @@ import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.IOException;
import java.net.InetSocketAddress;
@@ -57,8 +58,9 @@ class BedrockProxyTimeoutIntegrationTest {
backend.stop(0);
}
@Test
void converse_backendTimesOut_returnsModelTimeoutException() {
@ParameterizedTest
@ValueSource(strings = {"converse", "converse-stream"})
void backendTimesOut_returnsModelTimeoutException(String operation) {
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
@@ -66,7 +68,7 @@ class BedrockProxyTimeoutIntegrationTest {
{"messages": [{"role": "user", "content": [{"text": "hi"}]}]}
""")
.when()
.post("/model/" + MAPPED_MODEL_ID + "/converse")
.post("/model/" + MAPPED_MODEL_ID + "/" + operation)
.then()
.statusCode(408)
.body("__type", equalTo("ModelTimeoutException"));