Light, fluffy, and always free - The AWS Local Emulator alternative
feat(lambda): bound the warm pool globally with LRU eviction (#4683)
danielxoi73b8c6124c1e
diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.mdindex dceddea543..4d84797df1 100644--- a/docs/configuration/advanced/application-yml.md+++ b/docs/configuration/advanced/application-yml.md@@ -165,6 +165,8 @@ floci:poll-interval-ms: 1000async-retry-delay-seconds: 60 # Wait before the first retry of a failed Event invocation; the second waits twice thiscontainer-idle-timeout-seconds: 300 # Remove idle containers after this+ # warm-pool-max-per-function: # Idle containers kept per function (default max(4, cpus))+ warm-pool-max-total: 0 # Idle containers kept across all functions; 0 = unboundedregion-concurrency-limit: 1000 # Concurrent executions ceiling per regionunreserved-concurrency-min: 100 # Minimum unreserved capacity PutFunctionConcurrency must leavehot-reload:diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.mdindex f126cb25cf..fe6975f581 100644--- a/docs/configuration/environment-variables.md+++ b/docs/configuration/environment-variables.md@@ -246,6 +246,8 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s| `FLOCI_SERVICES_LAMBDA_POLL_INTERVAL_MS` | `1000` | How often (ms) the SQS and Kinesis event source pollers check for new messages || `FLOCI_SERVICES_LAMBDA_ASYNC_RETRY_DELAY_SECONDS` | `60` | Wait before the first retry of a failed asynchronous invocation (seconds); the second waits twice this, `0` retries back to back || `FLOCI_SERVICES_LAMBDA_CONTAINER_IDLE_TIMEOUT_SECONDS` | `300` | Seconds of inactivity before an idle Lambda container is removed |+| `FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_PER_FUNCTION` | `max(4, cpus)` | Maximum idle (warm) containers kept per function; a container released beyond this is stopped |+| `FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_TOTAL` | `0` | Maximum idle (warm) containers kept across all functions. Beyond it, the least-recently-used idle container of any function is stopped to make room for the one just released. `0` leaves the total unbounded; a negative value is ignored with a warning. See [Bounding warm containers](../services/lambda.md#bounding-warm-containers) || `FLOCI_SERVICES_LAMBDA_REGION_CONCURRENCY_LIMIT` | `1000` | Maximum concurrent Lambda invocations across all functions in a region || `FLOCI_SERVICES_LAMBDA_UNRESERVED_CONCURRENCY_MIN` | `100` | Minimum unreserved concurrency pool || `FLOCI_SERVICES_LAMBDA_CODE_VOLUME_POPULATE_CONCURRENCY` | `max(2, cpus/2)` | Maximum concurrent first-time code-volume populates (functions whose unpacked code is at least 32 MB). The default is derived from the CPU count the JVM sees, so a CPU-constrained Floci container collapses it to 2 and concurrent cold starts of distinct functions serialise into pairs; set this to decouple the cap from the CPU allocation |diff --git a/docs/services/lambda.md b/docs/services/lambda.mdindex b9f6672967..6e6dfb7141 100644--- a/docs/services/lambda.md+++ b/docs/services/lambda.md@@ -375,6 +375,8 @@ These AWS Lambda operations have no handler in Floci. Calls will return `404` or| `FLOCI_SERVICES_LAMBDA_POLL_INTERVAL_MS` | `1000` | Event-source mapping poll interval (milliseconds) || `FLOCI_SERVICES_LAMBDA_ASYNC_RETRY_DELAY_SECONDS` | `60` | Wait before the first retry of a failed asynchronous invocation (seconds); the second waits twice this, `0` retries back to back || `FLOCI_SERVICES_LAMBDA_CONTAINER_IDLE_TIMEOUT_SECONDS` | `300` | Idle container shutdown timeout (seconds) |+| `FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_PER_FUNCTION` | `max(4, cpus)` | Maximum idle (warm) containers kept per function |+| `FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_TOTAL` | `0` | Maximum idle (warm) containers kept across all functions, LRU-evicted beyond it. `0` = unbounded. See the note below || `FLOCI_SERVICES_LAMBDA_REGION_CONCURRENCY_LIMIT` | `1000` | Maximum concurrent executions per region || `FLOCI_SERVICES_LAMBDA_UNRESERVED_CONCURRENCY_MIN` | `100` | Minimum unreserved capacity `PutFunctionConcurrency` must leave || `FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED` | `false` | Enable bind-mount hot-reload via `S3Bucket=hot-reload` |@@ -423,6 +425,30 @@ These AWS Lambda operations have no handler in Floci. Calls will return `404` orOnly first-time populates are gated. Warm containers, already-populated volumes, andfunctions under 32 MB are never serialised by this.+!!! note "Bounding warm containers"+ After an invocation the container stays warm so the next call skips the cold start, and is+ reaped only after `container-idle-timeout-seconds` of inactivity. Each function keeps up to+ `warm-pool-max-per-function` idle containers, but nothing limits the sum: a stack of many+ functions that fan out through streams and triggers can accumulate one warm container per+ function touched, and each runtime container holds its own memory. On a Docker Desktop with+ a modest memory allocation that is enough to have Floci OOM-killed. `ephemeral: true` avoids+ it by cold-starting every invocation, at a large latency cost.++ `warm-pool-max-total` bounds the idle containers across all functions. When a release+ would exceed it, the least-recently-used idle container of any function is stopped first,+ so the function that just ran (the most likely to run again) keeps its container:++ ```bash+ FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_TOTAL=24+ ```++ This bounds idle containers only, emulator-wide. Busy containers do not count toward it;+ their ceiling is `region-concurrency-limit`, which applies independently in each region, so+ peak container count is `warm-pool-max-total` plus the in-flight invocations across every+ active region. A cap that is smaller than the number of functions invoked in a tight loop+ trades some warm hits for the memory bound. A negative value is ignored with a warning and+ leaves the total unbounded, like `0`.+### Runtime API host overrideWhen a Lambda container starts, it calls back into Floci's Runtime API to fetchdiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex b7281b5ce9..20e1b9acb2 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -2756,6 +2756,32 @@ public interface EmulatorConfig {@WithDefault("300")int containerIdleTimeoutSeconds();+ /**+ * Maximum idle (warm) containers kept per function. A container released when the+ * function already holds this many idle ones is stopped instead of pooled.+ *+ * <p>Unset derives {@code max(4, availableProcessors())}. Values below 1 are ignored+ * with a warning.+ *+ * Env var: FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_PER_FUNCTION+ */+ Optional<Integer> warmPoolMaxPerFunction();++ /**+ * Maximum idle (warm) containers kept across all functions. When a release would push+ * the total past this, the least-recently-used idle container of any function is+ * stopped first, so the container that just ran (the most likely to run again) stays+ * warm. {@code 0} disables the bound; a negative value is ignored with a warning and+ * also leaves it unbounded. This bounds idle containers only, emulator-wide. Busy+ * containers are not counted: their ceiling is {@code region-concurrency-limit}, which+ * applies independently in each region, so peak container count is this cap plus the+ * in-flight invocations across every active region.+ *+ * Env var: FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_TOTAL+ */+ @WithDefault("0")+ int warmPoolMaxTotal();+/** Docker network to attach Lambda containers to. Empty = default bridge. */Optional<String> dockerNetwork();diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java b/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.javaindex 03f1b4bdfe..8039eee091 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java@@ -12,11 +12,14 @@ import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;+import java.time.Clock;import java.util.ArrayDeque;import java.util.ArrayList;+import java.util.Comparator;import java.util.HashMap;import java.util.List;import java.util.Map;+import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;@@ -29,7 +32,10 @@ import java.util.concurrent.TimeUnit;** Two modes controlled by {@code emulator.services.lambda.ephemeral}:* - {@code false} (default): containers are reused across invocations and evicted- * after {@code container-idle-timeout-seconds} of inactivity.+ * after {@code container-idle-timeout-seconds} of inactivity. Idle containers are+ * bounded per function by {@code warm-pool-max-per-function} and, when+ * {@code warm-pool-max-total} is set, across all functions by stopping the+ * least-recently-used idle container of any function to make room.* - {@code true}: each invocation gets a fresh container that is stopped immediately* after the invocation completes.*/@@ -42,9 +48,18 @@ public class WarmPool implements ContainerTeardown {private final LambdaRuntimeLauncher lambdaRuntimeLauncher;private final EmulatorConfig config;+ private final Clock clock;private final int maxPoolSizePerFunction;+ private final int maxIdleTotal;private final ConcurrentHashMap<String, PoolState> poolStates = new ConcurrentHashMap<>();private final ConcurrentHashMap<ContainerHandle, Lease> activeLeases = new ConcurrentHashMap<>();+ /**+ * Serialises the return-to-pool step of {@link #release} so the global idle count is+ * checked and grown atomically. Lock order is this lock, then the releasing function's+ * pool, then any other pool the LRU eviction touches. Every other path holds a single pool+ * lock and never this one, so the nesting cannot cycle.+ */+ private final Object capLock = new Object();private final ScheduledExecutorService evictionScheduler = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = new Thread(r, "warm-pool-evictor"); t.setDaemon(true); return t; });@@ -56,18 +71,50 @@ public class WarmPool implements ContainerTeardown {private record Lease(PoolState poolState, long epoch, String environmentKey) {}+ private record IdleEntry(PoolState poolState, String environmentKey,+ ArrayDeque<ContainerHandle> idle, ContainerHandle handle) {+ }+@Inject- public WarmPool(LambdaRuntimeLauncher lambdaRuntimeLauncher, EmulatorConfig config) {+ public WarmPool(LambdaRuntimeLauncher lambdaRuntimeLauncher, EmulatorConfig config, Clock clock) {this.lambdaRuntimeLauncher = lambdaRuntimeLauncher;this.config = config;- this.maxPoolSizePerFunction = DEFAULT_MAX_POOL_SIZE;+ this.clock = clock;+ this.maxPoolSizePerFunction = resolveMaxPerFunction(config);+ this.maxIdleTotal = resolveMaxTotal(config);}/** Package-private constructor for testing (empty pool, no containers to drain). */WarmPool() {this.lambdaRuntimeLauncher = null;this.config = null;+ this.clock = Clock.systemUTC();this.maxPoolSizePerFunction = DEFAULT_MAX_POOL_SIZE;+ this.maxIdleTotal = 0;+ }++ static int resolveMaxPerFunction(EmulatorConfig config) {+ Optional<Integer> configured = config.services().lambda().warmPoolMaxPerFunction();+ if (configured.isEmpty()) {+ return DEFAULT_MAX_POOL_SIZE;+ }+ int max = configured.get();+ if (max < 1) {+ LOG.warnv("Ignoring floci.services.lambda.warm-pool-max-per-function {0}: must be "+ + "at least 1; using {1}", max, DEFAULT_MAX_POOL_SIZE);+ return DEFAULT_MAX_POOL_SIZE;+ }+ return max;+ }++ static int resolveMaxTotal(EmulatorConfig config) {+ int max = config.services().lambda().warmPoolMaxTotal();+ if (max < 0) {+ LOG.warnv("Ignoring floci.services.lambda.warm-pool-max-total {0}: must be 0 (unbounded) "+ + "or positive; leaving the total unbounded", max);+ return 0;+ }+ return max;}@PostConstruct@@ -202,18 +249,29 @@ public class WarmPool implements ContainerTeardown {boolean stale;boolean returned;- synchronized (lease.poolState()) {- stale = lease.epoch() != lease.poolState().epochByEnvironment- .getOrDefault(lease.environmentKey(), 0L);- returned = !stale && idleSize(lease.poolState()) < maxPoolSizePerFunction;- if (returned) {- handle.setState(ContainerState.WARM);- handle.touchLastUsed();- lease.poolState().idleByEnvironment- .computeIfAbsent(lease.environmentKey(), ignored -> new ArrayDeque<>())- .addFirst(handle);+ List<ContainerHandle> evicted = List.of();+ synchronized (capLock) {+ synchronized (lease.poolState()) {+ stale = lease.epoch() != lease.poolState().epochByEnvironment+ .getOrDefault(lease.environmentKey(), 0L);+ returned = !stale && idleSize(lease.poolState()) < maxPoolSizePerFunction;+ if (returned) {+ if (maxIdleTotal > 0) {+ evicted = evictIdleBeyond(maxIdleTotal - 1);+ }+ handle.setState(ContainerState.WARM);+ handle.touchLastUsed(clock.millis());+ lease.poolState().idleByEnvironment+ .computeIfAbsent(lease.environmentKey(), ignored -> new ArrayDeque<>())+ .addFirst(handle);+ }}}+ for (ContainerHandle victim : evicted) {+ LOG.infov("Warm pool global cap {0} reached; stopping least-recently-used container {1} for function {2}",+ maxIdleTotal, victim.getContainerId(), victim.getFunctionName());+ stopQuietly(victim);+ }if (stale) {LOG.debugv("Pool was invalidated while container {0} was busy; stopping it",handle.getContainerId());@@ -226,6 +284,43 @@ public class WarmPool implements ContainerTeardown {}}+ /**+ * Removes idle containers, oldest {@code lastUsed} first across every function, until at+ * most {@code keep} remain, and returns the removed handles for the caller to stop outside+ * the locks. Must be called under {@link #capLock}. The snapshot and the removal take each+ * pool's lock separately, so a handle that {@link #acquire} pops in between is simply no+ * longer in its deque and is left to its new lease. A drain in that window detaches the+ * whole deque from its pool and stops its contents itself; the removal checks the deque is+ * still the live one for its environment, so a drained handle is not stopped twice.+ */+ private List<ContainerHandle> evictIdleBeyond(int keep) {+ List<IdleEntry> entries = new ArrayList<>();+ for (PoolState poolState : poolStates.values()) {+ synchronized (poolState) {+ for (Map.Entry<String, ArrayDeque<ContainerHandle>> idle : poolState.idleByEnvironment.entrySet()) {+ for (ContainerHandle handle : idle.getValue()) {+ entries.add(new IdleEntry(poolState, idle.getKey(), idle.getValue(), handle));+ }+ }+ }+ }+ int excess = entries.size() - keep;+ if (excess <= 0) {+ return List.of();+ }+ entries.sort(Comparator.comparingLong(entry -> entry.handle().getLastUsedMs()));+ List<ContainerHandle> evicted = new ArrayList<>(excess);+ for (IdleEntry entry : entries.subList(0, excess)) {+ synchronized (entry.poolState()) {+ ArrayDeque<ContainerHandle> live = entry.poolState().idleByEnvironment.get(entry.environmentKey());+ if (live == entry.idle() && live.remove(entry.handle())) {+ evicted.add(entry.handle());+ }+ }+ }+ return evicted;+ }+/*** Pushes a code update to all warm containers in the pool for the given function.* In this implementation, we drain the containers to force a fresh start with new code.@@ -319,7 +414,7 @@ public class WarmPool implements ContainerTeardown {return;}long idleTimeoutMs = config.services().lambda().containerIdleTimeoutSeconds() * 1000L;- long now = System.currentTimeMillis();+ long now = clock.millis();for (var entry : poolStates.entrySet()) {String functionName = entry.getKey();diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.javaindex ac1f85a941..6b14aec234 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.java@@ -53,7 +53,7 @@ public class ContainerHandle {public RuntimeApiServer getRuntimeApiServer() { return runtimeApiServer; }public long getCreatedAt() { return createdAt; }public long getLastUsedMs() { return lastUsedMs; }- public void touchLastUsed() { this.lastUsedMs = System.currentTimeMillis(); }+ public void touchLastUsed(long nowMs) { this.lastUsedMs = nowMs; }public ContainerState getState() { return state; }public void setState(ContainerState state) { this.state = state; }diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex b4ca4d7f81..a6c3b7e673 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -366,6 +366,8 @@ floci:poll-interval-ms: 1000async-retry-delay-seconds: 60 # FLOCI_SERVICES_LAMBDA_ASYNC_RETRY_DELAY_SECONDS - a failed Event invocation waits this before its first retry and twice this before its second (AWS: 1 min, then 2); 0 retries back to backcontainer-idle-timeout-seconds: 300+ # warm-pool-max-per-function: # FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_PER_FUNCTION - idle containers kept per function (default max(4, cpus))+ warm-pool-max-total: 0 # FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_TOTAL - idle containers kept across all functions, LRU evicted beyond it; 0 = unboundedregion-concurrency-limit: 1000unreserved-concurrency-min: 100accept-external-layer-arns: false # FLOCI_SERVICES_LAMBDA_ACCEPT_EXTERNAL_LAYER_ARNS - accept a Layers ARN from another account (content is never mounted). AWS answers these through the layer resource policy, which Floci does not model, so the default refuses them like AWS refuses a non-public one. Turn on to attach public layers such as Powertools.diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.javaindex 948913bb46..da650b1a8a 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.java@@ -11,6 +11,12 @@ import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import java.time.Clock;+import java.time.Duration;+import java.time.Instant;+import java.time.ZoneId;+import java.time.ZoneOffset;+import java.util.Optional;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;@@ -35,14 +41,60 @@ class WarmPoolTest {@Mock LambdaRuntimeLauncher containerLauncher;@Mock EmulatorConfig config;+ private final MutableClock clock = new MutableClock(Instant.parse("2026-09-29T12:00:00Z"));+private WarmPool buildPool() {+ return buildPool(Optional.empty(), 0);+ }++ private WarmPool buildPool(Optional<Integer> maxPerFunction, int maxTotal) {EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class);when(config.services()).thenReturn(services);when(services.lambda()).thenReturn(lambda);when(lambda.ephemeral()).thenReturn(false);when(lambda.containerIdleTimeoutSeconds()).thenReturn(0);- return new WarmPool(containerLauncher, config);+ when(lambda.warmPoolMaxPerFunction()).thenReturn(maxPerFunction);+ when(lambda.warmPoolMaxTotal()).thenReturn(maxTotal);+ return new WarmPool(containerLauncher, config, clock);+ }++ private static LambdaFunction function(String name) {+ LambdaFunction fn = mock(LambdaFunction.class);+ when(fn.getFunctionName()).thenReturn(name);+ return fn;+ }++ /** LRU order is by the release timestamp, so consecutive releases must land on distinct ticks. */+ private void nextMillisecond() {+ clock.advance(Duration.ofMillis(1));+ }++ private static final class MutableClock extends Clock {+ private Instant now;++ private MutableClock(Instant now) {+ this.now = now;+ }++ void advance(Duration duration) {+ now = now.plus(duration);+ }++ @Override+ public ZoneId getZone() {+ return ZoneOffset.UTC;+ }++ @Override+ public Clock withZone(ZoneId zone) {+ return this;+ }++ @Override+ public Instant instant() {+ return now;+ }}@Test@@ -451,4 +503,198 @@ class WarmPoolTest {pool.shutdown();}}++ /**+ * A drain detaches the deque from its pool and stops the contents itself. An eviction that+ * snapshotted the same deque before the drain must not remove from the orphaned object and+ * stop the container a second time. The LRU sort reads {@code getLastUsedMs()} between the+ * snapshot and the removal, which is the only hook into that window without a sleep.+ */+ @Test+ void totalCap_doesNotStopContainerAlreadyClaimedByDrain() {+ WarmPool pool = buildPool(Optional.empty(), 2);+ pool.init();++ LambdaFunction fnA = function("fn-a");+ LambdaFunction fnB = function("fn-b");+ LambdaFunction fnC = function("fn-c");+ CountDownLatch drainOnce = new CountDownLatch(1);+ ContainerHandle a1 = new ContainerHandle("cid-a1", "fn-a", null, ContainerState.WARM) {+ @Override+ public long getLastUsedMs() {+ if (drainOnce.getCount() > 0) {+ drainOnce.countDown();+ pool.drainFunction("fn-a");+ }+ return super.getLastUsedMs();+ }+ };+ ContainerHandle b1 = new ContainerHandle("cid-b1", "fn-b", null, ContainerState.WARM);+ ContainerHandle c1 = new ContainerHandle("cid-c1", "fn-c", null, ContainerState.WARM);+ when(containerLauncher.launch(any())).thenReturn(a1, b1, c1);++ ContainerHandle leasedA1 = pool.acquire(fnA);+ ContainerHandle leasedB1 = pool.acquire(fnB);+ ContainerHandle leasedC1 = pool.acquire(fnC);+ pool.release(leasedA1);+ nextMillisecond();+ pool.release(leasedB1);+ nextMillisecond();+ // Two idle entries are snapshotted, so the LRU sort compares them and the hook drains+ // fn-a before the removal step. a1 is the LRU; it must be stopped by the drain only.+ pool.release(leasedC1);++ assertEquals(0, drainOnce.getCount());+ verify(containerLauncher, times(1)).stop(a1);+ verify(containerLauncher, never()).stop(b1);+ verify(containerLauncher, never()).stop(c1);++ pool.shutdown();+ }++ @Test+ void totalCap_evictsLeastRecentlyUsedAcrossFunctions() {+ WarmPool pool = buildPool(Optional.empty(), 2);+ pool.init();++ LambdaFunction fnA = function("fn-a");+ LambdaFunction fnB = function("fn-b");+ ContainerHandle a1 = new ContainerHandle("cid-a1", "fn-a", null, ContainerState.WARM);+ ContainerHandle b1 = new ContainerHandle("cid-b1", "fn-b", null, ContainerState.WARM);+ ContainerHandle a2 = new ContainerHandle("cid-a2", "fn-a", null, ContainerState.WARM);+ when(containerLauncher.launch(any())).thenReturn(a1, b1, a2);++ // Lease all three at once so none is reused, then release oldest-first.+ ContainerHandle leasedA1 = pool.acquire(fnA);+ ContainerHandle leasedB1 = pool.acquire(fnB);+ ContainerHandle leasedA2 = pool.acquire(fnA);+ pool.release(leasedA1);+ nextMillisecond();+ pool.release(leasedB1);+ nextMillisecond();+ pool.release(leasedA2);++ // Third idle container exceeds the cap of 2: a1 is the global LRU and goes, even though+ // it belongs to the function that just released. b1 (older than a2) survives.+ verify(containerLauncher).stop(a1);+ verify(containerLauncher, never()).stop(b1);+ verify(containerLauncher, never()).stop(a2);++ when(containerLauncher.isAlive(any())).thenReturn(true);+ assertSame(a2, pool.acquire(fnA));+ assertSame(b1, pool.acquire(fnB));+ verify(containerLauncher, times(3)).launch(any());++ pool.shutdown();+ }++ @Test+ void totalCap_evictsOwnOldestContainerWhenSameFunction() {+ WarmPool pool = buildPool(Optional.empty(), 1);+ pool.init();++ LambdaFunction fn = function("fn-single");+ ContainerHandle h1 = new ContainerHandle("cid-1", "fn-single", null, ContainerState.WARM);+ ContainerHandle h2 = new ContainerHandle("cid-2", "fn-single", null, ContainerState.WARM);+ when(containerLauncher.launch(any())).thenReturn(h1, h2);++ ContainerHandle leased1 = pool.acquire(fn);+ ContainerHandle leased2 = pool.acquire(fn);+ pool.release(leased1);+ nextMillisecond();+ pool.release(leased2);++ verify(containerLauncher).stop(h1);+ verify(containerLauncher, never()).stop(h2);++ when(containerLauncher.isAlive(h2)).thenReturn(true);+ assertSame(h2, pool.acquire(fn));++ pool.shutdown();+ }++ @Test+ void perFunctionCap_rejectsExcessWithoutEvictingOtherFunctions() {+ WarmPool pool = buildPool(Optional.of(1), 10);+ pool.init();++ LambdaFunction fnA = function("fn-a");+ LambdaFunction fnB = function("fn-b");+ ContainerHandle b1 = new ContainerHandle("cid-b1", "fn-b", null, ContainerState.WARM);+ ContainerHandle a1 = new ContainerHandle("cid-a1", "fn-a", null, ContainerState.WARM);+ ContainerHandle a2 = new ContainerHandle("cid-a2", "fn-a", null, ContainerState.WARM);+ when(containerLauncher.launch(any())).thenReturn(b1, a1, a2);++ ContainerHandle leasedB1 = pool.acquire(fnB);+ ContainerHandle leasedA1 = pool.acquire(fnA);+ ContainerHandle leasedA2 = pool.acquire(fnA);+ pool.release(leasedB1);+ nextMillisecond();+ pool.release(leasedA1);+ nextMillisecond();+ pool.release(leasedA2);++ // fn-a already holds its one idle container, so a2 is the excess and is stopped. The+ // global LRU (b1) is untouched: the total cap only evicts to admit a container that the+ // per-function cap has accepted.+ verify(containerLauncher).stop(a2);+ verify(containerLauncher, never()).stop(a1);+ verify(containerLauncher, never()).stop(b1);++ pool.shutdown();+ }++ @Test+ void totalCapZero_keepsEveryIdleContainer() {+ WarmPool pool = buildPool(Optional.empty(), 0);+ pool.init();++ ContainerHandle a1 = new ContainerHandle("cid-a1", "fn-a", null, ContainerState.WARM);+ ContainerHandle b1 = new ContainerHandle("cid-b1", "fn-b", null, ContainerState.WARM);+ ContainerHandle c1 = new ContainerHandle("cid-c1", "fn-c", null, ContainerState.WARM);+ when(containerLauncher.launch(any())).thenReturn(a1, b1, c1);++ pool.release(pool.acquire(function("fn-a")));+ pool.release(pool.acquire(function("fn-b")));+ pool.release(pool.acquire(function("fn-c")));++ verify(containerLauncher, never()).stop(any());++ pool.shutdown();+ }++ @Test+ void resolveMaxPerFunction_fallsBackToDerivedDefaultBelowOne() {+ int derived = Math.max(4, Runtime.getRuntime().availableProcessors());++ assertEquals(7, WarmPool.resolveMaxPerFunction(buildConfig(Optional.of(7))));+ assertEquals(derived, WarmPool.resolveMaxPerFunction(buildConfig(Optional.of(0))));+ assertEquals(derived, WarmPool.resolveMaxPerFunction(buildConfig(Optional.empty())));+ }++ /**+ * {@code 0} is the documented opt-out, so a negative value must not quietly become it:+ * the fallback is still unbounded, but it is logged rather than mistaken for a cap.+ */+ @Test+ void resolveMaxTotal_treatsNegativeAsUnboundedWithWarning() {+ assertEquals(24, WarmPool.resolveMaxTotal(buildConfig(Optional.empty(), 24)));+ assertEquals(0, WarmPool.resolveMaxTotal(buildConfig(Optional.empty(), 0)));+ assertEquals(0, WarmPool.resolveMaxTotal(buildConfig(Optional.empty(), -1)));+ }++ private static EmulatorConfig buildConfig(Optional<Integer> maxPerFunction) {+ return buildConfig(maxPerFunction, 0);+ }++ private static EmulatorConfig buildConfig(Optional<Integer> maxPerFunction, int maxTotal) {+ EmulatorConfig emulatorConfig = mock(EmulatorConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class);+ when(emulatorConfig.services()).thenReturn(services);+ when(services.lambda()).thenReturn(lambda);+ lenient().when(lambda.warmPoolMaxPerFunction()).thenReturn(maxPerFunction);+ lenient().when(lambda.warmPoolMaxTotal()).thenReturn(maxTotal);+ return emulatorConfig;+ }}