feat(lambda): initialize provisioned concurrency environments (#6320)

Initialize and route qualifier-owned provisioned environments without invoking handlers during initialization. Keep configuration outcomes committed while failed removal remains owned for retry, and bound cleanup after late invocation release. Preserve on-demand spillover and the separate alias-retargeting stage.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-23 06:35:02 -04:00
1 parent f60cf120c6
commit 238d16e541
15 files changed
+2061 -248

No files matched your search

@@ -464,7 +464,7 @@ class SamTransformIntegrationTest {
}
@Test
void samAutoPublishAliasKeepsPublishedConfiguration() {
void samAutoPublishAliasKeepsPublishedConfigurationAndQualifiesForProvisionedConcurrency() {
String stackName = "sam-published-config-stack";
String function = "sam-published-config-func";
stacksToDelete.add(stackName);
@@ -503,6 +503,12 @@ class SamTransformIntegrationTest {
.when().get("/2015-03-31/functions/" + function + "/configuration")
.then().statusCode(200).body("Version", equalTo("1"))
.body("MemorySize", equalTo(128)).body("Environment.Variables.MARKER", equalTo("original"));
// No allocation exists, but the generated alias is an eligible immutable target.
given().queryParam("Qualifier", "production")
.when().get("/2019-09-30/functions/" + function + "/provisioned-concurrency")
.then().statusCode(404)
.body("__type", equalTo("ProvisionedConcurrencyConfigNotFoundException"));
}
@Test
@@ -29,6 +29,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.Awaitility.await;
@@ -38,6 +39,7 @@ import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
@@ -61,11 +63,11 @@ class WarmPoolTest {
}
private WarmPool buildPool(Optional<Integer> maxPerFunction, int maxTotal) {
return buildPool(maxPerFunction, maxTotal, 15);
return buildPool(maxPerFunction, maxTotal, null, 15);
}
private WarmPool buildPool(Optional<Integer> maxPerFunction, int maxTotal,
int drainSeconds) {
ProvisionedConcurrencyPool provisioned, int drainSeconds) {
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
when(config.services()).thenReturn(services);
@@ -75,7 +77,7 @@ class WarmPoolTest {
when(lambda.warmPoolMaxPerFunction()).thenReturn(maxPerFunction);
when(lambda.warmPoolMaxTotal()).thenReturn(maxTotal);
when(lambda.containerDrainTimeoutSeconds()).thenReturn(drainSeconds);
return new WarmPool(containerLauncher, config, clock);
return new WarmPool(containerLauncher, config, clock, provisioned);
}
private static LambdaFunction function(String name) {
@@ -189,7 +191,7 @@ class WarmPoolTest {
@Test
void shutdownDeadlineCancelsConcurrentRemovalsAndResetRetainsThemForRetry() throws Exception {
WarmPool pool = buildPool(Optional.empty(), 0, 1);
WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
ContainerHandle first = new ContainerHandle("first", "first", null, ContainerState.WARM);
ContainerHandle second = new ContainerHandle("second", "second", null, ContainerState.WARM);
when(containerLauncher.launch(any())).thenReturn(first, second);
@@ -238,7 +240,7 @@ class WarmPoolTest {
@Test
void releaseAfterShutdownDeadlineRetriesFailedRemoval() throws Exception {
WarmPool pool = buildPool(Optional.empty(), 0, 1);
WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
LambdaFunction fn = function("late-release");
ContainerHandle busy = new ContainerHandle("busy", "late-release", null, ContainerState.WARM);
ContainerHandle slow = new ContainerHandle("slow", "late-release", null, ContainerState.WARM);
@@ -303,7 +305,7 @@ class WarmPoolTest {
@Test
void functionDrainUsesConfiguredBudgetAndMaintenanceRetriesCanceledRemoval() throws Exception {
WarmPool pool = buildPool(Optional.empty(), 0, 1);
WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
ContainerHandle handle = new ContainerHandle("bounded-drain", "bounded", null, ContainerState.WARM);
when(containerLauncher.launch(any())).thenReturn(handle);
AtomicInteger attempts = new AtomicInteger();
@@ -338,6 +340,68 @@ class WarmPoolTest {
verify(containerLauncher, times(2)).stop(handle);
}
@Test
void bothPoolsUseOneConfiguredDeadlineAndCanceledRemovalRemainsRetryable() throws Exception {
ProvisionedConcurrencyPool provisioned = mock(ProvisionedConcurrencyPool.class);
WarmPool pool = buildPool(Optional.empty(), 0, provisioned, 1);
pool.init();
ContainerHandle handle = new ContainerHandle("cid-canceled", "cancel-fn", null, ContainerState.WARM);
when(containerLauncher.launch(any())).thenReturn(handle);
LambdaFunction fn = function("cancel-fn");
pool.release(pool.acquire(fn));
CountDownLatch bothStarted = new CountDownLatch(2);
CountDownLatch bothInterrupted = new CountDownLatch(2);
CountDownLatch release = new CountDownLatch(1);
AtomicLong provisionedDeadline = new AtomicLong();
doAnswer(invocation -> {
provisionedDeadline.set(invocation.getArgument(0));
bothStarted.countDown();
try {
release.await();
} catch (InterruptedException interrupted) {
bothInterrupted.countDown();
Thread.currentThread().interrupt();
}
return null;
}).when(provisioned).stopManagedContainers(anyLong());
doAnswer(invocation -> {
bothStarted.countDown();
try {
release.await();
} catch (InterruptedException interrupted) {
bothInterrupted.countDown();
Thread.currentThread().interrupt();
throw new IllegalStateException(interrupted);
}
return null;
}).when(containerLauncher).stop(handle);
ExecutorService executor = Executors.newSingleThreadExecutor();
long before = System.nanoTime();
Future<?> drain = executor.submit(pool::stopManagedContainers);
try {
assertTrue(bothStarted.await(3, TimeUnit.SECONDS),
"Both pools must start draining before either pool finishes");
drain.get(5, TimeUnit.SECONDS);
assertTrue(bothInterrupted.await(3, TimeUnit.SECONDS));
assertTrue(provisionedDeadline.get() >= before + TimeUnit.SECONDS.toNanos(1));
assertTrue(provisionedDeadline.get() <= System.nanoTime());
assertThrows(RuntimeException.class, () -> pool.acquire(fn));
pool.shutdown();
verify(containerLauncher, times(1)).stop(handle);
verify(provisioned, times(1)).stopManagedContainers(anyLong());
pool.afterReset();
doNothing().when(containerLauncher).stop(handle);
pool.drainFunction("cancel-fn");
pool.drainFunction("cancel-fn");
verify(containerLauncher, times(2)).stop(handle);
} finally {
release.countDown();
executor.shutdownNow();
pool.shutdown();
}
}
@Test
void warmHandleRemovedDuringLivenessProbeIsNotOwnedAgain() throws Exception {
WarmPool pool = buildPool();
@@ -373,7 +437,7 @@ class WarmPoolTest {
@Test
void knownWarmHandleStopsWhileColdLaunchRemainsBlocked() throws Exception {
WarmPool pool = buildPool(Optional.empty(), 0, 1);
WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
pool.init();
ContainerHandle warm = new ContainerHandle("cid-known", "known-fn", null, ContainerState.WARM);
ContainerHandle late = new ContainerHandle("cid-blocked", "blocked-fn", null, ContainerState.WARM);
@@ -415,7 +479,7 @@ class WarmPoolTest {
@Test
void oldColdLaunchCannotAcquireAfterResetReopensPool() throws Exception {
WarmPool pool = buildPool(Optional.empty(), 0, 1);
WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
pool.init();
LambdaFunction fn = function("reset-fn");
ContainerHandle old = new ContainerHandle("cid-old-launch", "reset-fn", null, ContainerState.WARM);
@@ -494,7 +558,7 @@ class WarmPoolTest {
@Test
void launchBeyondShutdownDeadlineIsRefusedAndStopped() throws Exception {
WarmPool pool = buildPool(Optional.empty(), 0, 1);
WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
pool.init();
LambdaFunction fn = function("late-fn");
ContainerHandle handle = new ContainerHandle("cid-late", "late-fn", null, ContainerState.WARM);
@@ -89,6 +89,7 @@ class ContainerLauncherTest {
@Mock RuntimeApiServer runtimeApiServer;
@Mock DockerClient dockerClient;
@Mock LambdaExecutionRoleCredentials executionRoleCredentials;
@Mock LambdaLayerService layerService;
@TempDir
Path tempDir;
@@ -144,7 +145,7 @@ class ContainerLauncherTest {
LaunchedContainerAwsEnv awsEnv = new LaunchedContainerAwsEnv(reachableEndpoint);
launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver,
runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager,
mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class), awsEnv,
layerService, awsEnv,
executionRoleCredentials);
when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer);
@@ -661,6 +662,16 @@ class ContainerLauncherTest {
verify(lifecycleManager, never()).createAndStart(any());
}
private static LambdaFunction imageFunction() {
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("image-function");
fn.setAccountId("222233334444");
fn.setFunctionArn("arn:aws:lambda:us-east-1:222233334444:function:image-function");
fn.setPackageType("Image");
fn.setImageUri("unit-lambda:latest");
return fn;
}
@Test
void launchFunction_injectsDefaultAwsCredentials() throws Exception {
Path codePath = Files.createDirectory(tempDir.resolve("creds-defaults"));
@@ -682,6 +693,120 @@ class ContainerLauncherTest {
"AWS_SESSION_TOKEN should be injected when awsConfigPath is absent");
}
@ParameterizedTest
@ValueSource(strings = {"$LATEST", "1", "7"})
void onDemandLaunchUsesTheSelectedVersion(String version) {
LambdaFunction fn = imageFunction();
fn.setVersion(version);
fn.setEnvironment(Map.of("AWS_LAMBDA_FUNCTION_VERSION", "user-override"));
launcher.launch(fn);
assertEquals(List.of("AWS_LAMBDA_FUNCTION_VERSION=" + version),
captureRealContainerSpec().env().stream()
.filter(value -> value.startsWith("AWS_LAMBDA_FUNCTION_VERSION=")).toList());
}
@Test
void provisionedLaunchUsesTheImmutableVersionAndPlatformInitializationType() throws Exception {
stubExtensionDiscovery("example-extension");
when(logStreamer.execLogCallbackForAccount(anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(new ResultCallback.Adapter<>());
LambdaFunction fn = imageFunction();
fn.setVersion("7");
fn.setEnvironment(Map.of("AWS_LAMBDA_INITIALIZATION_TYPE", "on-demand",
"AWS_LAMBDA_FUNCTION_VERSION", "$LATEST"));
launcher.launchProvisioned(fn);
List<String> env = captureRealContainerSpec().env();
assertEquals(List.of("AWS_LAMBDA_FUNCTION_VERSION=7"),
env.stream().filter(value -> value.startsWith("AWS_LAMBDA_FUNCTION_VERSION=")).toList());
assertEquals(List.of("AWS_LAMBDA_INITIALIZATION_TYPE=provisioned-concurrency"),
env.stream().filter(value -> value.startsWith("AWS_LAMBDA_INITIALIZATION_TYPE=")).toList());
verify(runtimeApiServer).expectExtensions(1);
verify(runtimeApiServer, never()).awaitExtensionsReady(anyLong());
verify(runtimeApiServer, never()).enqueue(any());
}
@Test
void provisionedLaunchRefusesFailedExtensionDiscoveryAndCleansTheCreatedRuntime() {
LambdaFunction fn = imageFunction();
fn.setVersion("1");
CopyArchiveFromContainerCmd archive = mock(CopyArchiveFromContainerCmd.class);
when(dockerClient.copyArchiveFromContainerCmd("container-123", "/opt/extensions")).thenReturn(archive);
when(archive.exec()).thenThrow(new IllegalStateException("controlled archive failure"));
assertThrows(RuntimeException.class, () -> launcher.launchProvisioned(fn));
verify(runtimeApiServerFactory).release(runtimeApiServer);
verify(runtimeApiServer, never()).expectExtensions(0);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void provisionedLaunchCopiesTheStoredAccountsLayerWithoutAmbientLookup(boolean legacyAccount) throws Exception {
LambdaFunction fn = imageFunction();
fn.setAccountId(legacyAccount ? null : "123456789012");
fn.setFunctionArn("arn:aws:lambda:eu-west-1:123456789012:function:layer-function");
fn.setVersion("1");
String arn = "arn:aws:lambda:eu-west-1:123456789012:layer:owned:1";
fn.setLayers(List.of(arn));
Path layerPath = Files.createDirectory(tempDir.resolve("owned-layer"));
Files.writeString(layerPath.resolve("dependency.txt"), "owned");
LambdaLayerVersion layer = new LambdaLayerVersion();
layer.setCodeLocalPath(layerPath.toString());
when(layerService.resolveLayerByArnForAccount(arn, "123456789012", "eu-west-1")).thenReturn(layer);
stubExtensionDiscovery();
launcher.launchProvisioned(fn);
assertTrue(capturedRemotePaths.contains("/opt"));
verify(layerService, never()).resolveLayerByArn(anyString());
verify(lifecycleManager).startCreated(eq("container-123"), any());
verify(runtimeApiServer).expectExtensions(0);
}
@ParameterizedTest
@MethodSource("unavailableLayerPaths")
void provisionedLaunchRefusesMissingLayerInputsAndCleansBeforeStart(String pathKind) throws Exception {
LambdaFunction fn = imageFunction();
fn.setAccountId("123456789012");
fn.setFunctionArn("arn:aws:lambda:us-east-1:123456789012:function:missing-layer");
fn.setVersion("1");
String arn = "arn:aws:lambda:us-east-1:123456789012:layer:missing:1";
fn.setLayers(List.of(arn));
if (!"unresolved".equals(pathKind)) {
LambdaLayerVersion layer = new LambdaLayerVersion();
if ("absent".equals(pathKind)) {
layer.setCodeLocalPath(tempDir.resolve("absent").toString());
} else if ("regular-file".equals(pathKind)) {
layer.setCodeLocalPath(Files.writeString(tempDir.resolve("not-a-directory"), "data").toString());
}
when(layerService.resolveLayerByArnForAccount(eq(arn), eq("123456789012"), anyString()))
.thenReturn(layer);
}
IllegalStateException error = assertThrows(IllegalStateException.class,
() -> launcher.launchProvisioned(fn));
assertTrue(error.getMessage().startsWith("Configured layer is unavailable for provisioned initialization:"));
verify(lifecycleManager, never()).startCreated(anyString(), any());
verify(lifecycleManager).stopAndRemove("container-123", null);
verify(runtimeApiServerFactory).release(runtimeApiServer);
verify(runtimeApiServer, never()).expectExtensions(anyInt());
verify(runtimeApiServer, never()).enqueue(any());
}
private static Stream<String> unavailableLayerPaths() {
return Stream.of("unresolved", "null-path", "absent", "regular-file");
}
@Test
void ordinaryLaunchRetainsItsUnresolvedLayerBehavior() {
LambdaFunction fn = imageFunction();
String arn = "arn:aws:lambda:us-east-1:123456789012:layer:missing:1";
fn.setLayers(List.of(arn));
launcher.launch(fn);
verify(layerService).resolveLayerByArnForAccount(arn, "222233334444", "us-east-1");
verify(layerService, never()).resolveLayerByArn(anyString());
verify(lifecycleManager).startCreated(eq("container-123"), any());
}
@Test
void launchFunction_injectsOwningAccountAsAccessKeyAndFallsBackForTheRest() throws Exception {
// The access key identifies the container's owning account to AccountResolver, so it is
@@ -0,0 +1,140 @@
package io.github.hectorvent.floci.services.lambda.runtime;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
@Timeout(15)
class RuntimeInitializationTest {
private Vertx vertx;
private RuntimeApiServer server;
private HttpClient client;
private String base;
@BeforeEach
void setUp() throws Exception {
vertx = Vertx.vertx();
int port;
try (ServerSocket socket = new ServerSocket(0)) {
port = socket.getLocalPort();
}
base = "http://127.0.0.1:" + port;
server = new RuntimeApiServer(vertx, port);
server.start().get(5, TimeUnit.SECONDS);
client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
}
@AfterEach
void tearDown() throws Exception {
server.stop().get(5, TimeUnit.SECONDS);
client.shutdownNow();
vertx.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
}
private CompletableFuture<HttpResponse<String>> next() {
return client.sendAsync(HttpRequest.newBuilder(URI.create(base + "/2018-06-01/runtime/invocation/next"))
.GET().build(), HttpResponse.BodyHandlers.ofString());
}
private String register(String name) throws Exception {
HttpResponse<String> response = client.send(
HttpRequest.newBuilder(URI.create(base + "/2020-01-01/extension/register"))
.header("Lambda-Extension-Name", name).header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"events\":[\"INVOKE\",\"SHUTDOWN\"]}")).build(),
HttpResponse.BodyHandlers.ofString());
assertEquals(200, response.statusCode());
return response.headers().firstValue("Lambda-Extension-Identifier").orElseThrow();
}
private CompletableFuture<HttpResponse<String>> extensionNext(String id) {
return client.sendAsync(HttpRequest.newBuilder(URI.create(base + "/2020-01-01/extension/event/next"))
.header("Lambda-Extension-Identifier", id).GET().build(), HttpResponse.BodyHandlers.ofString());
}
@Test
void initializationNeedsRuntimeNextAndDoesNotProduceAnInvocation() throws Exception {
server.expectExtensions(0);
assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
CompletableFuture<HttpResponse<String>> pending = next();
server.awaitInitialization(2000);
assertTrue(server.isInitialized());
assertFalse(pending.isDone(), "No handler event was enqueued by initialization");
}
@Test
void runtimeNextBeforeExtensionDiscoveryCannotCompleteInitialization() throws Exception {
CompletableFuture<HttpResponse<String>> pending = next();
await().atMost(Duration.ofSeconds(2)).until(() -> server.waitingContextsSize() == 1);
assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
server.expectExtensions(1);
String extension = register("example-extension");
assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
extensionNext(extension);
server.awaitInitialization(2000);
assertFalse(pending.isDone());
}
@Test
void everyExtensionAndTheRuntimeMustFinishInit() throws Exception {
server.expectExtensions(2);
String first = register("first-extension");
String second = register("second-extension");
extensionNext(first);
assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
CompletableFuture<HttpResponse<String>> pending = next();
assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
extensionNext(second);
server.awaitInitialization(2000);
assertFalse(pending.isDone());
}
@Test
void initErrorFailsTheBarrierWithoutAnInvocation() throws Exception {
server.expectExtensions(0);
HttpResponse<String> response = client.send(
HttpRequest.newBuilder(URI.create(base + "/2018-06-01/runtime/init/error"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
new JsonObject().put("errorMessage", "controlled import failure").encode())).build(),
HttpResponse.BodyHandlers.ofString());
assertEquals(202, response.statusCode());
assertThrows(ExecutionException.class, () -> server.awaitInitialization(100));
assertFalse(server.isInitialized());
}
@Test
void processExitFailsTheBarrierAndCannotBeMadeReadyByALateNext() throws Exception {
server.expectExtensions(0);
server.handleRuntimeProcessExited(1);
assertThrows(ExecutionException.class, () -> server.awaitInitialization(100));
assertEquals(204, next().get(2, TimeUnit.SECONDS).statusCode());
assertFalse(server.isInitialized());
}
@Test
void stopInvalidatesCompletedReadiness() throws Exception {
server.expectExtensions(0);
next();
server.awaitInitialization(2000);
server.quiesce();
assertFalse(server.isInitialized());
assertThrows(IllegalStateException.class, () -> server.awaitInitialization(100));
}
}