mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(bedrock-runtime): return errors when upstream error bodies stall (#5527)
* fix(bedrock-runtime): cancel abandoned calls and bound stalled error bodies Close the upstream request when the caller disconnects, including a stream stalled between tokens, and read streaming error bodies under a one-second deadline so a backend that stalls mid-error still returns ModelErrorException. Warnings keep the upstream status but omit the response body. * fix(bedrock-runtime): bound stalled error bodies on non-streaming converse Non-streaming Converse read the upstream body with ofString, so an error status followed by a stalled body hung until the caller gave up: the request timeout stops at the headers. Both Converse paths now share one send step that reads error bodies under the collection deadline. The deadline is configurable (error-body-timeout-millis, default 1000) so the tests run against a short one, and the raw-socket upstream fixture is shared between the cancellation and logging tests. * fix(bedrock-runtime): declare the error-body timeout in application.yml * fix(bedrock-runtime): schedule the error-body cut instead of polling for it The cancellation poll checked the deadline every 100 ms, so a stalled error body was cut 100 to 200 ms after it started. A timer armed when the error status arrives cuts it exactly, and the poll goes back to watching only for a caller disconnect. The test deadline drops to 10 ms. * fix(bedrock-runtime): validate the error-body timeout and tighten its tests Refuse a non-positive error-body-timeout-millis at startup, list the setting in the configuration table, and restore the non-streaming "Proxy request interrupted." wording. The complete-error-body tests now send headers and body in one write through StallingUpstream, so the 10 ms test deadline cannot race them, and the 8 KiB test asserts that the read ended at the cap rather than at the deadline. A shared ConverseRequests helper replaces the three hand-built Converse requests.
This commit is contained in:
1 parent
1f4a46804c
commit
4204ee2ea5
11 files changed
+340
-239
No files matched your search
@@ -0,0 +1,28 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
@ApplicationScoped
|
||||
public class BedrockRuntimeStartupValidator {
|
||||
|
||||
private final EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
public BedrockRuntimeStartupValidator(EmulatorConfig config) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
void onStart(@Observes StartupEvent ignored) {
|
||||
validateErrorBodyTimeoutMillis(config.services().bedrockRuntime().proxy().errorBodyTimeoutMillis());
|
||||
}
|
||||
|
||||
public static void validateErrorBodyTimeoutMillis(int value) {
|
||||
if (value <= 0) {
|
||||
throw new IllegalArgumentException(
|
||||
"floci.services.bedrock-runtime.proxy.error-body-timeout-millis must be positive");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2375,6 +2375,14 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
@WithDefault("60")
|
||||
int requestTimeoutSeconds();
|
||||
|
||||
/**
|
||||
* How long to collect an upstream error response body before returning the
|
||||
* known model error without its details. Bounds a backend that sends an error
|
||||
* status and then stalls, since the request timeout stops at the headers.
|
||||
*/
|
||||
@WithDefault("1000")
|
||||
int errorBodyTimeoutMillis();
|
||||
}
|
||||
|
||||
interface TextractServiceConfig {
|
||||
|
||||
+68
-63
@@ -29,6 +29,7 @@ import java.util.Map;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Consumer;
|
||||
@@ -51,6 +52,7 @@ public class ProxyBackend implements BedrockBackend {
|
||||
// Config is immutable for the process's lifetime, so the mapping string is parsed
|
||||
// once here rather than on every Converse request.
|
||||
private final Map<String, String> modelMapping;
|
||||
private final Duration errorBodyReadTimeout;
|
||||
|
||||
private final HttpClient httpClient = HttpClient.newBuilder()
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
@@ -63,6 +65,7 @@ public class ProxyBackend implements BedrockBackend {
|
||||
this.config = config;
|
||||
this.currentRequest = currentRequest;
|
||||
this.modelMapping = parseModelMapping(config.services().bedrockRuntime().proxy().modelMapping().orElse(""));
|
||||
this.errorBodyReadTimeout = Duration.ofMillis(config.services().bedrockRuntime().proxy().errorBodyTimeoutMillis());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -73,16 +76,21 @@ public class ProxyBackend implements BedrockBackend {
|
||||
HttpRequest request = buildHttpRequest(proxyConfig, openAiRequest);
|
||||
|
||||
long start = System.nanoTime();
|
||||
HttpResponse<String> response = invoke(modelId, request, HttpResponse.BodyHandlers.ofString());
|
||||
long latencyMs = (System.nanoTime() - start) / 1_000_000;
|
||||
|
||||
if (response.statusCode() >= 300) {
|
||||
throw failedRequest(response.statusCode(), response.body());
|
||||
UpstreamCall call = send(modelId, request, "backend", "request");
|
||||
String responseBody;
|
||||
try (InputStream body = call.response().body()) {
|
||||
responseBody = new String(body.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException failure) {
|
||||
LOG.warnv("Bedrock proxy backend call failed: modelId={0}", modelId);
|
||||
throw new AwsException("ModelErrorException", "Proxy backend unavailable or disconnected.", 424);
|
||||
} finally {
|
||||
call.finish();
|
||||
}
|
||||
long latencyMs = (System.nanoTime() - start) / 1_000_000;
|
||||
|
||||
JsonNode openAiResponse;
|
||||
try {
|
||||
openAiResponse = objectMapper.readTree(response.body());
|
||||
openAiResponse = objectMapper.readTree(responseBody);
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("ModelErrorException", "Proxy backend returned malformed JSON: " + e.getMessage(), 424);
|
||||
}
|
||||
@@ -110,62 +118,15 @@ public class ProxyBackend implements BedrockBackend {
|
||||
// BedrockOpenAiTranslator.streamBedrockEvents).
|
||||
HttpRequest request = buildHttpRequest(proxyConfig, openAiRequest);
|
||||
long startNanos = System.nanoTime();
|
||||
// A stalled upstream must be closed on caller disconnect without waiting for another token.
|
||||
RoutingContext context = currentRequest.getCurrent();
|
||||
CompletableFuture<HttpResponse<InputStream>> pending = httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream());
|
||||
AtomicBoolean complete = new AtomicBoolean();
|
||||
Thread monitor = monitorCancellation(context.response()::closed, complete, () -> {
|
||||
pending.thenAccept(response -> closeBody(response.body()));
|
||||
pending.cancel(true);
|
||||
});
|
||||
HttpResponse<InputStream> response;
|
||||
try {
|
||||
response = pending.get();
|
||||
if (response.statusCode() >= 300) {
|
||||
String errorBody;
|
||||
try {
|
||||
errorBody = new String(response.body().readNBytes(8192), StandardCharsets.UTF_8);
|
||||
} catch (IOException unavailable) {
|
||||
LOG.warnv("Failed to read Bedrock proxy error response: modelId={0}, status={1}",
|
||||
modelId, response.statusCode());
|
||||
errorBody = "";
|
||||
} finally {
|
||||
closeBody(response.body());
|
||||
}
|
||||
throw failedRequest(response.statusCode(), errorBody);
|
||||
}
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
pending.thenAccept(completed -> closeBody(completed.body()));
|
||||
pending.cancel(true);
|
||||
complete.set(true);
|
||||
monitor.interrupt();
|
||||
throw new AwsException("ModelErrorException", "Proxy stream interrupted.", 424);
|
||||
} catch (ExecutionException | CancellationException failure) {
|
||||
complete.set(true);
|
||||
monitor.interrupt();
|
||||
if (failure.getCause() instanceof HttpTimeoutException) {
|
||||
LOG.warnv("Bedrock proxy backend timed out: modelId={0}", modelId);
|
||||
throw new AwsException("ModelTimeoutException", "Proxy stream timed out.", 408);
|
||||
}
|
||||
if (failure instanceof ExecutionException) {
|
||||
LOG.warnv("Bedrock proxy backend call failed: modelId={0}", modelId);
|
||||
}
|
||||
throw new AwsException("ModelErrorException", "Proxy stream unavailable or disconnected.", 424);
|
||||
} catch (RuntimeException failure) {
|
||||
complete.set(true);
|
||||
monitor.interrupt();
|
||||
throw failure;
|
||||
}
|
||||
UpstreamCall call = send(modelId, request, "stream", "stream");
|
||||
return output -> {
|
||||
try (InputStream body = response.body();
|
||||
try (InputStream body = call.response().body();
|
||||
Stream<String> lines = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)).lines()) {
|
||||
BedrockOpenAiTranslator.streamBedrockEvents(objectMapper, lines, output, startNanos);
|
||||
} catch (IOException failure) {
|
||||
throw new UncheckedIOException(failure);
|
||||
} finally {
|
||||
complete.set(true);
|
||||
monitor.interrupt();
|
||||
call.finish();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -184,27 +145,71 @@ public class ProxyBackend implements BedrockBackend {
|
||||
"Proxy backend returned HTTP %d: %s".formatted(response, truncate(errorBody, 512)), 424);
|
||||
}
|
||||
|
||||
private <T> HttpResponse<T> invoke(String modelId, HttpRequest request, HttpResponse.BodyHandler<T> bodyHandler) {
|
||||
/**
|
||||
* Sends the request and returns once a successful status arrives, leaving the body to the
|
||||
* caller. The cancellation monitor keeps running until {@link UpstreamCall#finish()}, so a
|
||||
* caller disconnect still closes the upstream while its body is read. An error status is
|
||||
* thrown here, after a read of its body that a timer cuts off at the deadline: the request
|
||||
* timeout stops at the headers, so nothing else bounds a backend that stalls mid-error-body.
|
||||
*/
|
||||
private UpstreamCall send(String modelId, HttpRequest request, String subject, String interruptedSubject) {
|
||||
// A stalled upstream must be closed on caller disconnect without waiting for another token.
|
||||
RoutingContext context = currentRequest.getCurrent();
|
||||
CompletableFuture<HttpResponse<T>> pending = httpClient.sendAsync(request, bodyHandler);
|
||||
CompletableFuture<HttpResponse<InputStream>> pending = httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream());
|
||||
AtomicBoolean complete = new AtomicBoolean();
|
||||
Thread monitor = monitorCancellation(context.response()::closed, complete, () -> pending.cancel(true));
|
||||
Thread monitor = monitorCancellation(context.response()::closed, complete, () -> {
|
||||
pending.thenAccept(response -> closeBody(response.body()));
|
||||
pending.cancel(true);
|
||||
});
|
||||
UpstreamCall call;
|
||||
try {
|
||||
return pending.get();
|
||||
call = new UpstreamCall(pending.get(), complete, monitor);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
pending.thenAccept(completed -> closeBody(completed.body()));
|
||||
pending.cancel(true);
|
||||
throw new AwsException("ModelErrorException", "Proxy request interrupted.", 424);
|
||||
complete.set(true);
|
||||
monitor.interrupt();
|
||||
throw new AwsException("ModelErrorException", "Proxy " + interruptedSubject + " interrupted.", 424);
|
||||
} catch (ExecutionException | CancellationException failure) {
|
||||
complete.set(true);
|
||||
monitor.interrupt();
|
||||
if (failure.getCause() instanceof HttpTimeoutException) {
|
||||
LOG.warnv("Bedrock proxy backend timed out: modelId={0}", modelId);
|
||||
throw new AwsException("ModelTimeoutException", "Proxy backend timed out.", 408);
|
||||
throw new AwsException("ModelTimeoutException", "Proxy " + subject + " timed out.", 408);
|
||||
}
|
||||
if (failure instanceof ExecutionException) {
|
||||
LOG.warnv("Bedrock proxy backend call failed: modelId={0}", modelId);
|
||||
}
|
||||
throw new AwsException("ModelErrorException", "Proxy backend unavailable or disconnected.", 424);
|
||||
throw new AwsException("ModelErrorException", "Proxy " + subject + " unavailable or disconnected.", 424);
|
||||
}
|
||||
HttpResponse<InputStream> response = call.response();
|
||||
if (response.statusCode() < 300) {
|
||||
return call;
|
||||
}
|
||||
// Collecting error details must not delay a known upstream failure indefinitely.
|
||||
CompletableFuture.delayedExecutor(errorBodyReadTimeout.toMillis(), TimeUnit.MILLISECONDS)
|
||||
.execute(() -> {
|
||||
if (!complete.get()) {
|
||||
closeBody(response.body());
|
||||
}
|
||||
});
|
||||
String errorBody;
|
||||
try {
|
||||
errorBody = new String(response.body().readNBytes(8192), StandardCharsets.UTF_8);
|
||||
} catch (IOException unavailable) {
|
||||
LOG.warnv("Failed to read Bedrock proxy error response: modelId={0}, status={1}",
|
||||
modelId, response.statusCode());
|
||||
errorBody = "";
|
||||
} finally {
|
||||
closeBody(response.body());
|
||||
call.finish();
|
||||
}
|
||||
throw failedRequest(response.statusCode(), errorBody);
|
||||
}
|
||||
|
||||
private record UpstreamCall(HttpResponse<InputStream> response, AtomicBoolean complete, Thread monitor) {
|
||||
void finish() {
|
||||
complete.set(true);
|
||||
monitor.interrupt();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user