fix(ecs): return RunTask before the task's images are pulled (#7753)

RunTask and StartTask pulled the images and started the containers inside the
request, so an unreachable registry held the call for minutes. They now answer
PROVISIONING (awsvpc) or PENDING with PENDING containers, as AWS does, and the
launch runs on a virtual-thread executor. A failed pull shows on DescribeTasks
as STOPPED / TaskFailedToStart, and a StopTask during the pull is no longer
overwritten when the containers start.

A RunTask response's PENDING containers carried the ExecuteCommandAgent as
RUNNING with a lastStartedAt; AWS reports it PENDING with neither. A start
failure after a StopTask overwrote the user's reason and UserInitiated code
with TaskFailedToStart.

AWS reports a container's memoryReservation from the moment RunTask answers.
Docker-mode responses had it from the started container; the pending
placeholders now carry it too.

ECS reports a task as pending from RunTask until it runs, through
PROVISIONING as well as PENDING. The cluster's pendingTasksCount was a
stored field nothing ever set, and the pending statistics counted only
PENDING, so both read 0 while a background launch pulled its image.

RunTask now answers before the task's images are pulled, so the test
waits for the launch to land the task instead of expecting RUNNING
straight away.

Closes #7670
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-11-09 09:31:39 -04:00
1 parent ddad6ddeb9
commit c4b22b25bd
28 files changed
+1039 -143

No files matched your search

@@ -21,6 +21,8 @@ import software.amazon.awssdk.services.ecs.model.Volume;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -47,7 +49,7 @@ class EcsEphemeralVolumeTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void nameOnlyAndEmptyHostVolumesShareFilesBetweenContainers(boolean emptyHost) {
void nameOnlyAndEmptyHostVolumesShareFilesBetweenContainers(boolean emptyHost) throws InterruptedException {
String name = "sdk-ephemeral-volume-" + UUID.randomUUID().toString().substring(0, 8);
Volume.Builder volume = Volume.builder().name("shared");
if (emptyHost) {
@@ -82,10 +84,15 @@ class EcsEphemeralVolumeTest {
Task task = started.tasks().get(0);
try {
assertThat(task.containers()).hasSize(2);
assumeTrue(task.containers().stream().allMatch(container -> container.runtimeId() != null),
"ECS Docker mode is required to check files shared by running containers");
DescribeTasksRequest describe = DescribeTasksRequest.builder()
.cluster(name).tasks(task.taskArn()).build();
// RunTask answers before the images are pulled, so whether Docker started the
// containers shows only once the launch is over.
Task launched = awaitLaunched(ecs, describe);
assertThat(launched.stopCodeAsString()).as(launched.stoppedReason())
.isNotEqualTo("TaskFailedToStart");
assumeTrue(launched.containers().stream().allMatch(container -> container.runtimeId() != null),
"ECS Docker mode is required to check files shared by running containers");
assertThat(ecs.waiter().waitUntilTasksStopped(describe,
TestFixtures.waiterOverride(Duration.ofSeconds(30)))
.matched().response()).isPresent();
@@ -106,6 +113,20 @@ class EcsEphemeralVolumeTest {
}
}
/**
* Polls until the task has left PROVISIONING and PENDING. The TasksRunning waiter cannot stand
* in: it fails on STOPPED, and this task's containers exit as soon as they have run.
*/
private static Task awaitLaunched(EcsClient ecs, DescribeTasksRequest describe) throws InterruptedException {
AtomicReference<Task> latest = new AtomicReference<>();
TestFixtures.await(() -> {
Task current = ecs.describeTasks(describe).tasks().get(0);
latest.set(current);
return !"PROVISIONING".equals(current.lastStatus()) && !"PENDING".equals(current.lastStatus());
}, describe.tasks().get(0), "the launch to finish", TimeUnit.SECONDS.toNanos(60), 500);
return latest.get();
}
private static ContainerDefinition container(String name, boolean readOnly, String command) {
return ContainerDefinition.builder().name(name).image("busybox:stable").essential(true)
.command("sh", "-c", command).stopTimeout(1)
@@ -37,6 +37,7 @@ import software.amazon.awssdk.services.ecs.model.StopTaskRequest;
import software.amazon.awssdk.services.ecs.model.Task;
import software.amazon.awssdk.services.ecs.model.TaskDefinition;
import java.time.Duration;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@@ -107,6 +108,9 @@ class EcsFargateTest {
.containerDefinitions(ContainerDefinition.builder()
.name("app")
.image("nginx:alpine")
// nginx cannot start as user 1000 on a read-only root, and the tests below
// wait for RUNNING, so the container idles until StopTask instead.
.command("sh", "-c", "trap 'exit 0' TERM QUIT; sleep 3600 & wait")
.essential(true)
.user("1000:1000")
.workingDirectory("/srv")
@@ -166,6 +170,8 @@ class EcsFargateTest {
Task task = tasks.get(0);
taskArn = task.taskArn();
// RunTask answers before the images are pulled, as AWS does: an awsvpc task is PROVISIONING.
assertThat(task.lastStatus()).isIn("PROVISIONING", "PENDING");
assertThat(task.launchType()).isEqualTo(LaunchType.FARGATE);
assertThat(task.platformVersion()).isNotBlank();
assertThat(task.platformFamily()).isEqualTo("Linux");
@@ -174,13 +180,17 @@ class EcsFargateTest {
assertThat(task.group()).isEqualTo("family:" + family);
assertThat(task.attachments()).hasSize(1);
assertThat(task.attachments().get(0).type()).isEqualTo("ElasticNetworkInterface");
assertThat(task.attachments().get(0).details())
.anySatisfy(detail -> assertThat(detail.name()).isEqualTo("privateIPv4Address"));
Task described = ecs.describeTasks(DescribeTasksRequest.builder()
DescribeTasksRequest describe = DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(taskArn)
.build()).tasks().get(0);
.build();
ecs.waiter().waitUntilTasksRunning(describe, TestFixtures.waiterOverride(Duration.ofSeconds(60)));
Task described = ecs.describeTasks(describe).tasks().get(0);
assertThat(described.attachments()).hasSize(1);
assertThat(described.attachments().get(0).details())
.anySatisfy(detail -> assertThat(detail.name()).isEqualTo("privateIPv4Address"));
assertThat(described.connectivityAsString()).isEqualTo("CONNECTED");
assertThat(described.healthStatusAsString()).isNotBlank();
assertThat(described.version()).isPositive();
@@ -228,6 +238,12 @@ class EcsFargateTest {
.build()).tasks().get(0);
try {
// ExecuteCommand reaches only a running task, and RunTask answers before the launch.
ecs.waiter().waitUntilTasksRunning(DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(plain.taskArn())
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
assertThatThrownBy(() -> ecs.executeCommand(ExecuteCommandRequest.builder()
.cluster(clusterName)
.task(plain.taskArn())
@@ -104,7 +104,7 @@ class EcsOneShotTaskLifecycleTest {
@Test
@Order(1)
@DisplayName("RunTask - task starts RUNNING")
@DisplayName("RunTask - task starts PROVISIONING or PENDING")
void runTask() {
List<Task> launched = ecs.runTask(RunTaskRequest.builder()
.cluster(clusterName)
@@ -115,7 +115,9 @@ class EcsOneShotTaskLifecycleTest {
assertThat(launched).hasSize(1);
taskArn = launched.get(0).taskArn();
assertThat(launched.get(0).lastStatus()).isEqualTo("RUNNING");
// RunTask answers before the images are pulled, as AWS does. The task runs for ~2 s, so the
// TasksStopped waiter below, not TasksRunning (which fails on STOPPED), follows it from here.
assertThat(launched.get(0).lastStatus()).isIn("PROVISIONING", "PENDING");
}
@Test
@@ -226,6 +228,16 @@ class EcsOneShotTaskLifecycleTest {
assertThat(stopping.desiredStatus()).isEqualTo("STOPPED");
assertThat(stopping.stoppedReason()).isEqualTo("test-explicit-stop");
// A stop that reaches the task while it is still launching lands asynchronously.
WaiterResponse<DescribeTasksResponse> stopped = ecs.waiter().waitUntilTasksStopped(
DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(explicitTaskArn)
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
assertThat(stopped.matched().response()).isPresent();
assertThat(stopped.matched().response().get().tasks().get(0).lastStatus()).isEqualTo("STOPPED");
}
// ── Helpers ──────────────────────────────────────────────────────────────
@@ -13,6 +13,7 @@ import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.ContainerDefinition;
import software.amazon.awssdk.services.ecs.model.CreateClusterRequest;
import software.amazon.awssdk.services.ecs.model.DeleteClusterRequest;
import software.amazon.awssdk.services.ecs.model.DescribeTasksRequest;
import software.amazon.awssdk.services.ecs.model.ExecuteCommandRequest;
import software.amazon.awssdk.services.ecs.model.LaunchType;
import software.amazon.awssdk.services.ecs.model.LogConfiguration;
@@ -29,6 +30,7 @@ import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -88,6 +90,12 @@ class EcsRunningTaskTest {
.enableExecuteCommand(true)
.count(1)
.build()).tasks().get(0).taskArn();
// RunTask answers before the images are pulled; ExecuteCommand needs the task RUNNING.
ecs.waiter().waitUntilTasksRunning(DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(taskArn)
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
}
@AfterAll
@@ -487,12 +487,18 @@ class EcsTests {
assertThat(started.get(0).taskArn()).isNotNull();
assertThat(started.get(0).containerInstanceArn()).isEqualTo(instanceArn);
// Stop the task
// Stop the task. StartTask answers before the launch, so the stop lands asynchronously;
// wait for it so the task no longer counts as running in the tests below.
if (!started.isEmpty()) {
ecs.stopTask(StopTaskRequest.builder()
.cluster(clusterName)
.task(started.get(0).taskArn())
.build());
ecs.waiter().waitUntilTasksStopped(DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(started.get(0).taskArn())
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
}
// Deregister
@@ -619,7 +625,16 @@ class EcsTests {
assertThat(task.taskArn()).isNotNull();
assertThat(task.clusterArn()).isEqualTo(cluster.clusterArn());
assertThat(task.taskDefinitionArn()).isEqualTo(taskDef.taskDefinitionArn());
assertThat(task.lastStatus()).isEqualTo("RUNNING");
// RunTask answers before the images are pulled, as AWS does; the task reaches RUNNING later.
assertThat(task.lastStatus()).isIn("PROVISIONING", "PENDING");
WaiterResponse<DescribeTasksResponse> running = ecs.waiter().waitUntilTasksRunning(
DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(task.taskArn())
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
assertThat(running.matched().response()).isPresent();
}
@Test
@@ -1127,6 +1142,15 @@ class EcsTests {
.task(taskArn)
.build());
}
// A task stopped while still launching lands STOPPED asynchronously, and a cluster with a
// task that has not stopped cannot be deleted.
if (!running.isEmpty()) {
ecs.waiter().waitUntilTasksStopped(DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(running)
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
}
Cluster deleted = ecs.deleteCluster(DeleteClusterRequest.builder()
.cluster(clusterName)