perf(lambda): mount function code from a read-only volume instead of copying per cold start (#1673)

* perf(lambda): mount function code from a read-only volume instead of copying it into every container

Every container launch tar-copied the function's whole /var/task tree into the
container's overlay filesystem. For a function with a large node_modules
(~34k files / 310MB) that small-file copy alone is ~95s on Docker Desktop; run
several at once (an app firing parallel requests at a cold pool) it saturates the
daemon so even `docker create` balloons to ~80s and a burst can take minutes.

Populate the code into a named Docker volume once per code version, then mount that
volume read-only into every container. Mounting is ~0.2s and the volume is shared by
all containers of the function - matching AWS, where /var/task is read-only.

Measured (310MB / 34k-file function): one-time populate ~120s (first launch only);
subsequent cold start ~95s copy -> 0.24s mount; 6 concurrent cold starts ~10 min -> ~1.3s.

Also: gate the whole create->copy->start with a semaphore (not just the copy) so a
cold-pool burst can't pile up half-built "Created" containers; treat a failed docker
inspect in isContainerRunning() as not-running so the warm pool discards dead
containers; enlarge the tar pipe buffer for the remaining small per-container copies.

* fix(lambda): only use code volume for large functions; gate populate not launch; fix stale-volume race and lock leak

Small functions keep the fast direct per-container copy of /var/task and only
large code (>= CODE_VOLUME_MIN_BYTES, default 32 MiB) is served from a shared
read-only volume. This fixes the apigatewayv2-websocket dataplane/tls cold-start
timeout regression: those routes invoke tiny Lambda handlers, and the volume
populate-helper round-trip plus launch serialization pushed the first invoke past
the 5s WS timeout. shouldUseCodeVolume walks the tree short-circuiting once the
running total crosses the threshold, and returns false on IO errors (falls back to
direct copy). The threshold is package-private and non-final so tests can override it.

The launch semaphore now guards ONLY the heavy volume populate (helper create +
tar copy) rather than every launch, so ordinary cold starts (volume mounts and
small-code direct copies) are never serialized (renamed to POPULATE_SEMAPHORE /
acquirePopulatePermit).

P1 (stale-volume race): removed the racy inline deletion of a function's previous
code-version volume. A concurrent in-flight launch could have already resolved the
old volume name and be about to mount it, so deleting it gave that container an
empty /var/task. Stale volumes are labeled floci=true and reclaimed by
`docker volume prune --filter label=floci`. Dropped the codeVolumeByFunction map.

P2 (lock leak): after a successful populate, codeVolumeLocks.remove(volName) is
called so the lock map only ever holds in-flight populates instead of growing
monotonically across redeploys.

* fix(lambda): release the runtime-api port when a launch fails before container create

runtimeApiServerFactory.create() allocates a runtime-api port up front, but the
launch's cleanup try/catch only opened at the container create() call. A failure
between them — most importantly the code-volume populate (ensureCodeVolume), but
also image/host resolve and the spec build — propagated past the catch and leaked
the port. That is exactly the cold-start-burst path this PR targets: when the
Docker daemon rejects the populate helper under load, each failed attempt leaked
one runtime-api port until the pool exhausted and every subsequent launch failed
even after the daemon recovered.

Widen the try to open right after the runtime-api server is allocated and run
through the container-handle build + log-stream attach, so any failure below
releases the port (and reaps any half-built container; containerId stays null when
we fail before create). Add a regression test that a populate failure still
releases the runtime-api server and creates/starts nothing.

Addresses the Greptile P1 (runtimeApiServer port leak) on #1673.

* chore: re-trigger CI (unrelated AutoScalingIntegrationTest.describeAutoScalingGroupsEmpty flake)

* fix(lambda): correct isContainerRunning Javadoc and widen the single-file tar buffer

Correct the isContainerRunning Javadoc, which still described the old return-true-on-error
behaviour and contradicted the implementation (an inspect error now returns false so a
hung/dead container is not reused). Widen copyFileToContainer's pipe buffer to the same
TAR_PIPE_BUFFER_BYTES used by copyDirToContainer (subsumes the separate tar-buffer change).
Resolve a merge with the TLS CA-cert copy from main: containerId is assigned along the
code-volume path and so is no longer effectively final, so its lambda capture becomes an
if-block.
This commit is contained in:
Alex Banna authored and GitHub committed 2026-07-05 10:19:43 -05:00
1 parent 87749e4600
commit 47abda8e9f
4 files changed
+539 -69

No files matched your search

@@ -14,6 +14,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.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.model.Mount;
import com.github.dockerjava.api.model.MountType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -30,6 +32,9 @@ import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
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.eq;
@@ -89,11 +94,13 @@ class ContainerLauncherTest {
when(runtimeApiServer.getPort()).thenReturn(9000);
when(dockerHostResolver.resolve()).thenReturn("127.0.0.1");
when(lifecycleManager.create(any())).thenReturn("container-123");
// lenient: the failure-path test (populate fails before any container is created) never
// reaches these, but every success-path test does — they must not trip strict-stubs.
lenient().when(lifecycleManager.create(any())).thenReturn("container-123");
ContainerLifecycleManager.ContainerInfo info =
new ContainerLifecycleManager.ContainerInfo("container-123", Map.of());
when(lifecycleManager.startCreated(eq("container-123"), any())).thenReturn(info);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
lenient().when(lifecycleManager.startCreated(eq("container-123"), any())).thenReturn(info);
lenient().when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
// Stub the Docker copy chain so copyDirToContainer / copyFileToContainer
// don't throw when the mock DockerClient is used. Each invocation
@@ -123,8 +130,44 @@ class ContainerLauncherTest {
});
}
/**
* Captures every {@link ContainerSpec} passed to {@code lifecycleManager.create(...)} and
* returns the REAL Lambda container's spec.
*
* <p>Small code (below {@link ContainerLauncher#CODE_VOLUME_MIN_BYTES}, the case for these
* tempdir-backed tests) is copied directly into {@code /var/task} on the real container, so
* {@code create} is called exactly once. Large code is instead served from a read-only named
* volume populated by a throwaway helper container (also via {@code create}), so {@code create}
* is called twice: the helper first, then the real container. The real container is the one that
* mounts {@code /var/task} read-only from the volume, so we identify it by that mount when
* present, otherwise fall back to the last (only) {@code create}.
*/
private ContainerSpec captureRealContainerSpec() {
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager, atLeastOnce()).create(specCaptor.capture());
List<ContainerSpec> specs = specCaptor.getAllValues();
// The real container (volume path) mounts /var/task read-only; the helper mounts it read-write.
return specs.stream()
.filter(s -> s.mounts() != null && s.mounts().stream()
.anyMatch(m -> "/var/task".equals(m.getTarget()) && Boolean.TRUE.equals(m.getReadOnly())))
.reduce((first, second) -> second) // last match, defensively
// Fall back to the last create() (the real container) for the direct-copy path.
.orElseGet(() -> specs.get(specs.size() - 1));
}
/** Returns the read-only {@code /var/task} volume mount on the spec, or null if absent. */
private static Mount varTaskVolumeMount(ContainerSpec spec) {
if (spec.mounts() == null) {
return null;
}
return spec.mounts().stream()
.filter(m -> m.getType() == MountType.VOLUME && "/var/task".equals(m.getTarget()))
.findFirst()
.orElse(null);
}
@Test
void launchFunction_createsWithoutBindMounts() throws Exception {
void launchFunction_createsWithoutBindMountsOrVolume_forSmallCode() throws Exception {
Path codePath = Files.createDirectory(tempDir.resolve("code"));
LambdaFunction fn = new LambdaFunction();
@@ -135,11 +178,14 @@ class ContainerLauncherTest {
launcher.launch(fn);
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(specCaptor.capture());
ContainerSpec spec = specCaptor.getValue();
ContainerSpec spec = captureRealContainerSpec();
// Small code is copied directly into /var/task (the fast path), NOT bind-mounted...
assertTrue(spec.binds().isEmpty(), "Function should NOT have bind mounts");
// ...and NOT served from a named volume (that's reserved for large code).
assertNull(varTaskVolumeMount(spec), "small code should NOT mount /var/task from a volume");
// The code is tar-copied straight into /var/task on the real container.
assertTrue(capturedRemotePaths.contains("/var/task"),
"small code should be copied directly into /var/task");
}
@Test
@@ -154,13 +200,24 @@ class ContainerLauncherTest {
launcher.launch(fn);
// Verify ordering: create → getDockerClient → Docker copy (to /var/task) → startCreated
// Small code takes the direct-copy path: the real container is created, its code is
// tar-copied straight into /var/task, and only then is it started. No populate helper.
// create(real) -> copy /var/task (real) -> start(real).
InOrder inOrder = inOrder(lifecycleManager, dockerClient);
inOrder.verify(lifecycleManager).create(any());
inOrder.verify(lifecycleManager).getDockerClient();
inOrder.verify(dockerClient).copyArchiveToContainerCmd("container-123");
inOrder.verify(lifecycleManager).startCreated(eq("container-123"), any());
// The code is copied to /var/task on the real container (no helper populate for small code).
assertTrue(capturedRemotePaths.contains("/var/task"),
"small code should be tar-copied directly to /var/task");
assertEquals(1, capturedRemotePaths.stream().filter("/var/task"::equals).count(),
"/var/task should be copied exactly once (the direct per-container copy)");
// No populate helper is created/discarded for small code.
verify(lifecycleManager, times(1)).create(any());
verify(lifecycleManager, never()).stopAndRemove(any(), any());
// createAndStart must NOT be called — Lambda uses the split path
verify(lifecycleManager, never()).createAndStart(any());
}
@@ -177,10 +234,7 @@ class ContainerLauncherTest {
launcher.launch(fn);
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(specCaptor.capture());
List<String> env = specCaptor.getValue().env();
List<String> env = captureRealContainerSpec().env();
assertTrue(env.stream().anyMatch(e -> e.startsWith("AWS_ACCESS_KEY_ID=")),
"AWS_ACCESS_KEY_ID should be injected when awsConfigPath is absent");
assertTrue(env.stream().anyMatch(e -> e.startsWith("AWS_SECRET_ACCESS_KEY=")),
@@ -204,10 +258,7 @@ class ContainerLauncherTest {
launcher.launch(fn);
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(specCaptor.capture());
List<String> env = specCaptor.getValue().env();
List<String> env = captureRealContainerSpec().env();
String accessKey = env.stream().filter(e -> e.startsWith("AWS_ACCESS_KEY_ID=")).findFirst().orElse("");
String secretKey = env.stream().filter(e -> e.startsWith("AWS_SECRET_ACCESS_KEY=")).findFirst().orElse("");
String sessionToken = env.stream().filter(e -> e.startsWith("AWS_SESSION_TOKEN=")).findFirst().orElse("");
@@ -235,10 +286,7 @@ class ContainerLauncherTest {
launcher.launch(fn);
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(specCaptor.capture());
List<String> env = specCaptor.getValue().env();
List<String> env = captureRealContainerSpec().env();
assertTrue(env.contains("AWS_DEFAULT_REGION=eu-central-1"));
assertTrue(env.contains("AWS_REGION=eu-central-1"));
}
@@ -256,10 +304,7 @@ class ContainerLauncherTest {
launcher.launch(fn);
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(specCaptor.capture());
List<String> env = specCaptor.getValue().env();
List<String> env = captureRealContainerSpec().env();
assertTrue(env.contains("AWS_DEFAULT_REGION=eu-west-2"));
assertTrue(env.contains("AWS_REGION=eu-west-2"));
verify(logStreamer).attach(
@@ -281,10 +326,7 @@ class ContainerLauncherTest {
launcher.launch(fn);
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(specCaptor.capture());
List<String> env = specCaptor.getValue().env();
List<String> env = captureRealContainerSpec().env();
// Docker honours the last occurrence of a duplicate Env entry, so user
// overrides must appear after the Floci defaults.
int defaultKeyIdx = -1;
@@ -325,12 +367,11 @@ class ContainerLauncherTest {
launcher.launch(fn);
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(specCaptor.capture());
ContainerSpec spec = captureRealContainerSpec();
verify(ecrRegistryManager).ensureStarted();
verify(ecrRegistryManager).getRepositoryUri("123456789012", "us-east-1", "backend-user:1");
assertEquals("123456789012.dkr.ecr.us-east-1.localhost:5100/backend-user:1",
specCaptor.getValue().image());
spec.image());
}
@Test
@@ -345,12 +386,11 @@ class ContainerLauncherTest {
launcher.launch(fn);
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(specCaptor.capture());
ContainerSpec spec = captureRealContainerSpec();
verify(ecrRegistryManager).ensureStarted();
verify(ecrRegistryManager).getRepositoryUri("123456789012", "us-east-1", "backend-user:1");
assertEquals("localhost:5100/123456789012/us-east-1/backend-user:1",
specCaptor.getValue().image());
spec.image());
}
@Test
@@ -366,21 +406,28 @@ class ContainerLauncherTest {
launcher.launch(fn);
// The critical invariant: create must happen before any Docker copy,
// and start must happen after. This is the exact regression from #466.
// The critical invariant preserved from #466: the REAL container must be created before its
// code and bootstrap are copied, and started only after. Small code takes the direct-copy
// path, so everything happens on the one real container (no populate helper).
//
// Ordering:
// real: create -> copy /var/task + copy bootstrap to /var/runtime -> start
// (two copyArchiveToContainerCmd calls on the real container: code, then bootstrap).
InOrder inOrder = inOrder(lifecycleManager, dockerClient);
inOrder.verify(lifecycleManager).create(any());
inOrder.verify(lifecycleManager).getDockerClient();
// Two copies: code to /var/task + bootstrap to /var/runtime
inOrder.verify(dockerClient, times(2)).copyArchiveToContainerCmd("container-123");
inOrder.verify(dockerClient, atLeastOnce()).copyArchiveToContainerCmd("container-123");
inOrder.verify(lifecycleManager).startCreated(eq("container-123"), any());
// Verify both /var/task and /var/runtime were targeted
// Small code is copied directly to /var/task; bootstrap is copied to /var/runtime — both on
// the one real container.
assertTrue(capturedRemotePaths.contains("/var/task"),
"code should be copied to /var/task");
"small code should be tar-copied directly to /var/task");
assertTrue(capturedRemotePaths.contains("/var/runtime"),
"bootstrap should be copied to /var/runtime");
"bootstrap should be copied to /var/runtime on the real container");
// No populate helper for small code.
verify(lifecycleManager, times(1)).create(any());
verify(lifecycleManager, never()).stopAndRemove(any(), any());
verify(lifecycleManager, never()).createAndStart(any());
}
@@ -399,10 +446,7 @@ class ContainerLauncherTest {
launcher.launch(fn);
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(specCaptor.capture());
ContainerSpec spec = specCaptor.getValue();
ContainerSpec spec = captureRealContainerSpec();
// Should bind-mount to /opt/aws-config (read-only)
assertTrue(spec.binds().stream()
@@ -439,11 +483,84 @@ class ContainerLauncherTest {
launcher.launch(fn);
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(specCaptor.capture());
assertTrue(specCaptor.getValue().binds().stream()
assertTrue(captureRealContainerSpec().binds().stream()
.noneMatch(b -> b.getVolume().getPath().equals("/opt/aws-config")),
"no .aws bind mount when awsConfigPath is absent");
}
@Test
void launchFunction_usesReadOnlyVolume_forLargeCode() throws Exception {
Path codePath = Files.createDirectory(tempDir.resolve("large-code"));
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]); // 8 KiB
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("large-fn");
fn.setRuntime("nodejs20.x");
fn.setHandler("index.handler");
fn.setCodeLocalPath(codePath.toString());
fn.setCodeSha256("large-fn-sha-v1");
long original = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
try {
// Force the volume path without writing a 32 MiB file.
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024; // 4 KiB
launcher.launch(fn);
} finally {
ContainerLauncher.CODE_VOLUME_MIN_BYTES = original;
}
ContainerSpec spec = captureRealContainerSpec();
// The real container mounts /var/task read-only from the code volume...
Mount codeMount = varTaskVolumeMount(spec);
assertNotNull(codeMount, "large code: /var/task should be a named-volume mount");
assertEquals(MountType.VOLUME, codeMount.getType(), "/var/task should be a volume mount");
assertTrue(Boolean.TRUE.equals(codeMount.getReadOnly()), "/var/task volume should be read-only");
assertTrue(spec.binds().isEmpty(), "large code: real container should have NO bind mounts");
// ...and /var/task is populated ONCE via a helper container (create -> start -> copy ->
// stopAndRemove), not copied onto the real container. The volume is populated exactly once.
assertEquals(1, capturedRemotePaths.stream().filter("/var/task"::equals).count(),
"/var/task should be copied exactly once (into the populate helper)");
// Two creates: the helper + the real container. The helper is discarded.
verify(lifecycleManager, times(2)).create(any());
verify(lifecycleManager, atLeastOnce()).ensureVolume(any());
verify(lifecycleManager, times(1)).stopAndRemove(any(), any()); // the helper only
// Old code-version volumes are NOT eagerly deleted (race fix); they are label-pruned instead.
verify(lifecycleManager, never()).removeVolume(any());
}
@Test
void launchFunction_releasesRuntimeApiServer_whenCodeVolumePopulateFails() throws Exception {
// Regression for the runtime-api port leak: the volume path allocates a runtime-api server
// up front (before the code-volume populate). If the populate then fails — the exact
// cold-start-burst scenario this PR targets, where the Docker daemon rejects the helper work
// under load — the launch must STILL release that port. Otherwise every failed attempt leaks
// one port and the pool eventually exhausts, so launches keep failing after the daemon recovers.
Path codePath = Files.createDirectory(tempDir.resolve("leak-code"));
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]); // 8 KiB
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("leak-fn");
fn.setRuntime("nodejs20.x");
fn.setHandler("index.handler");
fn.setCodeLocalPath(codePath.toString());
fn.setCodeSha256("leak-fn-sha-v1");
// The code-volume populate fails (daemon under load), before any container is created.
doThrow(new RuntimeException("docker daemon busy")).when(lifecycleManager).ensureVolume(any());
long original = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
try {
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024; // force the volume path without a 32 MiB file
assertThrows(RuntimeException.class, () -> launcher.launch(fn));
} finally {
ContainerLauncher.CODE_VOLUME_MIN_BYTES = original;
}
// The runtime-api port allocated before the populate is released on this failure path...
verify(runtimeApiServerFactory).release(runtimeApiServer);
// ...and we bailed before creating or starting any container (nothing to reap).
verify(lifecycleManager, never()).create(any());
verify(lifecycleManager, never()).startCreated(any(), any());
}
}
@@ -0,0 +1,133 @@
package io.github.hectorvent.floci.services.lambda.launcher;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit tests for {@link ContainerLauncher#codeVolumeName(LambdaFunction)}, the naming logic for
* the per-function-version code volume. The name must be stable for a given code version (so all
* of a function's containers share one volume), distinct across code versions (so a redeploy gets
* a fresh volume), and always a legal Docker volume name.
*
* <p>Kept separate from {@link ContainerLauncherTest} because these are pure static-method tests
* that need none of that test's Mockito mocks; mixing them in would trip strict-stubbing.
*/
class ContainerLauncherVolumeNamingTest {
/** The pattern Docker requires a volume name to match. */
private static final Pattern DOCKER_VOLUME_NAME = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9_.-]*$");
private static LambdaFunction fnWithSha(String name, String sha) {
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName(name);
fn.setCodeSha256(sha);
return fn;
}
@Test
void isFlociCodeShapedAndDockerSafe() {
String name = ContainerLauncher.codeVolumeName(
fnWithSha("my-fn", "AbC123+/xyz=deadbeefcafebabe0123456789"));
assertTrue(name.startsWith("floci-code-my-fn-"),
"should be floci-code-<functionName>-<hash> shaped, was: " + name);
assertTrue(DOCKER_VOLUME_NAME.matcher(name).matches(),
"must be a docker-volume-safe name, was: " + name);
}
@Test
void sanitizesUnsafeFunctionNameChars() {
// Real function names are constrained, but be defensive: any unsafe char must not leak
// into the volume name (which would make `docker volume create` reject it).
String name = ContainerLauncher.codeVolumeName(fnWithSha("weird name/v2:1", "abc123"));
assertTrue(DOCKER_VOLUME_NAME.matcher(name).matches(),
"unsafe function-name chars must be sanitized, was: " + name);
}
@Test
void differsAcrossCodeVersions() {
String v1 = ContainerLauncher.codeVolumeName(fnWithSha("same-fn", "sha-version-one"));
String v2 = ContainerLauncher.codeVolumeName(fnWithSha("same-fn", "sha-version-two"));
assertNotEquals(v1, v2,
"different codeSha256 must yield different volume names so a redeploy gets a fresh volume");
}
@Test
void isStableForSameFunctionAndSha() {
String a = ContainerLauncher.codeVolumeName(fnWithSha("stable-fn", "stable-sha-abc"));
String b = ContainerLauncher.codeVolumeName(fnWithSha("stable-fn", "stable-sha-abc"));
assertEquals(a, b, "same function + same sha must produce a stable volume name");
}
@Test
void fallsBackToLastModifiedWhenShaMissing() {
LambdaFunction nullSha = new LambdaFunction();
nullSha.setFunctionName("no-sha-fn");
nullSha.setCodeSha256(null);
nullSha.setLastModified(1700000000000L);
LambdaFunction blankSha = new LambdaFunction();
blankSha.setFunctionName("no-sha-fn");
blankSha.setCodeSha256(" ");
blankSha.setLastModified(1700000000000L);
String nullName = ContainerLauncher.codeVolumeName(nullSha);
String blankName = ContainerLauncher.codeVolumeName(blankSha);
assertTrue(DOCKER_VOLUME_NAME.matcher(nullName).matches(),
"must be docker-safe even when falling back to lastModified, was: " + nullName);
assertTrue(nullName.contains("1700000000000"),
"null sha should key off lastModified, was: " + nullName);
assertEquals(nullName, blankName, "null and blank sha should both fall back to lastModified");
// A different lastModified (new deploy) must yield a different name.
LambdaFunction newer = new LambdaFunction();
newer.setFunctionName("no-sha-fn");
newer.setLastModified(1700000009999L);
assertNotEquals(nullName, ContainerLauncher.codeVolumeName(newer),
"a later lastModified must produce a different volume name");
}
@TempDir
Path tempDir;
@Test
void shouldUseCodeVolume_falseForSmallDir_trueWhenOverThreshold() throws Exception {
Path smallDir = Files.createDirectory(tempDir.resolve("small"));
Files.write(smallDir.resolve("a.txt"), new byte[1024]); // 1 KiB
Path bigDir = Files.createDirectory(tempDir.resolve("big"));
Files.write(bigDir.resolve("a.bin"), new byte[8 * 1024]); // 8 KiB
long original = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
try {
// Override the threshold small so we don't have to write huge files.
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024; // 4 KiB
assertFalse(ContainerLauncher.shouldUseCodeVolume(smallDir),
"1 KiB dir is below the 4 KiB threshold");
assertTrue(ContainerLauncher.shouldUseCodeVolume(bigDir),
"8 KiB dir exceeds the 4 KiB threshold");
} finally {
ContainerLauncher.CODE_VOLUME_MIN_BYTES = original;
}
}
@Test
void shouldUseCodeVolume_falseWhenDirMissing() {
// IO errors (e.g. a non-existent dir) fall back to the direct copy.
assertFalse(ContainerLauncher.shouldUseCodeVolume(tempDir.resolve("does-not-exist")),
"a missing code dir should fall back to direct copy (false)");
}
}