fix(lambda): SIGTERM container before closing runtime API socket (#2098)

* fix(lambda): SIGTERM container before closing runtime API socket

Real AWS Lambda tears an execution environment down by sending SIGTERM
to the runtime while the runtime API stays responsive; the runtime
library (awslambdaric, Node.js RIC, ...) sees the signal and exits
cleanly on the OS default handler. Floci closed the runtime API socket
first, causing the parked /invocation/next long-poll to wake with a
network error before SIGTERM could reach the process — the runtime
library treated that as a fault and printed a ~40-line traceback on
every clean invocation.

Split RuntimeApiServer.stop() into quiesce() (settle bookkeeping,
notify extensions, complete pending/in-flight invocations) and close()
(release the httpServer socket). Reorder ContainerLauncher.stop() to
quiesce → docker stop → close, so the runtime process receives SIGTERM
against a still-bound socket and exits cleanly. Parked runtime pollers
now stay parked through quiesce() rather than receiving an
AWS-undocumented 204, matching real Lambda behaviour where a shutting
runtime is expected to exit on SIGTERM without the API side responding.

Docker's stop timeout is now selected from AWS's documented
Shutdown-phase grace tiers: 2s when at least one extension is
registered, 1s (rounding up AWS's 300ms runtime sub-budget) otherwise.

Closes #2091

* fix(lambda): populate inFlight under lock to close teardown race

enqueue() and the /invocation/next handler polled the parked ctx or
pending invocation inside the server lock, then dispatched
sendInvocation() asynchronously on the Vert.x context. inFlight was
populated inside sendInvocation, after the lock had been released — so
a concurrent quiesce() could sweep pendingQueue and inFlight (both
empty at that instant) and miss an invocation that was already in
flight from the caller's perspective. The invocation's future would
then never complete, and the caller would hang until the function's
deadline.

Move inFlight.put(...) into the same synchronized block as the poll,
so quiesce()'s sweep and enqueue's dispatch are ordered by the lock.
sendInvocation still does its inFlight.put — now a same-value overwrite
in the fast path, and the source of truth for the slow path where
inFlight.put runs earlier than the ctx write does.

Add two property tests exercising the race window: one where enqueue()
hands the invocation to a parked poller, one where NEXT_PATH polls
from pendingQueue, both followed by an immediate stop().

* fix(lambda): drop deferred dispatch if quiesce completed the invocation

After enqueue() records an invocation in inFlight and hands it to a
parked poller, the actual sendInvocation() runs on a deferred Vert.x
context. If quiesce() lands between the two, it sweeps inFlight and
completes the caller's future with ContainerStopped — but the deferred
callback would still deliver the invocation to the runtime, which
would execute the handler (side effects) and POST /response into a
future that's already completed. CompletableFuture silently discards
the second complete(), so the caller sees an error even though the
function ran and succeeded.

Re-check `stopped && inFlight.get(requestId) == null` inside the lock
before dispatching, and skip the dispatch if so. Applies to both entry
points: enqueue()'s deferred sendInvocation and NEXT_PATH's
synchronous-but-post-lock-release sendInvocation.

Add a property test that parks a poller, enqueues, immediately stops,
and asserts the poller does NOT receive a 200 with the invocation
payload — only a socket close from close() is acceptable.

* fix(lambda): make quiesce's inFlight sweep atomic under lock

The dispatch guards in enqueue()'s deferred callback and NEXT_PATH read
`stopped` under the server lock. Their correctness relies on the
invariant: once quiesce() releases its lock, stopped=true implies
inFlight is empty. The prior code cleared inFlight *outside* the lock,
which left a window where a dispatch could observe stopped=true while
an inFlight entry it's about to deliver was still present — the guard
would let the delivery through, quiesce would then complete the future
with ContainerStopped, and the runtime's /response would be silently
discarded.

Snapshot inFlight inside the lock (symmetric with pendingQueue two
lines above), complete futures outside. Dispatch guards simplified to
just `stopped` since the atomicity now holds by construction. Drop
sendInvocation's redundant inFlight.put — both entry points pre-insert
under the lock.

Also:
- Narrow ContainerLauncher.stop()'s timeout comment: docker's --time is
  a max wait for PID 1, not a grace floor. Extensions run as sibling
  `docker exec`s and are killed with the container; the 2s ceiling
  doesn't back the deadlineMs advertised to extensions.
- Fix javadoc placement: hasRegisteredExtensions() had accidentally
  inherited isFaulted()'s comment. Give each its own doc.

Add quiesceAtomicallyClearsInFlightWithStopped test: multiple in-flight
invocations → quiesce → all futures must complete with ContainerStopped.

* fix(lambda): reconcile with #2156 write-flush + trim comments

#2156 landed the "await parked writes before httpServer.close" pattern
for extension SHUTDOWN dispatches. Reconcile our teardown split with
that: quiesce() schedules extension SHUTDOWN dispatches and records
their aggregate flush completion in a new field extensionWritesFlushed;
close() awaits that field before dropping the httpServer.

Preserves both behaviours: SIGTERM-before-socket-close ordering (this
PR's core value) and the write-flush guarantee (#2156's contribution).

Runtime pollers still stay parked — no 204 — matching real AWS Lambda's
teardown. Trim design-doc-shaped comments to reviewer-friendly length
in the same file.

* test(lambda): add deterministic race tests via test-specific subclass

The three sleep-based race tests (removed here) don't distinguish the
fix from the pre-fix code — they exercise the interleaving with
Thread.sleep and pass either way. Replace them with two latch-gated
tests that reproduce the exact interleaving hampsterx flagged
(enqueue's deferred dispatch, and NEXT_PATH's synchronous dispatch,
each racing against a partially-swept quiesce) and prove the guards
plus atomic inFlight sweep close the silent-discard bug.

The tests use the "test-specific subclass" pattern (Meszaros, xUnit
Test Patterns) rather than a settable-field hook on the production
class: quiesce() and the two dispatch sites call three empty
`protected void` methods that a test subclass overrides to gate on
CountDownLatches. Production has no mutable state, no volatile reads,
and matches Floci's existing `Test-only:` javadoc convention
(ContainerLauncher, LambdaService, LambdaConcurrencyLimiter, ...).

Verified: reverting the atomic-sweep-in-lock fix AND the guard
simplification causes both new tests to fail with the expected
"parked poller received the invocation" assertion. Restoring either
fix alone is enough for the tests to pass, confirming they gate on
the invariant that matters (stopped=true ⇒ inFlight empty).

* fix(lambda): commit enqueue dispatch/requeue decision atomically

Per @abanna's review of #2098. enqueue()'s deferred callback read
waitingCtx.response().ended() twice — once inside `synchronized(lock)`
deciding requeue, once outside deciding send. A client disconnect
between the two reads left neither branch firing and the invocation
stranded in inFlight until the function deadline.

Read ended() exactly once inside the lock and commit dispatch/requeue
before releasing. Adds a deterministic latch-gated race test (two new
Test-only protected seams) that fails on the double-read shape and
passes on the fix. 50/50 tests pass.

* fix(lambda): requeue invocation when sendInvocation's write fails

Per Greptile's P1 review of a1a659b4. Even with the atomic dispatch
decision, a runtime disconnect between the lock-committed decision and
the .end() flush left the invocation stranded in inFlight until the
function deadline — the fluent chain has no failure handler.

Wrap the fluent chain in try/catch (setStatusCode/putHeader throw
synchronously on an already-ended response) and attach .onFailure to
.end() (which returns a failed Future for socket-level failures). Both
paths funnel into one handler that requeues into pendingQueue and drops
the stale inFlight entry — mirror of the ctx-ended branch in enqueue()'s
deferred callback. No-op if quiesce() beat us (stopped=true).

Adds a deterministic test that ends the parked ctx from
beforeSendInvocationWrite and asserts pendingQueueSize=1 + inFlightSize=0.
Fails on the pre-fix write-and-forget shape, passes on the fix. 51/51.
This commit is contained in:
Guinevere Friedman authored and GitHub committed 2026-08-13 09:30:44 -04:00
1 parent a235b76835
commit b911ccd013
4 files changed
+691 -90

No files matched your search

@@ -162,11 +162,23 @@ public class ContainerLifecycleManager {
* @param logStream optional log stream to close (may be null)
*/
public void stopAndRemove(String containerId, Closeable logStream) {
stopAndRemove(containerId, logStream, 5);
}
/**
* Stops and removes a container, closing any associated log stream.
*
* @param containerId the container ID to stop and remove
* @param logStream optional log stream to close (may be null)
* @param stopTimeoutSeconds seconds to wait for the container to stop cleanly after
* SIGTERM before Docker sends SIGKILL. Must be a non-negative integer.
*/
public void stopAndRemove(String containerId, Closeable logStream, int stopTimeoutSeconds) {
LOG.infov("Stopping container {0}", containerId);
boolean stoppedOrMissing = false;
try {
dockerClient.stopContainerCmd(containerId).withTimeout(5).exec();
dockerClient.stopContainerCmd(containerId).withTimeout(stopTimeoutSeconds).exec();
stoppedOrMissing = true;
} catch (NotFoundException e) {
LOG.debugv("Container {0} not found (already removed)", containerId);
@@ -445,17 +445,43 @@ public class ContainerLauncher {
LOG.infov("Stopping container {0}", handle.getContainerId());
handle.setState(ContainerState.STOPPED);
RuntimeApiServer server = handle.getRuntimeApiServer();
// Quiesce first: stop accepting new work, notify extensions, complete pending
// invocations. Existing runtime pollers on /invocation/next stay parked.
server.quiesce();
// Then SIGTERM the container. The runtime library's default SIGTERM handler exits
// the process while the runtime API socket is still up, matching real AWS Lambda's
// shutdown flow.
//
// stopTimeoutSeconds is the ceiling docker waits for PID 1 to exit before SIGKILL,
// not a grace floor: the runtime typically exits promptly, so `docker stop`
// returns shortly after and this value rarely matters end-to-end. Sized against
// AWS's documented Shutdown-phase tiers as a defensive upper bound only — 2s
// when at least one extension is registered (matching AWS's 2000ms
// external-extensions budget), else 1s. NOTE: extensions run as sibling
// `docker exec`s (not children of PID 1) and are killed when the container
// exits; the 2s ceiling does not provide a guaranteed grace window for
// extension shutdown work — only that we will not preempt PID 1 for at least
// that long if it happens to be slow.
int stopTimeoutSeconds = server.hasRegisteredExtensions() ? 2 : 1;
lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream(),
stopTimeoutSeconds);
// Only now close the runtime API socket. Any pollers that were still parked when
// the container exited get terminated by their end of the connection closing;
// this call releases the port for reuse.
try {
handle.getRuntimeApiServer().stop().get(5, TimeUnit.SECONDS);
server.close().get(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException | TimeoutException e) {
LOG.warnv(e, "RuntimeApiServer did not close cleanly for container {0}",
handle.getContainerId());
} finally {
runtimeApiServerFactory.release(handle.getRuntimeApiServer());
runtimeApiServerFactory.release(server);
}
lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream());
}
/**
@@ -127,6 +127,72 @@ public class RuntimeApiServer {
private boolean stopped;
private CompletableFuture<Void> closeFuture;
// Set by quiesce() (under lock); completes when every parked extension SHUTDOWN
// has flushed. close() awaits this before dropping the httpServer (see #2142).
// Null if quiesce() has not run.
private CompletableFuture<Void> extensionWritesFlushed;
/** Test-only: number of /next pollers parked in waitingContexts, for
* tests that want to await the parked state deterministically without sleeping. */
int waitingContextsSize() {
synchronized (lock) {
return waitingContexts.size();
}
}
/** Test-only: number of invocations queued waiting for a /next poller. Used by
* the requeue-on-write-failure test to verify the requeue actually happened. */
int pendingQueueSize() {
synchronized (lock) {
return pendingQueue.size();
}
}
/** Test-only: number of invocations currently in flight. Used alongside
* {@link #pendingQueueSize()} to verify a requeue-on-failure both offered
* to pendingQueue AND cleared the stale inFlight entry. */
int inFlightSize() {
return inFlight.size();
}
/**
* Test-only: called at the start of enqueue()'s deferred sendInvocation,
* before the guard's `stopped` re-check. A test subclass overrides this to
* gate the dispatch on a CountDownLatch and drive a specific interleaving
* with quiesce(). Empty no-op in production.
*/
protected void beforeEnqueueDeferredDispatch() { }
/**
* Test-only: called at the start of NEXT_PATH's post-lock guard block, before
* the guard's `stopped` re-check. Same shape as {@link #beforeEnqueueDeferredDispatch}
* but for the synchronous handler-thread dispatch path.
*/
protected void beforeNextPathDispatchGuard() { }
/**
* Test-only: called inside quiesce() immediately after the lock has been
* released, before any outside-lock work runs. Test subclasses override
* to freeze quiesce at that point and drive a dispatch through the guard
* against a supposedly-partially-swept state, proving atomicity holds.
*/
protected void afterQuiesceStoppedFlagSet() { }
/**
* Test-only: called inside enqueue()'s deferred dispatch after lock release,
* before the send/requeue decision is acted on. Test subclasses override to
* mutate the parked ctx (e.g. end it) and prove the decision was committed
* atomically inside the lock.
*/
protected void afterEnqueueDispatchLockReleased(RoutingContext waitingCtx) { }
/**
* Test-only: called at the top of sendInvocation so tests can observe whether
* a dispatch actually ran. Distinguishes "sent to a dead ctx" from "skipped,
* stranded" — both leave the invocation in inFlight otherwise.
*/
protected void beforeSendInvocationWrite(String requestId) { }
// Set once an extension reports an init/exit error. Real AWS treats both as fatal to the
// execution environment, so the container must neither accept new work nor be reused.
//
@@ -183,6 +249,18 @@ public class RuntimeApiServer {
return port;
}
/**
* True if at least one extension has completed registration via
* {@code /extension/register}. Callers use this to pick the Shutdown-phase grace tier
* (see AWS's documented 0/500/2000ms limits): a container with a registered extension
* gets the 2s external-extensions budget, otherwise the runtime-only sub-budget.
*/
public boolean hasRegisteredExtensions() {
synchronized (lock) {
return !extensions.isEmpty();
}
}
/**
* True once a registered extension reported an init or exit error. The execution environment
* is condemned: {@code WarmPool} must not return this container to the pool or hand it out
@@ -252,25 +330,46 @@ public class RuntimeApiServer {
// exhaustion when many warm containers poll concurrently.
router.get(NEXT_PATH).handler(ctx -> {
PendingInvocation toDispatch = null;
boolean send204 = false;
boolean faultedNow = false;
synchronized (lock) {
// `faulted` alongside `stopped`: a condemned environment must not be handed work,
// including an invocation that was queued just before the fault was reported.
if (stopped || faulted) {
send204 = true;
if (faulted) {
// Faulted environment: signal the fault so the runtime exits cleanly rather
// than parking forever. Distinct from `stopped` — stopped is a normal
// teardown, faulted means something invariant-breaking happened upstream.
faultedNow = true;
} else if (stopped) {
// Teardown in progress. Park the poll; the container process is being
// SIGTERMed and will exit before the socket closes, matching how real
// AWS Lambda tears an environment down.
waitingContexts.add(ctx);
} else {
toDispatch = pendingQueue.poll();
if (toDispatch == null) {
waitingContexts.add(ctx);
} else {
// Move to inFlight under the same lock so a concurrent quiesce()
// sweep sees it — otherwise the invocation escapes both queues
// and its future is never completed.
inFlight.put(toDispatch.getRequestId(), toDispatch);
}
}
}
if (send204) {
if (faultedNow) {
ctx.response().setStatusCode(204).end();
} else if (toDispatch != null) {
sendInvocation(ctx, toDispatch);
beforeNextPathDispatchGuard();
// Re-check `stopped` under the lock: quiesce() may have run since our
// poll above, in which case it completed toDispatch's future with
// ContainerStopped and dispatching now would silently discard /response.
boolean alreadyHandled;
synchronized (lock) {
alreadyHandled = stopped;
}
if (!alreadyHandled) {
sendInvocation(ctx, toDispatch);
}
}
// else: parked — enqueue() or stop() will dispatch this ctx later.
// else: parked — enqueue() or the httpServer close will dispatch/end this ctx.
});
// POST /runtime/invocation/{requestId}/response — success
@@ -479,22 +578,31 @@ public class RuntimeApiServer {
});
}
public CompletableFuture<Void> stop() {
CompletableFuture<Void> closed;
List<RoutingContext> contextsToClose204;
List<Supplier<Future<Void>>> dispatches = new ArrayList<>();
/**
* Mark the server stopped and settle all bookkeeping, without closing the underlying HTTP
* server. Idempotent — repeated calls are no-ops.
*
* Runtime pollers already parked on {@code /invocation/next} stay parked; the caller is
* expected to shut the container process down (docker stop → SIGTERM) before invoking
* {@link #close()}, so those pollers are terminated by the container exit rather than by
* a server-side response. Extensions parked on {@code /event/next} get a {@code Shutdown}
* event (this is documented AWS behavior for the Extensions API). Pending and in-flight
* invocations are completed with {@code ContainerStopped}.
*
* Call {@link #close()} afterward to release the port.
*/
public void quiesce() {
List<Supplier<Future<Void>>> extensionDispatches = new ArrayList<>();
List<PendingInvocation> invocationsToFailContainerStopped;
List<PendingInvocation> inFlightToFail;
CompletableFuture<Void> writesFuture = new CompletableFuture<>();
synchronized (lock) {
if (closeFuture != null) {
return closeFuture;
if (stopped) {
return;
}
stopped = true;
closed = new CompletableFuture<>();
closeFuture = closed;
contextsToClose204 = new ArrayList<>(waitingContexts);
waitingContexts.clear();
extensionWritesFlushed = writesFuture;
ExtensionEvent shutdownEvent = ExtensionEvent.shutdown(System.currentTimeMillis() + 2000, "SPINDOWN");
for (RegisteredExtension ext : extensions.values()) {
@@ -503,7 +611,7 @@ public class RuntimeApiServer {
}
RoutingContext waitingCtx = ext.takeWaitingContext();
if (waitingCtx != null) {
dispatches.add(() -> {
extensionDispatches.add(() -> {
if (waitingCtx.response().ended()) {
return Future.succeededFuture();
}
@@ -516,6 +624,75 @@ public class RuntimeApiServer {
invocationsToFailContainerStopped = new ArrayList<>(pendingQueue);
pendingQueue.clear();
// Snapshot and clear inFlight inside the lock, atomic with stopped=true.
// The dispatch guards in NEXT_PATH and enqueue()'s deferred callback rely on
// this: once quiesce releases the lock, stopped=true implies inFlight is
// empty, so a guard reading `stopped` cannot deliver an invocation whose
// future quiesce is about to complete with ContainerStopped.
inFlightToFail = new ArrayList<>(inFlight.values());
inFlight.clear();
}
afterQuiesceStoppedFlagSet();
// Extension SHUTDOWN writes go through the event loop; chain on end() rather
// than the scheduled handler's return, because response.end() is async and the
// bytes are not on the wire until its future completes. close() awaits
// extensionWritesFlushed before dropping the httpServer (see #2142).
//
// Runtime pollers stay parked — no 204. They are terminated either by the
// container process exiting on SIGTERM (the ContainerLauncher path, which
// interleaves docker stop between quiesce and close) or by the httpServer
// close itself (the stop() wrapper path); either matches real AWS Lambda's
// teardown better than an undocumented 204 on /invocation/next would.
if (extensionDispatches.isEmpty()) {
writesFuture.complete(null);
} else {
AtomicInteger remainingWrites = new AtomicInteger(extensionDispatches.size());
for (Supplier<Future<Void>> dispatch : extensionDispatches) {
vertx.runOnContext(v -> dispatch.get().onComplete(ar -> {
if (remainingWrites.decrementAndGet() == 0) {
writesFuture.complete(null);
}
}));
}
}
// Fail queued invocations that were never consumed by /next.
for (PendingInvocation pending : invocationsToFailContainerStopped) {
pending.getResultFuture().complete(
new InvokeResult(200, "Unhandled", CONTAINER_STOPPED_PAYLOAD, null, pending.getRequestId()));
}
// Complete any in-flight invocations with error.
for (PendingInvocation inv : inFlightToFail) {
inv.getResultFuture().complete(
new InvokeResult(200, "Unhandled", CONTAINER_STOPPED_PAYLOAD, null, inv.getRequestId()));
}
}
/**
* Close the underlying HTTP server, releasing the bound port. Idempotent — the returned
* future resolves once the server has actually closed (first call) or immediately with
* the same future (subsequent calls). Any parked runtime pollers are terminated by the
* underlying channel closing.
*
* {@link #quiesce()} should be called first so that any registered extensions have the
* chance to receive a Shutdown event before their sockets die.
*/
public CompletableFuture<Void> close() {
CompletableFuture<Void> closed;
CompletableFuture<Void> awaitWrites;
synchronized (lock) {
if (closeFuture != null) {
return closeFuture;
}
closed = new CompletableFuture<>();
closeFuture = closed;
// Await any extension SHUTDOWN writes quiesce() scheduled before closing
// the httpServer, so their responses don't race the socket teardown.
awaitWrites = extensionWritesFlushed != null
? extensionWritesFlushed
: CompletableFuture.completedFuture(null);
}
Runnable closeServer = () -> {
@@ -533,54 +710,21 @@ public class RuntimeApiServer {
closed.complete(null);
}
};
// Wake any parked /next pollers with 204 (container shutting down — runtime will exit) and
// dispatch SHUTDOWN to every extension already parked on /event/next, then close the HTTP
// server. Each write is scheduled on the event loop via vertx.runOnContext(...), and the
// server is closed only once every write's response has actually been flushed — tracked by
// remainingWrites, decremented from each end() future's completion rather than when the
// scheduled handler returns (response.end() is asynchronous, so the bytes are not on the
// wire yet when the handler returns). So a parked extension's SHUTDOWN — or a poller's 204
// — is fully written before its connection is torn down, instead of racing
// httpServer.close() and orphaning the extension with an EOF. See issue #2142.
int parkedWrites = contextsToClose204.size() + dispatches.size();
if (parkedWrites == 0) {
closeServer.run();
} else {
AtomicInteger remainingWrites = new AtomicInteger(parkedWrites);
Runnable afterWrite = () -> {
if (remainingWrites.decrementAndGet() == 0) {
closeServer.run();
}
};
for (RoutingContext ctx : contextsToClose204) {
vertx.runOnContext(v -> {
Future<Void> written = ctx.response().ended()
? Future.succeededFuture()
: ctx.response().setStatusCode(204).end();
written.onComplete(ar -> afterWrite.run());
});
}
for (Supplier<Future<Void>> dispatch : dispatches) {
vertx.runOnContext(v -> dispatch.get().onComplete(ar -> afterWrite.run()));
}
}
// Fail queued invocations that were never consumed by /next.
for (PendingInvocation pending : invocationsToFailContainerStopped) {
pending.getResultFuture().complete(
new InvokeResult(200, "Unhandled", CONTAINER_STOPPED_PAYLOAD, null, pending.getRequestId()));
}
// Complete any in-flight invocations with error.
inFlight.values().forEach(inv ->
inv.getResultFuture().complete(
new InvokeResult(200, "Unhandled", CONTAINER_STOPPED_PAYLOAD, null, inv.getRequestId())));
inFlight.clear();
awaitWrites.whenComplete((v, err) -> closeServer.run());
return closed;
}
/**
* Convenience wrapper: {@link #quiesce()} then {@link #close()} back-to-back, matching the
* pre-split single-step teardown. Callers that need to SIGTERM the container between the
* quiesce and close phases (which is the AWS-faithful teardown) should call the two
* methods directly rather than this wrapper.
*/
public CompletableFuture<Void> stop() {
quiesce();
return close();
}
public CompletableFuture<InvokeResult> enqueue(PendingInvocation invocation) {
boolean rejected;
List<Runnable> dispatches = new ArrayList<>();
@@ -621,6 +765,11 @@ public class RuntimeApiServer {
waitingCtxForInvocation = waitingContexts.poll();
if (waitingCtxForInvocation == null) {
pendingQueue.offer(invocation);
} else {
// Move to inFlight under the same lock so a concurrent quiesce()
// sweep sees it — otherwise the invocation escapes both queues and
// the caller hangs until the function deadline.
inFlight.put(invocation.getRequestId(), invocation);
}
}
}
@@ -638,13 +787,38 @@ public class RuntimeApiServer {
if (waitingCtxForInvocation != null) {
final RoutingContext waitingCtx = waitingCtxForInvocation;
vertx.runOnContext(v -> {
if (!waitingCtx.response().ended()) {
sendInvocation(waitingCtx, invocation);
} else {
// Connection closed between park and dispatch — re-queue.
synchronized (lock) {
pendingQueue.offer(invocation);
beforeEnqueueDeferredDispatch();
// Two things could have changed between enqueue()'s lock release and
// this deferred dispatch reaching the event loop:
// 1. quiesce() may have run — atomic with clearing inFlight and
// completing the caller's future with ContainerStopped. Skip.
// 2. The parked client may have disconnected — the ctx is ended and
// writing to it would fail. Requeue for the next /next poller
// and drop this stale inFlight entry (the next poller will re-put
// the invocation into inFlight under its own lock).
//
// Read waitingCtx.response().ended() ONCE, under the lock, so the
// dispatch/requeue decision is committed atomically. Reading it a
// second time outside the lock (as the code did previously) let a
// disconnect between the two reads produce a stranded inFlight entry:
// the inside-lock read saw !ended → no requeue; the outside-lock read
// saw ended → no send; neither branch fired.
boolean shouldDispatch;
synchronized (lock) {
if (stopped) {
return;
}
if (waitingCtx.response().ended()) {
pendingQueue.offer(invocation);
inFlight.remove(invocation.getRequestId());
shouldDispatch = false;
} else {
shouldDispatch = true;
}
}
afterEnqueueDispatchLockReleased(waitingCtx);
if (shouldDispatch) {
sendInvocation(waitingCtx, invocation);
}
});
}
@@ -677,19 +851,40 @@ public class RuntimeApiServer {
}
private void sendInvocation(RoutingContext ctx, PendingInvocation invocation) {
inFlight.put(invocation.getRequestId(), invocation);
beforeSendInvocationWrite(invocation.getRequestId());
// Invariant: callers put the invocation in inFlight under the lock before
// dispatching, so no inFlight.put here.
byte[] payload = invocation.getPayload();
String body = (payload != null && payload.length > 0)
? new String(payload)
: "{}";
ctx.response()
.setStatusCode(200)
.putHeader("Content-Type", "application/json")
.putHeader("Lambda-Runtime-Aws-Request-Id", invocation.getRequestId())
.putHeader("Lambda-Runtime-Invoked-Function-Arn", invocation.getFunctionArn())
.putHeader("Lambda-Runtime-Deadline-Ms", String.valueOf(invocation.getDeadlineMs()))
.end(body);
// Vert.x reports a client-side disconnect two ways: setStatusCode/putHeader
// throw synchronously if the response is already ended, .end() returns a
// failed Future if the socket dies mid-flush. Funnel both into one handler.
Future<Void> write;
try {
write = ctx.response()
.setStatusCode(200)
.putHeader("Content-Type", "application/json")
.putHeader("Lambda-Runtime-Aws-Request-Id", invocation.getRequestId())
.putHeader("Lambda-Runtime-Invoked-Function-Arn", invocation.getFunctionArn())
.putHeader("Lambda-Runtime-Deadline-Ms", String.valueOf(invocation.getDeadlineMs()))
.end(body);
} catch (IllegalStateException alreadyEnded) {
write = Future.failedFuture(alreadyEnded);
}
write.onFailure(err -> {
// Requeue for the next /next poller; mirrors enqueue()'s ctx-ended branch.
// Skip if quiesce() beat us — it already swept inFlight and settled the
// future with ContainerStopped.
synchronized (lock) {
if (stopped) {
return;
}
pendingQueue.offer(invocation);
inFlight.remove(invocation.getRequestId());
}
});
}
private Future<Void> sendExtensionEvent(RoutingContext ctx, ExtensionEvent event) {