fix(lambda): report real runtime errors instead of Function.TimedOut (#3505)

RuntimeApiServer now reports real init errors, crashed processes, and
the actual FunctionError instead of Function.TimedOut, and retains the
fault payload so a same-cause enqueue() rejection returns it instead of
a generic ContainerStopped.

* Fix #3314

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-09-12 23:04:16 -05:00
1 parent 9f9a828439
commit 34062f6383
3 files changed
+395 -19

No files matched your search

@@ -19,6 +19,8 @@ import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServerFactory;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.WaitResponse;
import com.github.dockerjava.core.command.WaitContainerResultCallback;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
@@ -404,6 +406,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
// Now start the container with code in place
lifecycleManager.startCreated(containerId, spec);
watchForUnexpectedExit(dockerClient, containerId, runtimeApiServer);
// Extensions can log as soon as they start, which is before the container's own log stream
// is attached below. Create the group/stream up front so those early lines are not dropped
@@ -1235,6 +1238,36 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
/** Where a container's output is sent: the CloudWatch log group/stream and its region. */
private record LogDestination(String logGroup, String logStream, String region) { }
/**
* Arms an async watch (via Docker's own wait-for-exit API, not polling) that notices when
* this container's main process dies while nothing inside the runtime reported it - a
* stray {@code sys.exit}/{@code process.exit}/{@code System.exit} in the handler, or any
* other crash (see #3314). Without this, a dead runtime left every pending/in-flight
* invocation waiting out the full function timeout to be told {@code Function.TimedOut}
* instead of the {@code Runtime.ExitError} AWS reports immediately.
*
* <p>Fires exactly once per container, on whatever exit eventually happens - including an
* intentional {@code docker stop} during normal teardown. {@link RuntimeApiServer
* #handleRuntimeProcessExited} itself distinguishes a genuine crash from that case (its own
* {@code stopped}/{@code faulted} guard), so this method only needs to forward the event;
* it does not need to be un-armed on the teardown path.
*/
private void watchForUnexpectedExit(DockerClient dockerClient, String containerId,
RuntimeApiServer runtimeApiServer) {
try {
dockerClient.waitContainerCmd(containerId).exec(new WaitContainerResultCallback() {
@Override
public void onNext(WaitResponse response) {
super.onNext(response);
Integer statusCode = response.getStatusCode();
runtimeApiServer.handleRuntimeProcessExited(statusCode != null ? statusCode : -1);
}
});
} catch (RuntimeException e) {
LOG.debugv(e, "Could not arm exit watcher for container {0}", containerId);
}
}
private void launchExtensions(DockerClient dockerClient, String containerId, String functionName,
RuntimeApiServer runtimeApiServer, LogDestination logDestination) {
List<String> extensionNames = listExtensionBinaries(dockerClient, containerId, functionName);
@@ -207,6 +207,25 @@ public class RuntimeApiServer {
// rather than aborted mid-invoke. WarmPool performs the actual teardown afterwards.
private volatile boolean faulted;
/**
* The runtime's own error payload when {@code faulted} was set by {@link #handleInitError}
* or {@link #handleRuntimeProcessExited} - i.e. by a real runtime fault, as opposed to an
* extension init/exit error or an intentional {@link #quiesce()}. Written under {@code lock}
* in the same block that sets {@code faulted}, so the two are always consistent.
*
* <p>{@code warmPool.acquire(fn)} launches the container and only returns afterward does
* {@code LambdaExecutorService.executeSync()} create the {@code PendingInvocation} and call
* {@link #enqueue}, so a cold-start init error or an immediate crash can fault this server
* before any invocation exists for {@code handleInitError}/{@code handleRuntimeProcessExited}
* to strand. Retaining the payload here lets a later {@link #enqueue} rejection return the
* runtime's actual reported error instead of the generic {@link #CONTAINER_STOPPED_PAYLOAD}.
*
* <p>Left {@code null} for a fault raised by {@link #handleExtensionFatalError} and for a
* plain {@code quiesce()} with no fault, both of which should keep returning
* {@code CONTAINER_STOPPED_PAYLOAD} on a later {@code enqueue} rejection.
*/
private volatile byte[] fatalRuntimeErrorPayload;
// Init-readiness barrier. ContainerLauncher launches extension binaries as detached `docker
// exec`s and returns immediately, so without this the first invocation can reach the runtime
// before an extension is ready — the adapter never sees that invoke and silently misses it.
@@ -384,25 +403,9 @@ public class RuntimeApiServer {
sendStatusOk(ctx);
});
// POST /runtime/invocation/{requestId}/error — failure
router.post(ERROR_PATH).handler(ctx -> {
String requestId = ctx.pathParam("requestId");
PendingInvocation invocation = inFlight.remove(requestId);
if (invocation != null) {
byte[] payload = ctx.body().buffer() != null ? ctx.body().buffer().getBytes() : new byte[0];
String errorType = ctx.request().getHeader("Lambda-Runtime-Function-Error-Type");
String functionError = errorType != null && errorType.contains("Runtime") ? "Unhandled" : "Handled";
InvokeResult result = new InvokeResult(200, functionError, payload, null, requestId);
invocation.getResultFuture().complete(result);
}
sendStatusOk(ctx);
});
router.post(ERROR_PATH).handler(this::handleInvocationError);
// POST /runtime/init/error — runtime initialization failure
router.post(INIT_ERROR_PATH).handler(ctx -> {
LOG.warnv("Lambda runtime reported init error on port {0}", String.valueOf(port));
sendStatusOk(ctx);
});
router.post(INIT_ERROR_PATH).handler(this::handleInitError);
// POST /extension/register — an extension process (e.g. aws-lambda-web-adapter)
// registers to receive lifecycle events. Real AWS requires the Lambda-Extension-Name
@@ -772,6 +775,7 @@ public class RuntimeApiServer {
public CompletableFuture<InvokeResult> enqueue(PendingInvocation invocation) {
boolean rejected;
byte[] rejectionPayload = null;
RoutingContext waitingCtxForInvocation = null;
synchronized (lock) {
@@ -781,6 +785,12 @@ public class RuntimeApiServer {
// failing fast. Read inside the lock alongside `stopped` so the accept/reject decision
// stays a single atomic step.
rejected = stopped || faulted;
if (rejected && faulted) {
// A genuine runtime fault (init error or process exit) beats plain `stopped`: the
// caller gets the runtime's actual reported error rather than the generic
// CONTAINER_STOPPED_PAYLOAD used for an unfaulted, intentional quiesce().
rejectionPayload = fatalRuntimeErrorPayload;
}
if (!rejected) {
waitingCtxForInvocation = waitingContexts.poll();
if (waitingCtxForInvocation == null) {
@@ -795,8 +805,9 @@ public class RuntimeApiServer {
}
if (rejected) {
byte[] payload = rejectionPayload != null ? rejectionPayload : CONTAINER_STOPPED_PAYLOAD;
invocation.getResultFuture().complete(
new InvokeResult(200, "Unhandled", CONTAINER_STOPPED_PAYLOAD, null, invocation.getRequestId()));
new InvokeResult(200, "Unhandled", payload, null, invocation.getRequestId()));
return invocation.getResultFuture();
}
@@ -859,6 +870,62 @@ public class RuntimeApiServer {
return false;
}
/**
* Handles {@code POST /runtime/invocation/{requestId}/error}: the runtime reports that the
* handler itself failed (an uncaught exception, {@code callback(err)}, a response Lambda
* could not marshal, ...).
*
* <p>Always completes with {@code FunctionError: Unhandled} - real AWS reports that for
* every one of these regardless of runtime or error shape. The {@code
* Lambda-Runtime-Function-Error-Type} header this used to be keyed on does not decide it
* (see #3314): the Python and Node.js RICs don't even send that header on this path, and
* the Java RIC's own vocabulary ({@code Runtime.UserException}, {@code
* Runtime.BadFunctionCode}) is coincidentally what an earlier, narrower
* {@code contains("Runtime")} heuristic here keyed on. {@code Handled} is a legacy value
* current runtimes never produce.
*/
private void handleInvocationError(RoutingContext ctx) {
String requestId = ctx.pathParam("requestId");
PendingInvocation invocation = inFlight.remove(requestId);
if (invocation != null) {
byte[] payload = ctx.body().buffer() != null ? ctx.body().buffer().getBytes() : new byte[0];
invocation.getResultFuture().complete(new InvokeResult(200, "Unhandled", payload, null, requestId));
}
sendStatusOk(ctx);
}
/**
* Handles {@code POST /runtime/init/error}: the runtime reports a failed initialization
* (module not importable, handler missing, a syntax error, an exception raised at import
* time) and exits without ever calling {@code NEXT_PATH}. There is therefore no in-flight
* invocation to fail - the one that triggered this cold start is still sitting in {@code
* pendingQueue} - and the environment is condemned the same way an extension init/exit
* error condemns it (see {@link #faulted}'s doc): the runtime process is gone, so nothing
* will ever answer a {@code /next} poll on this container again.
*/
private void handleInitError(RoutingContext ctx) {
byte[] payload = ctx.body().buffer() != null ? ctx.body().buffer().getBytes() : new byte[0];
LOG.warnv("Lambda runtime reported init error on port {0}", String.valueOf(port));
List<PendingInvocation> stranded;
synchronized (lock) {
faulted = true;
// Retained for a possible later enqueue(): the invocation that triggered this cold
// start may not exist yet (see fatalRuntimeErrorPayload's doc), in which case
// `stranded` below is empty and this is the only place the real error survives.
fatalRuntimeErrorPayload = payload;
stranded = new ArrayList<>(pendingQueue);
pendingQueue.clear();
stranded.addAll(inFlight.values());
inFlight.clear();
}
for (PendingInvocation invocation : stranded) {
invocation.getResultFuture().complete(
new InvokeResult(200, "Unhandled", payload, null, invocation.getRequestId()));
}
sendStatusOk(ctx);
}
private void sendStatusOk(RoutingContext ctx) {
ctx.response()
.setStatusCode(202)
@@ -942,6 +1009,61 @@ public class RuntimeApiServer {
+ "init/exit error\"}");
}
/**
* Called by {@code ContainerLauncher}'s Docker exit watcher when the container's main
* process has died - a stray {@code sys.exit}/{@code process.exit}/{@code System.exit} in
* the handler, or any other crash - detected from outside the runtime, since a dead
* process obviously cannot report anything itself through {@code /runtime/invocation/
* {id}/error}. Without this, a crash left every pending/in-flight invocation waiting out
* the full function timeout to be told {@code Function.TimedOut}, instead of the real
* {@code Runtime.ExitError} AWS reports immediately (see #3314).
*
* <p>Condemns the environment like an extension init/exit error or a runtime init error
* does: this container must never be pooled or reused, its main process is gone.
*
* <p>A no-op when {@code stopped} or already {@code faulted}: an intentional teardown
* calls {@code quiesce()} (which sets {@code stopped}) before the container is actually
* stopped/removed, so the exit event this same teardown causes must not be reinterpreted
* as a crash.
*/
public void handleRuntimeProcessExited(int exitCode) {
List<PendingInvocation> stranded;
synchronized (lock) {
if (stopped || faulted) {
return;
}
faulted = true;
// Retained for a possible later enqueue(): the invocation that would have hit this
// container may not exist yet (see fatalRuntimeErrorPayload's doc), so this generic,
// requestId-free payload is built here rather than only per-stranded-invocation below.
fatalRuntimeErrorPayload = buildRuntimeExitErrorPayload(
"Runtime exited with error: exit status " + exitCode);
stranded = new ArrayList<>(pendingQueue);
pendingQueue.clear();
stranded.addAll(inFlight.values());
inFlight.clear();
}
if (!stranded.isEmpty()) {
LOG.warnv("Lambda runtime process on port {0} exited unexpectedly (status {1}) "
+ "with {2} invocation(s) pending",
String.valueOf(port), String.valueOf(exitCode), String.valueOf(stranded.size()));
}
for (PendingInvocation invocation : stranded) {
String message = "RequestId: " + invocation.getRequestId()
+ " Error: Runtime exited with error: exit status " + exitCode;
invocation.getResultFuture().complete(new InvokeResult(
200, "Unhandled", buildRuntimeExitErrorPayload(message), null, invocation.getRequestId()));
}
}
private static byte[] buildRuntimeExitErrorPayload(String message) {
return new JsonObject()
.put("errorType", "Runtime.ExitError")
.put("errorMessage", message)
.encode()
.getBytes(java.nio.charset.StandardCharsets.UTF_8);
}
private void handleExtensionFatalError(RoutingContext ctx, String phase) {
String identifier = ctx.request().getHeader(EXTENSION_ID_HEADER);
String errorType = ctx.request().getHeader(EXTENSION_ERROR_TYPE_HEADER);
@@ -256,6 +256,227 @@ class RuntimeApiServerTest {
assertEquals("OK", new JsonObject(response.body()).getString("status"));
}
/**
* Regression for #3314: the Python and Node.js runtime interface clients never send
* {@code Lambda-Runtime-Function-Error-Type} on {@code /invocation/{id}/error} at all, so
* FunctionError must not depend on that header being present or on its value - it is
* always {@code Unhandled}, matching AWS for every runtime.
*/
@Test
@Timeout(15)
void errorEndpoint_reportsUnhandledEvenWithoutTheErrorTypeHeader() throws Exception {
assertErrorEndpointReportsUnhandled("req-no-header", null);
}
/**
* The Java RIC does send the header, with its own vocabulary ({@code
* Runtime.UserException}); an earlier, narrower {@code contains("Runtime")} heuristic
* happened to key on exactly that value. Must still be {@code Unhandled}.
*/
@Test
@Timeout(15)
void errorEndpoint_reportsUnhandledWithARuntimeVocabularyHeader() throws Exception {
assertErrorEndpointReportsUnhandled("req-runtime-header", "Runtime.UserException");
}
/**
* A plain error type with no "Runtime" substring (e.g. a Python {@code ValueError}) used to
* fall through the old heuristic to the legacy {@code Handled} value. AWS reports
* {@code Unhandled} regardless.
*/
@Test
@Timeout(15)
void errorEndpoint_reportsUnhandledWithAPlainErrorTypeHeader() throws Exception {
assertErrorEndpointReportsUnhandled("req-plain-header", "ValueError");
}
private void assertErrorEndpointReportsUnhandled(String requestId, String errorTypeHeader) throws Exception {
CompletableFuture<InvokeResult> resultFuture = new CompletableFuture<>();
PendingInvocation invocation = new PendingInvocation(
requestId, "{}".getBytes(), System.currentTimeMillis() + 60_000,
"arn:aws:lambda:us-east-1:000000000000:function:test", resultFuture);
server.enqueue(invocation);
httpClient.send(HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/invocation/next"))
.GET().build(),
HttpResponse.BodyHandlers.ofString());
HttpRequest.Builder errorRequest = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + port
+ "/2018-06-01/runtime/invocation/" + requestId + "/error"))
.POST(HttpRequest.BodyPublishers.ofString("{\"errorMessage\":\"boom\",\"errorType\":\"X\"}"));
if (errorTypeHeader != null) {
errorRequest.header("Lambda-Runtime-Function-Error-Type", errorTypeHeader);
}
httpClient.send(errorRequest.build(), HttpResponse.BodyHandlers.ofString());
InvokeResult result = resultFuture.get(2, TimeUnit.SECONDS);
assertEquals("Unhandled", result.getFunctionError());
assertTrue(new String(result.getPayload()).contains("boom"));
}
/**
* Regression for #3314: a runtime that reports a failed initialization (module not
* importable, handler missing, a syntax error, ...) via {@code /runtime/init/error} never
* calls {@code /next} - it exits immediately. The invocation that triggered this cold
* start must fail with the runtime's own reported payload and {@code Unhandled}, not sit
* until the function timeout to be told {@code Function.TimedOut}.
*/
@Test
@Timeout(15)
void initErrorEndpoint_failsThePendingInvocationAndCondemnsTheEnvironment() throws Exception {
CompletableFuture<InvokeResult> resultFuture = new CompletableFuture<>();
PendingInvocation invocation = new PendingInvocation(
"req-init-error", "{}".getBytes(), System.currentTimeMillis() + 60_000,
"arn:aws:lambda:us-east-1:000000000000:function:test", resultFuture);
server.enqueue(invocation);
assertFalse(resultFuture.isDone(), "invocation must still be queued, waiting for a /next poller");
HttpResponse<String> initErrorResponse = httpClient.send(HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/init/error"))
.header("Lambda-Runtime-Function-Error-Type", "Runtime.ImportModuleError")
.POST(HttpRequest.BodyPublishers.ofString(
"{\"errorMessage\":\"Unable to import module\","
+ "\"errorType\":\"Runtime.ImportModuleError\"}"))
.build(),
HttpResponse.BodyHandlers.ofString());
assertEquals(202, initErrorResponse.statusCode());
InvokeResult result = resultFuture.get(2, TimeUnit.SECONDS);
assertEquals("Unhandled", result.getFunctionError());
assertTrue(new String(result.getPayload()).contains("Unable to import module"));
assertTrue(server.isFaulted(), "a condemned environment must never be pooled or reused");
CompletableFuture<InvokeResult> secondFuture = new CompletableFuture<>();
server.enqueue(new PendingInvocation(
"req-after-init-error", "{}".getBytes(), System.currentTimeMillis() + 60_000,
"arn:aws:lambda:us-east-1:000000000000:function:test", secondFuture));
assertEquals("Unhandled", secondFuture.get(2, TimeUnit.SECONDS).getFunctionError(),
"a condemned environment must fail new work immediately, not queue it to a dead runtime");
}
/**
* Regression: production enqueues in the opposite order used above. {@code
* LambdaExecutorService.executeSync()} calls {@code warmPool.acquire(fn)} first, which
* launches the container, and only creates/enqueues the {@code PendingInvocation} once
* that returns - so a cold-start init error can fault this server before any invocation
* exists for {@code handleInitError} to strand. A later {@code enqueue()} on the now-faulted
* server must still return the runtime's own reported error, not the generic
* {@code ContainerStopped} fallback.
*/
@Test
@Timeout(15)
void initErrorBeforeEnqueue_completesTheLaterInvocationWithTheOriginalInitError() throws Exception {
HttpResponse<String> initErrorResponse = httpClient.send(HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/init/error"))
.header("Lambda-Runtime-Function-Error-Type", "Runtime.ImportModuleError")
.POST(HttpRequest.BodyPublishers.ofString(
"{\"errorMessage\":\"Unable to import module\","
+ "\"errorType\":\"Runtime.ImportModuleError\"}"))
.build(),
HttpResponse.BodyHandlers.ofString());
assertEquals(202, initErrorResponse.statusCode());
assertTrue(server.isFaulted(), "a condemned environment must never be pooled or reused");
CompletableFuture<InvokeResult> resultFuture = new CompletableFuture<>();
server.enqueue(new PendingInvocation(
"req-init-error-cold-start", "{}".getBytes(), System.currentTimeMillis() + 60_000,
"arn:aws:lambda:us-east-1:000000000000:function:test", resultFuture));
InvokeResult result = resultFuture.get(2, TimeUnit.SECONDS);
assertEquals("Unhandled", result.getFunctionError());
String payload = new String(result.getPayload());
assertTrue(payload.contains("Runtime.ImportModuleError"), payload);
assertTrue(payload.contains("Unable to import module"), payload);
assertFalse(payload.contains("ContainerStopped"), payload);
}
/**
* Regression for #3314: nothing inside the runtime can report its own process dying (a
* stray {@code sys.exit}/{@code process.exit}/{@code System.exit} in the handler, or any
* other crash), so {@code ContainerLauncher}'s Docker exit watcher calls this directly.
* The in-flight invocation must fail immediately with {@code Runtime.ExitError}, not wait
* out the full function timeout for {@code Function.TimedOut}.
*/
@Test
@Timeout(15)
void handleRuntimeProcessExited_failsInFlightInvocationWithRuntimeExitError() throws Exception {
CompletableFuture<InvokeResult> resultFuture = new CompletableFuture<>();
PendingInvocation invocation = new PendingInvocation(
"req-exit", "{}".getBytes(), System.currentTimeMillis() + 60_000,
"arn:aws:lambda:us-east-1:000000000000:function:test", resultFuture);
server.enqueue(invocation);
httpClient.send(HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/invocation/next"))
.GET().build(),
HttpResponse.BodyHandlers.ofString());
assertEquals(1, server.inFlightSize(), "invocation must be in flight before the process exits");
server.handleRuntimeProcessExited(1);
InvokeResult result = resultFuture.get(2, TimeUnit.SECONDS);
assertEquals("Unhandled", result.getFunctionError());
String payload = new String(result.getPayload());
assertTrue(payload.contains("Runtime.ExitError"), payload);
assertTrue(payload.contains("req-exit"), payload);
assertTrue(payload.contains("exit status 1"), payload);
assertTrue(server.isFaulted());
}
/**
* Regression: mirrors {@code initErrorBeforeEnqueue_completesTheLaterInvocationWithTheOriginal
* InitError} for the process-exit path. {@code warmPool.acquire(fn)} arms {@code
* ContainerLauncher}'s Docker exit watcher while it launches the container, before {@code
* LambdaExecutorService.executeSync()} creates and enqueues the {@code PendingInvocation} -
* so an immediate crash can fault this server with nothing yet in {@code pendingQueue}/{@code
* inFlight} for {@code handleRuntimeProcessExited} to strand. The invocation enqueued
* afterward must still surface {@code Runtime.ExitError}, not {@code ContainerStopped}.
*/
@Test
@Timeout(15)
void processExitBeforeEnqueue_completesTheLaterInvocationWithRuntimeExitError() throws Exception {
server.handleRuntimeProcessExited(1);
assertTrue(server.isFaulted(), "a condemned environment must never be pooled or reused");
CompletableFuture<InvokeResult> resultFuture = new CompletableFuture<>();
server.enqueue(new PendingInvocation(
"req-exit-cold-start", "{}".getBytes(), System.currentTimeMillis() + 60_000,
"arn:aws:lambda:us-east-1:000000000000:function:test", resultFuture));
InvokeResult result = resultFuture.get(2, TimeUnit.SECONDS);
assertEquals("Unhandled", result.getFunctionError());
String payload = new String(result.getPayload());
assertTrue(payload.contains("Runtime.ExitError"), payload);
assertTrue(payload.contains("exit status 1"), payload);
assertFalse(payload.contains("ContainerStopped"), payload);
}
/**
* An intentional teardown ({@code quiesce()}, which sets {@code stopped}) always runs
* before {@code ContainerLauncher} actually stops the container - so the exit event that
* same teardown causes must not be reinterpreted as a crash and re-fail an invocation
* {@code quiesce()} already completed with {@code ContainerStopped}.
*/
@Test
@Timeout(15)
void handleRuntimeProcessExited_isANoOpAfterIntentionalTeardown() throws Exception {
CompletableFuture<InvokeResult> resultFuture = new CompletableFuture<>();
PendingInvocation invocation = new PendingInvocation(
"req-teardown", "{}".getBytes(), System.currentTimeMillis() + 60_000,
"arn:aws:lambda:us-east-1:000000000000:function:test", resultFuture);
server.enqueue(invocation);
server.quiesce();
InvokeResult quiesceResult = resultFuture.get(2, TimeUnit.SECONDS);
server.handleRuntimeProcessExited(0);
assertEquals(quiesceResult.getFunctionError(), resultFuture.get().getFunctionError());
assertTrue(new String(resultFuture.get().getPayload()).contains("ContainerStopped"),
"must keep quiesce()'s ContainerStopped result, not overwrite it with Runtime.ExitError");
}
@Test
@Timeout(15)
void stopCompletesInFlightWithContainerStopped() throws Exception {